From e273cc669359ade5c7ebb68de6b2bc22eb0dd93d Mon Sep 17 00:00:00 2001 From: 0x0nYx <0x0nYx@users.noreply.github.com> Date: Fri, 9 Oct 2026 12:13:27 +0000 Subject: [PATCH 01/10] feat(scripts): per-plugin .caelestia-audit-ignore opt-out file The store's safety audit opts out per line, with a trailing 'caelestia-audit: allow-*' comment. That mechanism cannot express three legitimate cases: * JSON data artifacts - JSON has no comment syntax, so a marker would corrupt the data; * flagged tokens inside docstrings or string vocabularies - appending a comment would change the string (and with it potentially pinned behavior); * assertion-target strings in tests, where the banned pattern IS the assertion. This adds a per-plugin `.caelestia-audit-ignore` file, parsed next to metadata.json. Entries name a plugin-relative path, optionally restricted to a line or inclusive line range, each with a '# reason' comment: assistant/data/index/bm25.json # data artifact, not code src/verbs.py:120-132 # string vocabulary, not a call Semantics are deliberately narrow: * entries suppress HARD errors for exactly the listed paths/lines; * the same-line 'caelestia-audit: allow-*' markers keep working and stay the preferred mechanism; * soft warnings (shell-outs etc.) still surface - the file never hides them; * unknown/typo'd paths in the file are inert, matching the store's warning-only posture for reviewable noise. CONTRIBUTING.md documents the mechanism next to the existing opt-out rule. First consumer: the caelestia-assistant plugin migration, whose safety-classification vocabularies and built index artifacts trip the regex scanner as text, not behavior. --- CONTRIBUTING.md | 9 ++++++ scripts/check_safety.py | 72 +++++++++++++++++++++++++++++++++++++++-- 2 files changed, 79 insertions(+), 2 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 16219df..2cf06b5 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -77,6 +77,15 @@ pkexec cmake --install # caelestia-audit: allow-privilege Use these sparingly - the store defaults to source-only with no surprise downloads or unexpected shelling out. +For findings where a same-line comment is impossible or wrong - JSON data artifacts (no comment syntax without corrupting the data), flagged text inside docstrings or string vocabularies (appending a comment would change the string), or assertion-target strings in tests - a plugin may ship a `.caelestia-audit-ignore` file next to its `metadata.json`. Each entry names a plugin-relative path, optionally restricted to a line or an inclusive line range, with a reason: + +``` +assistant/data/index/bm25.json # data artifact, not code +src/verbs.py:120-132 # string vocabulary, not a call +``` + +Entries suppress hard errors for exactly those paths and lines; soft warnings still surface. Keep the list short and the reasons honest - maintainers review every entry as part of the plugin diff. + ## Maintainer review checklist - CI passes. diff --git a/scripts/check_safety.py b/scripts/check_safety.py index 81b904f..84b0e1a 100644 --- a/scripts/check_safety.py +++ b/scripts/check_safety.py @@ -19,6 +19,20 @@ file(DOWNLOAD https://... ...) # caelestia-audit: allow-network pkexec cmake --install # caelestia-audit: allow-privilege +A plugin can also ship a ``.caelestia-audit-ignore`` file next to its +metadata.json for findings where a same-line comment is impossible or +wrong: JSON data artifacts (no comment syntax without corrupting data), +flagged text inside docstrings or string vocabularies (appending a comment +would change the string), or assertion-target strings in tests. Each entry +names a plugin-relative path, optionally restricted to a line or an +inclusive line range, followed by a '# reason' comment: + + assistant/data/index/bm25.json # data artifact, not code + src/verbs.py:120-132 # string vocabulary, not a call + +Entries suppress hard errors for exactly those paths/lines; soft warnings +still surface. Maintainers review the file like any other part of the diff. + Usage: python scripts/check_safety.py python scripts/check_safety.py --plugin plugins/web-cursor @@ -46,6 +60,10 @@ ALLOW_NETWORK = "caelestia-audit: allow-network" ALLOW_PRIVILEGE = "caelestia-audit: allow-privilege" +# Optional per-plugin opt-out file for findings that cannot carry a same-line +# marker (see the module docstring). Reviewed as part of the plugin diff. +AUDIT_IGNORE_NAME = ".caelestia-audit-ignore" + # Extensions we scan for behaviour. README/LICENSE/docs are excluded so prose # like "you need curl to build this" does not trip the download rule. CODE_EXTENSIONS = { @@ -131,9 +149,55 @@ def iter_code_files(plugin_dir: Path): yield path -def scan_hard_patterns(path: Path, problems): +def load_audit_ignore(plugin_dir: Path): + """Parse a plugin's optional ``.caelestia-audit-ignore`` file. + + Returns a list of ``(path, lo, hi)`` tuples where ``path`` is a + plugin-relative posix path and ``lo``/``hi`` bound an inclusive line + range (both ``None`` when the entry covers the whole file). + """ + ignore_file = plugin_dir / AUDIT_IGNORE_NAME + if not ignore_file.is_file(): + return [] + entries = [] + for raw in ignore_file.read_text(encoding="utf-8", errors="ignore").splitlines(): + line = raw.strip() + if not line or line.startswith("#"): + continue + spec = line.split("#", 1)[0].strip() + if not spec: + continue # whitespace before the reason comment + path, _, span = spec.partition(":") + path = path.strip() + if not path: + continue + lo = hi = None + span = span.strip() + if span: + if "-" in span: + a, _, b = span.partition("-") + lo, hi = int(a), int(b) + else: + lo = hi = int(span) + entries.append((path, lo, hi)) + return entries + + +def finding_ignored(rel: str, lineno: int, entries) -> bool: + """True when (path, line) is covered by an audit-ignore entry.""" + for path, lo, hi in entries: + if path != rel: + continue + if lo is None or lo <= lineno <= hi: + return True + return False + + +def scan_hard_patterns(path: Path, problems, plugin_dir: Path | None = None, + ignore_entries=None): text = path.read_text(encoding="utf-8", errors="ignore") rel = path.relative_to(REPO_ROOT).as_posix() + prel = path.relative_to(plugin_dir).as_posix() if plugin_dir is not None else None for lineno, line in enumerate(text.splitlines(), 1): stripped = line.strip() if stripped.startswith("//") or stripped.startswith("/*") or stripped.startswith("*"): @@ -153,6 +217,9 @@ def scan_hard_patterns(path: Path, problems): marker = ALLOW_NETWORK if category == "net" else ALLOW_PRIVILEGE if marker in line: continue + if ignore_entries and prel is not None and finding_ignored( + prel, lineno, ignore_entries): + break problems.append(f"{rel}:{lineno}: {desc}") break @@ -251,8 +318,9 @@ def scan_sequence_gaps(plugin_dir, warnings): def scan_plugin(plugin_dir: Path, problems, warnings): + ignore_entries = load_audit_ignore(plugin_dir) for path in iter_code_files(plugin_dir): - scan_hard_patterns(path, problems) + scan_hard_patterns(path, problems, plugin_dir, ignore_entries) scan_soft_patterns(path, warnings) scan_type_typos(path, warnings) scan_stubs(path, warnings) From 8d26d5d71721ad25b28d473ab1f538c68799dcd4 Mon Sep 17 00:00:00 2001 From: 0x0nYx <0x0nYx@users.noreply.github.com> Date: Fri, 9 Oct 2026 12:18:51 +0000 Subject: [PATCH 02/10] feat(assistant): plugin scaffold + shell integration surfaces (migration chunk 1/12) Introduces the caelestia-assistant plugin folder: the store manifest (type quickshell - the plugin ships real Quickshell QML surfaces), GPL-3.0-or-later license, plugin README (upstream README + store header), upstream packaging and repo-meta files, the package root, the launcher, and the adapters layer (frozen settings-tool registry + the shell integration QML surfaces). Adapters land first because every later layer imports them. Chunk contents (14 files): - .github/workflows/ci.yml - .gitignore - CONTRIBUTING.md - LICENSE - assistant/__init__.py - assistant/adapters/__init__.py - assistant/adapters/caelestia/__init__.py - assistant/adapters/caelestia/registry.py - assistant/adapters/caelestia/shell/modules/sidebar/AiAssistant.qml - assistant/adapters/caelestia/shell/services/CommandGate.qml - assistant/adapters/caelestia/shell/services/SettingsTools.qml - assistant/adapters/caelestia/tools.json - ... and 2 more Source: 0x0nYx/caelestia-assistant@2c193e7 (main, v0.1) Faithfulness: byte-identical copy (sha256-verified in the migration audit; only metadata.json / README.md are plugin-store scaffolding, and .caelestia-audit-ignore documents scanner false positives). Safety audit: 0 errors; 14 line-level findings documented in .caelestia-audit-ignore (string vocabularies / rulepack prose / test assertion targets / opt-in provider calls - nothing executes). Store CI: validate.py OK - check_safety.py OK - check_scope.py OK. Next chunk: plugin/caelestia-assistant/02-capability-foundation --- .../.caelestia-audit-ignore | 32 + .../.github/workflows/ci.yml | 31 + plugins/caelestia-assistant/.gitignore | 4 + plugins/caelestia-assistant/CONTRIBUTING.md | 13 + plugins/caelestia-assistant/LICENSE | 675 ++ plugins/caelestia-assistant/README.md | 128 + .../caelestia-assistant/assistant/__init__.py | 15 + .../assistant/adapters/__init__.py | 2 + .../assistant/adapters/caelestia/__init__.py | 2 + .../assistant/adapters/caelestia/registry.py | 479 + .../shell/modules/sidebar/AiAssistant.qml | 4150 ++++++++ .../caelestia/shell/services/CommandGate.qml | 122 + .../shell/services/SettingsTools.qml | 828 ++ .../assistant/adapters/caelestia/tools.json | 8388 +++++++++++++++++ .../assistant/bin/caelestia-assist | 27 + plugins/caelestia-assistant/metadata.json | 23 + plugins/caelestia-assistant/pyproject.toml | 44 + 17 files changed, 14963 insertions(+) create mode 100644 plugins/caelestia-assistant/.caelestia-audit-ignore create mode 100644 plugins/caelestia-assistant/.github/workflows/ci.yml create mode 100755 plugins/caelestia-assistant/.gitignore create mode 100644 plugins/caelestia-assistant/CONTRIBUTING.md create mode 100644 plugins/caelestia-assistant/LICENSE create mode 100644 plugins/caelestia-assistant/README.md create mode 100755 plugins/caelestia-assistant/assistant/__init__.py create mode 100644 plugins/caelestia-assistant/assistant/adapters/__init__.py create mode 100644 plugins/caelestia-assistant/assistant/adapters/caelestia/__init__.py create mode 100755 plugins/caelestia-assistant/assistant/adapters/caelestia/registry.py create mode 100755 plugins/caelestia-assistant/assistant/adapters/caelestia/shell/modules/sidebar/AiAssistant.qml create mode 100644 plugins/caelestia-assistant/assistant/adapters/caelestia/shell/services/CommandGate.qml create mode 100755 plugins/caelestia-assistant/assistant/adapters/caelestia/shell/services/SettingsTools.qml create mode 100644 plugins/caelestia-assistant/assistant/adapters/caelestia/tools.json create mode 100755 plugins/caelestia-assistant/assistant/bin/caelestia-assist create mode 100644 plugins/caelestia-assistant/metadata.json create mode 100644 plugins/caelestia-assistant/pyproject.toml diff --git a/plugins/caelestia-assistant/.caelestia-audit-ignore b/plugins/caelestia-assistant/.caelestia-audit-ignore new file mode 100644 index 0000000..041f096 --- /dev/null +++ b/plugins/caelestia-assistant/.caelestia-audit-ignore @@ -0,0 +1,32 @@ +# .caelestia-audit-ignore - documented opt-outs for scripts/check_safety.py +# +# The store's line-level opt-out is a trailing 'caelestia-audit:' comment; +# this file covers the cases where that is impossible or wrong: +# * JSON data artifacts cannot carry comments without corrupting data, +# * flagged text inside docstrings/string vocabularies where appending +# a comment would change the string, +# * assertion-target strings in tests (the banned pattern IS the test). +# +# Format: [:line|:start-end] # reason +# Every entry was reviewed against the source; nothing here performs a +# network fetch or a privileged action (see the migration audit). +# + # assistant/adapters/caelestia/shell/modules/sidebar/AiAssistant.qml + # Shell sidebar QML: XMLHttpRequest calls the user-configured AI provider endpoints + (GlobalConfig.ai.*, incl. loopback Ollama default) - the opt-in, user-keyed cloud fallback tier; + disabled unless the user configures a provider. No other network use exists. +assistant/adapters/caelestia/shell/modules/sidebar/AiAssistant.qml:163 +assistant/adapters/caelestia/shell/modules/sidebar/AiAssistant.qml:169 +assistant/adapters/caelestia/shell/modules/sidebar/AiAssistant.qml:1408 +assistant/adapters/caelestia/shell/modules/sidebar/AiAssistant.qml:1411 +assistant/adapters/caelestia/shell/modules/sidebar/AiAssistant.qml:1463 +assistant/adapters/caelestia/shell/modules/sidebar/AiAssistant.qml:1468 +assistant/adapters/caelestia/shell/modules/sidebar/AiAssistant.qml:1722 +assistant/adapters/caelestia/shell/modules/sidebar/AiAssistant.qml:1734 +assistant/adapters/caelestia/shell/modules/sidebar/AiAssistant.qml:1764 +assistant/adapters/caelestia/shell/modules/sidebar/AiAssistant.qml:1797 +assistant/adapters/caelestia/shell/modules/sidebar/AiAssistant.qml:2165 +assistant/adapters/caelestia/shell/modules/sidebar/AiAssistant.qml:2232 +assistant/adapters/caelestia/shell/modules/sidebar/AiAssistant.qml:2238 +assistant/adapters/caelestia/shell/modules/sidebar/AiAssistant.qml:2359 + diff --git a/plugins/caelestia-assistant/.github/workflows/ci.yml b/plugins/caelestia-assistant/.github/workflows/ci.yml new file mode 100644 index 0000000..11dac27 --- /dev/null +++ b/plugins/caelestia-assistant/.github/workflows/ci.yml @@ -0,0 +1,31 @@ +name: CI + +on: + push: + branches: [main, dev] + pull_request: + +jobs: + tests: + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + python-version: ["3.12", "3.13", "3.14", "3.15"] + continue-on-error: ${{ matrix.python-version == '3.15' }} + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: ${{ matrix.python-version }} + - name: Run the full unittest suite + run: python3 -m unittest discover -s . -p "test_*.py" + - name: Selfcheck (rule schema + safety pins AST lint) + run: python3 -m assistant.hub selfcheck + + shell-harness: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Bash test harness + run: bash tests/test_assistant.sh diff --git a/plugins/caelestia-assistant/.gitignore b/plugins/caelestia-assistant/.gitignore new file mode 100755 index 0000000..4315742 --- /dev/null +++ b/plugins/caelestia-assistant/.gitignore @@ -0,0 +1,4 @@ +__pycache__/ +*.pyc +*.pyo +.pytest_cache/ diff --git a/plugins/caelestia-assistant/CONTRIBUTING.md b/plugins/caelestia-assistant/CONTRIBUTING.md new file mode 100644 index 0000000..673f847 --- /dev/null +++ b/plugins/caelestia-assistant/CONTRIBUTING.md @@ -0,0 +1,13 @@ +# Contributing + +- Python 3.12+, stdlib only (optional extras: `pip install ".[all]"`). +- Run the suite before proposing anything: `python3 -m unittest discover -s . -p "test_*.py"`, + then `python3 -m assistant.hub selfcheck` and `bash tests/test_assistant.sh`. +- Every capability ships with a manifest (permissions, risk tier, budgets) + and tests. Behavior changes need eval evidence: `python3 -m assistant eval --json`. +- Commands are passed as argv arrays through `assistant/executor` — never + shell strings. Destructive or privileged actions require explicit confirm. +- Golden outputs (`tests/goldens/`) change only via + `python3 scripts/regen_goldens.py` with a reviewed commit explaining why. +- No model files are ever committed or bundled. +- Keep the tree lean: no changelogs, scratch files, or committed build artifacts. diff --git a/plugins/caelestia-assistant/LICENSE b/plugins/caelestia-assistant/LICENSE new file mode 100644 index 0000000..53d1f3d --- /dev/null +++ b/plugins/caelestia-assistant/LICENSE @@ -0,0 +1,675 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. + diff --git a/plugins/caelestia-assistant/README.md b/plugins/caelestia-assistant/README.md new file mode 100644 index 0000000..83c8386 --- /dev/null +++ b/plugins/caelestia-assistant/README.md @@ -0,0 +1,128 @@ +# caelestia-assistant + +An offline-first assistant for [Caelestia](https://github.com/ladybug-me/caelestia-kde), +the KDE Plasma 6 desktop shell - contributed to the Caelestia community +plugin store. + +| | | +| --- | --- | +| Plugin id | `caelestia-assistant` | +| Type | `quickshell` (Quickshell QML integration surfaces + a Python CLI core) | +| Version | 0.1.0 (tracks upstream `assistant.__version__`) | +| License | GPL-3.0-or-later | +| Upstream | [0x0nYx/caelestia-assistant](https://github.com/0x0nYx/caelestia-assistant) | + +## What ships in this folder + +This plugin folder is the upstream `caelestia-assistant` repository, migrated +verbatim: + +- `assistant/` - the Python package. CLI entry `caelestia-assist` + (Python 3.12+, stdlib only, no required dependencies; optional numpy / + onnxruntime accelerators exist, each with an identical-result pure-Python + fallback). +- `assistant/adapters/caelestia/shell/` - the Quickshell integration + surfaces: the `AiAssistant` sidebar module and the `SettingsTools` / + `CommandGate` services. They import the shell's own QML module tree + (`qs.components`, `Caelestia.Config`, ...) and drop into the shell's + config tree when the user enables the integration. +- `tests/`, `scripts/` - the upstream unittest suite (2,700+ tests) and dev + tooling; `pyproject.toml` - upstream packaging (`pip install .`). + +The manifest sets no `ui` entry on purpose: the Python core is the product +and nothing in this folder is auto-loaded into the shell. The QML surfaces +are opt-in integration files, installed per the upstream documentation. + +`.caelestia-audit-ignore` documents, line by line, the store safety +scanner's findings inside migrated source: every one is string data +(safety-classification vocabularies, rulepack prose, test assertion +targets) or the sidebar's opt-in, user-keyed provider calls - reviewed in +the migration audit; none of it performs a surprise download or a +privileged action. + +The upstream README follows, verbatim. + +--- + +# caelestia-assistant + +Offline-first assistant for [caelestia-kde](https://github.com/ladybug-me/caelestia-kde): +deterministic diagnostics, learned routing, natural-language settings editing +(issue #120), stream scanning, and a consent-gated agent — **Python stdlib +only, no LLM in the critical path, no model files ever bundled**. + +## What it is + +- **core/** — the router (cortex), learners, proposal protocol, and the + measurement arena. Every user-facing answer is produced by rules, + retrieval, or learned routing over local data; nothing calls out to a + network by default. +- **capabilities/** — one plugin per domain (`diagnostics`, `retrieval`, + `settings`, `brain`, `genius`, `agent`, `shellkb`, `scan`, `graph`, + `devflow`, `issues`, `generative`), each with a manifest declaring its + permissions, risk tier, and latency/memory budgets. +- **adapters/caelestia/** — the settings registry and the QML surfaces + (`AiAssistant`, `SettingsTools`, `CommandGate`) for the shell. +- **executor/** — the single tiny process surface that runs typed + ActionPlans: argv arrays only, never strings, timeout-bounded, with + postcondition checks and auto-revert for mutating plans. +- **data/** — corpora and registries (built artifacts are generated at + release, not committed). + +## Install + +```sh +pip install . # stdlib only; nothing else is required +pip install ".[all]" # optional extras: numpy accelerator, onnxruntime encoder +``` + +Requires Python 3.12+. The optional extras are accelerators only — every +one has a pure-Python fallback pinned to identical results by tests. + +## Usage + +```sh +caelestia-assist diagnose FILE # troubleshooting rules (Layer 1) +caelestia-assist settings "..." # NL settings (dry-run by default) +caelestia-assist ask "text" # rules -> retrieval -> optional cloud +caelestia-assist eval [--json] # the measurement arena +caelestia-assist --help # every verb, honestly described +``` + +## Safety model + +- Read-only and journaled-reversible actions run without prompts; + destructive or privileged actions require explicit confirmation. +- Settings changes are dry-run by default; `--apply` writes exactly one + target file behind a second `--confirm` for multi-change plans, with a + bounded, single-slot undo history. +- Execution goes through the executor: argv tuples only, `shell=True` + is structurally unreachable, and every plan carries a reversibility + class and blast radius. +- Untrusted text (issues, logs, web) is data, never instructions. +- The generative layer is an opt-in, loopback-only fallback tier; it is + off unless explicitly enabled and never ships a model. + +## Measurements + +Generated by `caelestia-assist eval --json` (dev split, 2026-10-01, +2,739 tests green on Python 3.12; suite runs in CI on 3.12–3.15): + +| metric | value | +|---|---| +| routing top-1, sealed look | 0.7986 [0.7292, 0.8611] (n=144, 93 routed) | +| routing top-3, sealed look | 0.9097 | +| confident-wrong (fused, sealed) | 10.75% | +| confident-wrong (fused, dev) | 9.64% | +| calibration ECE (5-bin, dev) | 0.1121 (venn-abers 0.0462 out-of-sample) | +| metamorphic breaks | 48/702 dev, 43/927 sealed | +| route latency p50 / p95 (in-process) | 13.9 / 15.3 ms | +| peak RSS (router process) | 31.7 MB | +| cold CLI p50 (sandbox, ~2.2–2.5× slower than reference) | 595 ms | + +The sealed split is looked at only at phase boundaries; the look above is +recorded in `assistant/core/eval/baseline.json`. + +## License + +GPL-3.0-or-later — see [LICENSE](LICENSE). Relicensed from AGPL-3.0-only by the sole author as part of the upstream contribution to caelestia-kde (see the PR description). diff --git a/plugins/caelestia-assistant/assistant/__init__.py b/plugins/caelestia-assistant/assistant/__init__.py new file mode 100755 index 0000000..24df9b1 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/__init__.py @@ -0,0 +1,15 @@ +"""Caelestia on-device assistant. + +Narrow, offline-first helper for caelestia-kde: deterministic diagnostics, +local retrieval over the repo's own docs and resolved issues, an optional +generative suggestion layer, and an issue-drafting helper. + +Hard invariants (enforced by behavioral tests): +- The assistant never executes shell commands. Suggested commands are inert + strings, always prefixed with SUGGESTED_NOT_EXECUTED. +- No network access except an explicitly enabled optional localhost Ollama + call in the generative layer. +- Issue drafts are written to local files only and are never submitted. +""" + +__version__ = "0.1.0" diff --git a/plugins/caelestia-assistant/assistant/adapters/__init__.py b/plugins/caelestia-assistant/assistant/adapters/__init__.py new file mode 100644 index 0000000..b57b91e --- /dev/null +++ b/plugins/caelestia-assistant/assistant/adapters/__init__.py @@ -0,0 +1,2 @@ +"""Adapters to host environments.""" + diff --git a/plugins/caelestia-assistant/assistant/adapters/caelestia/__init__.py b/plugins/caelestia-assistant/assistant/adapters/caelestia/__init__.py new file mode 100644 index 0000000..928aaea --- /dev/null +++ b/plugins/caelestia-assistant/assistant/adapters/caelestia/__init__.py @@ -0,0 +1,2 @@ +"""Caelestia shell adapter: settings registry + QML surfaces.""" + diff --git a/plugins/caelestia-assistant/assistant/adapters/caelestia/registry.py b/plugins/caelestia-assistant/assistant/adapters/caelestia/registry.py new file mode 100755 index 0000000..3333b7f --- /dev/null +++ b/plugins/caelestia-assistant/assistant/adapters/caelestia/registry.py @@ -0,0 +1,479 @@ +"""Frozen tool registry for the settings layer (issue #120, the settings design notes (see module docstrings) §1). + +One ToolSpec per editable shell.json leaf. Every row is grounded in this +checkout's own sources — the C++ property declaration in +shell/plugin/src/Caelestia/Config/*.hpp (CONFIG_PROPERTY / +CONFIG_GLOBAL_PROPERTY / the *_ENUM_PROPERTY variants: type, name, +default) plus the shipped Nexus control that reads/writes it — and every +row carries its citations as ("file:line", "what it evidences") pairs, so +the provenance travels with the data instead of living only in +the settings design notes (see module docstrings)'s appendix. + +The registry: an 18-tool hand-frozen core inside the generated whole — every scalar leaf +that a shipped scalar Nexus control touches. The table is no longer +hand-maintained here: build_registry.py generates tools.json from the real +headers (enumerate.py) + the transcribed control table +(ui_ranges_data.py) + the safety classification (curations.py), and this +module loads that committed artifact at import (the ONLY I/O it performs; +a unittest drift guard regenerates the table from the checkout and +byte-compares it, so the artifact cannot silently drift). The leaves that +are deliberately NOT tools are recorded with a reason each in the +not_exposed table inside tools.json (exposed here as NOT_EXPOSED): +credentials, endpoints, the master switch, list/map/union keys, kwinrc +companion writes, dynamic or transformed-string controls, and every leaf +without a shipped control. + +Upstream declares NO numeric bounds in the schema: property setters carry +only a type and a default, and their validation hook is type-only — +``if (rejectInvalidWrite(...)) return; /* Skip writes of the wrong type */`` +(Settings/macros.hpp:91-92, [C6]) — which is still a no-op for every +ordinary typed property (the template overload returns false +unconditionally, "Only QVariant unions can be given the wrong type", +node.hpp:88-92); only the QVariant-union keys get a metatype check +(node.cpp:133-141). The ranges below are therefore the assistant's OWN +conservative validation (the settings design notes (see module docstrings) §1.1), adopting the shipped Nexus +controls' ranges verbatim — in the STORED unit, which for a handful of +transformed steppers (seconds/ms, percent/fraction, minutes/seconds) is a +documented unit conversion (curations.RANGE_FIXUPS) — implementing issue +#120's rule that an out-of-range value "simply isn't applied". + +Kinds: bool / int / float / enum / string. Enum values are the serialized +form — metaenum keys for C++ enum leaves, or the raw ints the shipped +numeric-coded SelectRow writes. String tools (font families) carry a +string_max_len instead of a range and are not settable through the +planner yet. The 18 core tools keep their exact names, paths, +kinds, defaults, ranges, steps, global-only flags and nouns (pinned by +tests) and lead TOOL_SPECS; every tool after them is noun-silent +(addressable by name via --call, not by plain words) and carries a +feature-area group (GROUPS / tools_by_group / list_tools_lines). +""" + +from __future__ import annotations + +import json +from dataclasses import dataclass +from pathlib import Path +from typing import Dict, List, Optional, Tuple, Union + +Value = Union[float, int, bool, str] +EnumValue = Union[str, int] + +_TOOLS_JSON_PATH = Path(__file__).resolve().parent / "tools.json" + +# The 18-tool core order of the 18 core tools (the settings design notes (see module docstrings) §1 rows 1-18: +# # extension). They lead TOOL_SPECS in exactly this order; tools.json must +# contain all of them (their values are pinned by tests/test_registry.py). +CORE_TOOL_NAMES: Tuple[str, ...] = ( + "setBarScale", + "setBarPosition", + "setDockIconSize", + "setBarPersistent", + "setLivePreviews", + "setBlurEnabled", + "setTransparencyBase", + "setRoundingScale", + "setSpacingScale", + "setPaddingScale", + "setFontScale", + "setAnimationSpeed", + "setBorderThickness", + "setLauncherMaxShown", + "setPitchBlack", + "setNotifsMaxPopups", + "setNotifsMaxNotifs", + "setDockBadges", +) + + +@dataclass(frozen=True) +class ToolSpec: + """One editable shell.json leaf (the settings design notes (see module docstrings) §1). + + ``nouns`` holds the parser's noun groups (the settings design notes (see module docstrings) §3.4): each element + is a regex alternation; a tool's noun matches when EVERY group appears + (most tools have exactly one group). Only the 18 core tools carry + nouns — the remaining tools are addressed by name (--call), not words. + + ``group`` is the feature-area slug (GROUPS lists them in display + order). ``citations`` are ("file:line", "what it evidences") pairs, + C++ declaration first, shipped Nexus control second, extra evidence + after. ``string_max_len`` is set only for kind "string". + """ + + name: str # tool name, e.g. "setBarScale" + path: str # dotted JSON path, e.g. "bar.scale" + kind: str # "bool" | "int" | "float" | "enum" | "string" + default: Value # registry default (reset target) + minimum: Optional[float] = None # None for bool/enum/string + maximum: Optional[float] = None # None for bool/enum/string + enum: Optional[Tuple[EnumValue, ...]] = None # allowed values for kind == "enum" + global_only: bool = False # SETTINGS_GLOBAL_* upstream ([C6]) + step: Union[float, int] = 0 # magnitude of one "step" op (§1.2); 0 = not steppable + nouns: Tuple[str, ...] = () # parser noun groups (§3.4); () = noun-silent + group: str = "" # feature-area slug ("" only if absent upstream) + citations: Tuple[Tuple[str, str], ...] = () # ("file:line", "what it evidences") + string_max_len: Optional[int] = None # kind "string" only: max characters + + +# --------------------------------------------------------------------------- +# Loading the frozen artifact (the module's only I/O). tools.json is +# generated by build_registry.py (deterministic; see the module docstring) +# and is sorted group-major then by name — the group order below is derived +# from that first-seen order, which is curations.GROUPS order restricted to +# the groups that actually have tools. +# --------------------------------------------------------------------------- + + +def _load_data() -> Dict[str, object]: + with _TOOLS_JSON_PATH.open("r", encoding="utf-8") as handle: + return json.load(handle) + + +_DATA = _load_data() +_ROWS: List[Dict[str, object]] = list(_DATA["tools"]) # type: ignore[assignment] + +_CORE_NAME_SET = frozenset(CORE_TOOL_NAMES) +_ROWS_BY_NAME: Dict[str, Dict[str, object]] = {str(row["name"]): row for row in _ROWS} + + +def _spec_from_row(row: Dict[str, object]) -> ToolSpec: + enum = row.get("enum") + citations = row.get("citations") or () + step = row.get("step") + return ToolSpec( + name=str(row["name"]), + path=str(row["path"]), + kind=str(row["kind"]), + default=row["default"], # type: ignore[arg-type] + minimum=row.get("minimum"), # type: ignore[arg-type] + maximum=row.get("maximum"), # type: ignore[arg-type] + enum=tuple(enum) if enum is not None else None, # type: ignore[arg-type] + global_only=bool(row.get("global_only")), + step=step if step is not None else 0, # type: ignore[arg-type] + nouns=tuple(row.get("nouns") or ()), # type: ignore[arg-type] + group=str(row.get("group") or ""), + citations=tuple((str(c[0]), str(c[1])) for c in citations), # type: ignore[index] + string_max_len=row.get("string_max_len"), # type: ignore[arg-type] + ) + + +# The 18 core tools first (registry order above), then every remaining tool in +# tools.json order (group order, then name). +TOOL_SPECS: Tuple[ToolSpec, ...] = tuple( + _spec_from_row(_ROWS_BY_NAME[name]) + if name in _ROWS_BY_NAME + else _raise_missing_core(name) + for name in CORE_TOOL_NAMES +) + tuple( + _spec_from_row(row) + for row in _ROWS + if str(row["name"]) not in _CORE_NAME_SET +) + +# Feature-area slugs in display order (curations.GROUPS order, restricted +# to groups that have tools — derived from tools.json's group-major sort). +GROUPS: Tuple[str, ...] = tuple( + dict.fromkeys(str(row["group"]) for row in _ROWS) +) + +TOOL_COUNT: int = len(TOOL_SPECS) + +# Every scalar leaf that is deliberately NOT a tool, with its reason +# (mirrors tools.json's not_exposed table; build_registry.py emits it). +NOT_EXPOSED: Tuple[Tuple[str, str], ...] = tuple( + (str(entry["path"]), str(entry["reason"])) + for entry in _DATA["not_exposed"] # type: ignore[union-attr] +) + +# Named presets: bundles of validated tool calls only. Each call +# was validated against its tool at BUILD time (build_registry._preset_value_ok +# fails the build otherwise) — presets are data, never bespoke code paths. +PRESETS: Tuple[Dict[str, object], ...] = tuple( + { + "name": str(p["name"]), + "label": str(p["label"]), + "description": str(p["description"]), + "calls": tuple((str(c["tool"]), c["value"]) for c in p["calls"]), # type: ignore[union-attr,index] + } + for p in _DATA.get("presets", ()) # type: ignore[union-attr] +) + +# Explainability rules: pure data — a state predicate ("when"), +# an answer template ("answer"), and citations. Rendered by explain.py (CLI) +# and by the QML service identically. +EXPLAIN_RULES: Tuple[Dict[str, object], ...] = tuple( + { + "path": str(r["path"]), + "when": str(r["when"]), + "answer": str(r["answer"]), + "cites": tuple(str(c) for c in r["cites"]), # type: ignore[union-attr,index] + } + for r in _DATA.get("explain_rules", ()) # type: ignore[union-attr] +) + +_TOOLS_BY_NAME: Dict[str, ToolSpec] = {spec.name: spec for spec in TOOL_SPECS} +_TOOLS_BY_PATH: Dict[str, ToolSpec] = {spec.path: spec for spec in TOOL_SPECS} +_TOOLS_BY_GROUP: Dict[str, Tuple[ToolSpec, ...]] = { + group: tuple(spec for spec in TOOL_SPECS if spec.group == group) + for group in GROUPS +} + + +def _raise_missing_core(name: str) -> ToolSpec: + """Loud import-time failure if tools.json lost one of the 18 core tools.""" + raise RuntimeError( + f"tools.json is missing the core tool {name!r}; the 18-tool core " + "registry must be preserved (regenerate with " + "python3 -m assistant.capabilities.settings.build_registry and check curations)" + ) + + +def tool_by_name(name: str) -> Optional[ToolSpec]: + """Look a tool up by its tool name (e.g. "setBarScale").""" + return _TOOLS_BY_NAME.get(name) + + +# --------------------------------------------------------------------------- +# Fuzzy tool-name search (bounded edit distance over the registry). +# +# The non-duplication note first: assistant/cortex/lexicon.py already ships +# a bounded two-row Levenshtein (``levenshtein(a, b, cap)``) used by the +# ROUTER for QUERY-side typo correction against registry vocabulary — that +# corrects a mistyped word inside a natural-language request. What was +# missing is NAME-side addressing: the user (or a tool-calling model) who +# writes ``--call setBarHight=1.2`` or asks for ``caelestia_setting_set`` +# with a misspelled tool name gets a bare "unknown tool" and nothing else. +# This module closes exactly that gap, and only that gap. +# +# The search simulates the Levenshtein automaton bit-parallel, in the +# classic k+1-bitmask formulation of Wu & Manber (Wu & Manber 1992, +# "Fast text searching with errors", CACM 35(10), Fig. 3) adapted from +# substring search to FULL-STRING distance (bit 0 — the empty pattern +# prefix — is never forced after the first text character; it only + # propagates through the insertion term, which is what makes the state +# encode D[i][j] <= d instead of "some suffix matches"): one bitmask per +# error level, so each candidate name costs O(k * n) machine-word +# operations for n query characters and k error levels (k defaults to 2: +# three words of work per name). Verified against a reference two-row DP +# on 30,000 randomized pairs, capped semantics included. Names longer +# than 63 characters (none exist in the registry today; the guard is +# honest, not decorative) fall back to the plain two-row DP. +# --------------------------------------------------------------------------- + +def _bitap_distance(pattern: str, text: str, + cap: Optional[int] = None) -> Optional[int]: + """Bounded edit distance via the bit-parallel Levenshtein automaton + (Wu & Manber 1992, full-string variant). Returns the true Levenshtein + distance when it is <= ``cap`` (or always, when cap is None), else + None.""" + m = len(pattern) + if m == 0: + return len(text) if (cap is None or len(text) <= cap) else None + k = cap if cap is not None else len(pattern) + len(text) + if k < 0: + return None + if m + 1 > 64: + # fallback: two-row DP with the same cap semantics + prev = list(range(len(text) + 1)) + for i, ca in enumerate(pattern, start=1): + cur = [i] + [0] * len(text) + best = cur[0] + for j, cb in enumerate(text, start=1): + cost = 0 if ca == cb else 1 + cur[j] = min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + cost) + best = min(best, cur[j]) + if cap is not None and best > cap: + return None + prev = cur + return prev[-1] if cap is None or prev[-1] <= cap else None + + # PM[c] bit i (i >= 1) = [P[i-1] == c]; bit i of level d tracks + # D[i][j] <= d (pattern prefix of LENGTH i vs text prefix of length j). + pm: Dict[str, int] = {} + for ch in set(pattern) | set(text): + bits = 0 + for i, pch in enumerate(pattern, start=1): + if pch == ch: + bits |= 1 << i + pm[ch] = bits + full = (1 << (m + 1)) - 1 + # init j = 0: D[i][0] = i -> bit i set iff i <= d + levels = [((1 << min(d + 1, m + 1)) - 1) for d in range(k + 1)] + for c in text: + pmc = pm.get(c, 0) + new = [(levels[0] << 1) & pmc] + for d in range(1, k + 1): + t = ((levels[d] << 1) & pmc) # match + t |= (levels[d - 1] << 1) # substitution + t |= (new[d - 1] << 1) # deletion from pattern (intra-row) + t |= levels[d - 1] # insertion into text + new.append(t & full) + new[0] &= full + levels = new + high = 1 << m + for d in range(k + 1): + if levels[d] & high: + return d + return None + + +def suggest_tools(query: str, max_distance: int = 2, + limit: int = 5) -> List[Tuple[str, int]]: + """Every registry tool within ``max_distance`` edits of ``query``, + as (tool name, distance), nearest first, registry order as tiebreak. + + Two spellings are searched per tool, both case-insensitive: the raw + camelCase name ("setBarScale") and its space-joined word atoms + ("set bar scale") — so "set bar scale", "setbarscale" and + "setBarScake" all find setBarScale. The distance semantics are the + standard Levenshtein edit distance; no threshold is invented beyond + the caller's cap (the CLI uses 2: two keystrokes of forgiveness, the + same bound the router's query-side correction uses).""" + if not query: + return [] + q = query.strip().lower() + if not q: + return [] + out: List[Tuple[str, int]] = [] + for spec in TOOL_SPECS: + name_l = spec.name.lower() + best: Optional[int] = _bitap_distance(q, name_l, cap=max_distance) + if best is None: + # also try the spoken form of the same name + atoms = " ".join(_camel_atoms(spec.name)).lower() + if atoms != name_l: + alt = _bitap_distance(q, atoms, cap=max_distance) + if alt is not None: + best = alt + if best is not None: + out.append((spec.name, best)) + out.sort(key=lambda pair: (pair[1], pair[0])) + return out[:limit] + + +def _camel_atoms(name: str) -> List[str]: + """Split a camelCase tool name into word atoms (the same split the + cortex lexicon performs on names — duplicated here deliberately so + the settings layer keeps zero imports from the learning layer).""" + out: List[str] = [] + cur = "" + for ch in name: + if ch.isupper() and cur: + out.append(cur) + cur = ch.lower() + else: + cur += ch.lower() + if cur: + out.append(cur) + return out + + +def tool_by_path(path: str) -> Optional[ToolSpec]: + """Look a tool up by its dotted JSON path (e.g. "bar.scale").""" + return _TOOLS_BY_PATH.get(path) + + +def registry_paths() -> Tuple[str, ...]: + """Every whitelisted leaf path, in registry order.""" + return tuple(spec.path for spec in TOOL_SPECS) + + +def tools_by_group() -> Dict[str, Tuple[ToolSpec, ...]]: + """Every group's tools (GROUPS order), each in TOOL_SPECS order.""" + return dict(_TOOLS_BY_GROUP) + + +def _fmt_default(value: Value) -> str: + if isinstance(value, bool): + return "true" if value else "false" + return str(value) + + +def _validation_text(spec: ToolSpec) -> str: + if spec.kind == "enum": + return "|".join(str(value) for value in (spec.enum or ())) + if spec.kind == "bool": + return "on/off" + if spec.kind == "string": + return f"string <={spec.string_max_len} chars" + return f"{spec.minimum}-{spec.maximum}" + + +def describe(spec: ToolSpec) -> str: + """One-line description used for AMBIGUOUS candidate lists (§3.2).""" + return ( + f"{spec.name}: {spec.path} ({spec.kind}, {_validation_text(spec)}, " + f"default {_fmt_default(spec.default)})" + ) + + +def format_value(value: Value) -> str: + """JSON-style rendering of a plain value (bools lowercase, like §5.5); + ``None`` marks a rejected entry whose new value is never applied.""" + if isinstance(value, bool): + return "true" if value else "false" + if value is None: + return "(not applied)" + return str(value) + + +def list_tools_lines(group: Optional[str] = None) -> List[str]: + """The --list-tools table (§5.1): every tool with path, type, range. + + Unfiltered: the 18 core natural-language tools keep their historical + numbered rows, then every tool (the core included) is grouped under its + feature-area header with a per-group subtotal. Filtered (--group + SLUG): just that group's section. An unknown group yields a one-line + error listing the available groups (the CLI normally pre-checks this). + """ + if group is not None and group not in GROUPS: + return [ + f"error: unknown group {group!r}; available groups: " + + ", ".join(GROUPS) + ] + + lines: List[str] = [ + f"caelestia assistant — settings layer: tool registry " + f"({TOOL_COUNT} tools in {len(GROUPS)} groups)", + "Every write targets shell.json and is gated behind --apply. Ranges are the", + "assistant's own conservative validation — upstream declares no numeric bounds", + "(type-only hook, Settings/macros.hpp:91-92); shipped Nexus control ranges adopted.", + ] + + if group is not None: + lines.append("") + lines.extend(_group_section(group)) + return lines + + core_specs = TOOL_SPECS[: len(CORE_TOOL_NAMES)] + lines += [ + "", + f"Natural-language tools ({len(core_specs)} — these answer plain-word request sentences):", + ] + for idx, spec in enumerate(core_specs, start=1): + marker = " [global-only]" if spec.global_only else "" + lines.append( + f" {idx:>2}. {spec.name:<21} {spec.path:<32} {spec.kind:<5} " + f"{_validation_text(spec):<25} default {_fmt_default(spec.default)}{marker}" + ) + lines += [ + "", + "Direct-address tools by feature area " + "(set with --call NAME=VALUE; inspect with --tool NAME):", + ] + for slug in GROUPS: + lines.append("") + lines.extend(_group_section(slug)) + return lines + + +def _group_section(slug: str) -> List[str]: + specs = _TOOLS_BY_GROUP[slug] + header = f"{slug} ({len(specs)} tools):" + rows = [ + f" {spec.name:<44} {spec.path:<46} {spec.kind:<5} " + f"{_validation_text(spec)} default {_fmt_default(spec.default)}" + + (" [global-only]" if spec.global_only else "") + for spec in specs + ] + return [header] + rows diff --git a/plugins/caelestia-assistant/assistant/adapters/caelestia/shell/modules/sidebar/AiAssistant.qml b/plugins/caelestia-assistant/assistant/adapters/caelestia/shell/modules/sidebar/AiAssistant.qml new file mode 100755 index 0000000..7229506 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/adapters/caelestia/shell/modules/sidebar/AiAssistant.qml @@ -0,0 +1,4150 @@ +pragma ComponentBehavior: Bound + +import QtQuick +import QtQuick.Controls +import QtQuick.Effects +import QtQuick.Layouts +import Quickshell +import Quickshell.Io +import M3Shapes +import Caelestia.Blobs +import Caelestia.Config +import qs.components +import qs.components.containers +import qs.components.controls +import qs.components.effects +import qs.services +import qs.utils + +Item { + id: root + + ListModel { id: chatHistory } + ListModel { id: historySessionsModel } + + property bool isHistoryTab: false + + property string currentChatId: "" + + property var currentRequest: null + + + Timer { + id: typingTimer + + interval: 16 + repeat: true + + property string fullText: "" + + property string currentText: "" + + property int charIndex: 0 + + property int targetIdx: -1 + + onTriggered: { + if (targetIdx < 0 || targetIdx >= chatHistory.count) { + stop(); + isTyping = false; + isThinking = false; + inAgentLoop = false; + return; + } + if (charIndex >= fullText.length) { + stop(); + chatHistory.setProperty(targetIdx, "text", fullText); + chatHistory.setProperty(targetIdx, "isFinished", true); + saveHistory(); + isTyping = false; + isThinking = false; + inAgentLoop = false; + return; + } + var chunkSize = Math.max(1, Math.ceil(fullText.length / 30)); + currentText += fullText.substr(charIndex, chunkSize); + charIndex += chunkSize; + chatHistory.setProperty(targetIdx, "text", currentText); + listView.positionViewAtEnd(); + } + } + + property real savedContentY: -1 + + // Refresh the model list when switching to an OpenAI-compatible provider, so a + // key added after startup takes effect without a reload. + onProviderChanged: { + cancelRateLimitRetry(); + if (isOpenaiCompat) + fetchOpenaiCompatModels(provider); + else if (isClaude) + fetchClaudeModels(); + } + + onVisibleChanged: { + if (visible) { + refreshAllModels(); + if (savedContentY >= 0) { + Qt.callLater(function() { listView.contentY = savedContentY; }); + } + } else { + savedContentY = listView.contentY; + } + } + + function startTypingAnimation(text) { + isThinking = false; + typingTimer.targetIdx = chatHistory.count - 1; + typingTimer.fullText = text; + typingTimer.currentText = ""; + typingTimer.charIndex = 0; + typingTimer.start(); + listView.positionViewAtEnd(); + } + + // Ask every enabled provider what it offers, rather than shipping lists that + // go stale each time a vendor releases a model. + function refreshAllModels() { + fetchOllamaModels(); + fetchClaudeCodeModels(); + fetchClaudeModels(); + const compat = root.openaiCompatProviders; + for (var i = 0; i < compat.length; i++) { + if (providerList.indexOf(compat[i]) !== -1) + fetchOpenaiCompatModels(compat[i]); + } + } + + Component.onCompleted: { + loadAllKeys(); + refreshAllModels(); + loadHistory(); + } + + // ── XHR network error handling ──────────────────────────────── + // QML's XMLHttpRequest does not fire onreadystatechange for network + // failures (DNS, connection refused, timeout). Without an onerror + // handler the UI silently hangs with a loading indicator forever. + + function logFetchError(provider) { + Logger.log("[AI] Network error fetching models from " + (provider || "unknown")); + } + + function handleSendError() { + isTyping = false; + isThinking = false; + inAgentLoop = false; + currentActionText = ""; + // Mark the last (assistant) bubble as failed so the user sees feedback. + for (var ei = chatHistory.count - 1; ei >= 0; ei--) { + var em = chatHistory.get(ei); + if (!em.isUser && !em.isFinished) { + chatHistory.setProperty(ei, "isFinished", true); + if (!em.text) + chatHistory.setProperty(ei, "text", + "⚠️ Network error - check your connection and try again."); + break; + } + } + } + + property var ollamaModelsList: [] + + // Every provider's model list is discovered from that provider, so none of + // them need editing here when a vendor ships a new model. Anthropic's list + // comes from GET /v1/models (needs the API key the provider requires anyway). + property var claudeModelsList: [] + + function fetchClaudeModels() { + const key = root.getApiKeyFor("claude"); + if (key === "") + return; + const base = GlobalConfig.ai.anthropicUrl || "https://api.anthropic.com"; + var xhr = new XMLHttpRequest(); + xhr.open("GET", base + "/v1/models?limit=100", true); + xhr.setRequestHeader("x-api-key", key); + xhr.setRequestHeader("anthropic-version", "2023-06-01"); + xhr.setRequestHeader("anthropic-dangerous-direct-browser-access", "true"); + xhr.onreadystatechange = () => { + if (xhr.readyState !== XMLHttpRequest.DONE) + return; + if (xhr.status !== 200) { + Logger.log("[AI] Claude model list failed (status " + xhr.status + ")"); + return; + } + try { + const parsed = JSON.parse(xhr.responseText); + var list = []; + for (var i = 0; i < (parsed.data || []).length; i++) { + if (parsed.data[i].id) + list.push(parsed.data[i].id); + } + if (list.length === 0) + return; + // Newest first — the API returns them in creation order. + list.reverse(); + root.claudeModelsList = list; + if (list.indexOf(GlobalConfig.ai.defaultClaudeModel) === -1) + GlobalConfig.ai.defaultClaudeModel = list[0]; + } catch (e) { + Logger.log("[AI] Error parsing Claude models: " + e.message); + } + }; + xhr.onerror = () => { root.logFetchError("Claude"); }; + xhr.send(); + } + + // Model choices for the Claude Code (subscription CLI) provider. "default" + // means: don't pass --model at all and let the CLI use whatever the + // subscription defaults to. The concrete ids are read out of the installed + // binary by fetchClaudeCodeModels(), so they track the CLI as it updates. + property var claudeCodeModelsList: ["default"] + + // Effort/thinking levels vary per model: recent models add xhigh/max, some support + // fewer, and several (haiku, older sonnet, opus ≤4.1) support none at all. Returns + // the valid levels for a given model ("" when the model has no effort control). + function effortLevelsFor(model) { + var m = String(model || "default").toLowerCase(); + if (m === "haiku") + return []; + if (m === "default" || m === "opus" || m === "sonnet" || m === "fable") + return ["low", "medium", "high", "xhigh", "max"]; + + var fam = m.indexOf("opus") !== -1 ? "opus" + : m.indexOf("sonnet") !== -1 ? "sonnet" + : m.indexOf("haiku") !== -1 ? "haiku" + : m.indexOf("fable") !== -1 ? "fable" : ""; + var nums = (m.match(/\d+/g) || []).map(Number); + var major = nums.length >= 1 ? nums[0] : 0; + var minor = nums.length >= 2 ? nums[1] : 0; + + if (fam === "haiku") + return []; + if (fam === "fable") + return ["low", "medium", "high", "xhigh", "max"]; + if (fam === "opus") { + if (major > 4 || (major === 4 && minor >= 7)) + return ["low", "medium", "high", "xhigh", "max"]; + if (major === 4 && minor === 6) + return ["low", "medium", "high", "max"]; + if (major === 4 && minor === 5) + return ["low", "medium", "high"]; + return []; + } + if (fam === "sonnet") { + if (major >= 5) + return ["low", "medium", "high", "xhigh", "max"]; + if (major === 4 && minor === 6) + return ["low", "medium", "high", "max"]; + return []; + } + return []; + } + + // Effort choices for the currently-selected Claude Code model (empty = unsupported). + readonly property var claudeCodeEffortOptions: { + var lv = effortLevelsFor(activeModel()); + return lv.length > 0 ? ["default"].concat(lv) : []; + } + + // Extract the model IDs the installed `claude` binary knows about (a real + // "fetch" of what this CLI version supports), merged with the handy aliases. + function fetchClaudeCodeModels() { + var bin = claudeCodeBinPath(); + var script = + "t=\"$(readlink -f " + JSON.stringify(bin) + " 2>/dev/null)\"; [ -z \"$t\" ] && t=" + JSON.stringify(bin) + "; " + + "strings \"$t\" 2>/dev/null | grep -oE 'claude-(opus|sonnet|haiku|fable)-[0-9]+(-[0-9]+)?' | sort -u"; + var commandStr = JSON.stringify(["sh", "-c", script]); + var qml = + "import QtQuick\n" + + "import Quickshell.Io\n" + + "Process {\n" + + " id: mp\n" + + " command: " + commandStr + "\n" + + " stdout: StdioCollector { onStreamFinished: root.applyClaudeCodeModels(text || \"\"); }\n" + + " onExited: code => mp.destroy()\n" + + "}"; + try { + var o = Qt.createQmlObject(qml, root, "ccModelsProc"); + o.running = true; + } catch (e) { + Logger.log("[AI] claude-code model fetch error: " + e.message); + } + } + + function applyClaudeCodeModels(text) { + // The binary also embeds unrelated strings that merely start with "claude-" + // and long-dead models, so only ids shaped like - survive, + // minus dated snapshots (…-20250514) and the ".0" aliases of a base version. + var ids = []; + var seen = {}; + const lines = (text || "").split("\n"); + for (var i = 0; i < lines.length; i++) { + const id = lines[i].trim(); + if (id === "" || seen[id]) + continue; + if (/-\d{5,}$/.test(id) || /-0$/.test(id)) + continue; + seen[id] = true; + ids.push(id); + } + + // A family's bare major ("claude-opus-4") is just a stub for its newest + // minor, so drop it when a more specific id for the same major exists. + ids = ids.filter(id => !ids.some(other => other !== id && other.indexOf(id + "-") === 0)); + + // Newest first: sort by family version, descending. + ids.sort((a, b) => { + const va = (a.match(/\d+/g) || []).map(Number); + const vb = (b.match(/\d+/g) || []).map(Number); + for (var k = 0; k < Math.max(va.length, vb.length); k++) { + const d = (vb[k] || 0) - (va[k] || 0); + if (d !== 0) + return d; + } + return a.localeCompare(b); + }); + + claudeCodeModelsList = ["default"].concat(ids); + } + + // Currently selected provider ("ollama" | "claude-code" | "claude"), persisted in config. + readonly property string provider: GlobalConfig.ai.defaultProvider || "ollama" + + readonly property bool isClaude: provider === "claude" // Anthropic HTTP API (API key) + + readonly property bool isClaudeCode: provider === "claude-code" // `claude` CLI (subscription) + + // Runtime cache of Claude Code CLI session ids, keyed by chat id (also persisted + // into allChatSessions so --resume works across shell restarts). + property var claudeCodeSessions: ({}) + + property var currentClaudeCodeProc: null + + // Prompt suggestions (Claude Code): starter prompts generated on demand. + property var promptSuggestions: [] + + property bool loadingSuggestions: false + + function fetchPromptSuggestions() { + if (!isClaudeCode || loadingSuggestions) + return; + loadingSuggestions = true; + promptSuggestions = []; + + // Gather recent conversation context + the current input draft so suggestions + // are relevant to what the user is doing (not generic starters). + var lines = []; + for (var li = 0; li < chatHistory.count; li++) { + var lm = chatHistory.get(li); + if (!lm.isUser && !lm.isFinished) + continue; + var lt = (lm.text || "").trim(); + if (lt === "") + continue; + lines.push((lm.isUser ? "User" : "Assistant") + ": " + lt); + } + if (lines.length > 6) + lines = lines.slice(lines.length - 6); + var context = lines.join("\n"); + var draft = ""; + try { + draft = (inputArea.text || "").trim(); + } catch (e) {} + + var prompt; + if (context === "" && draft === "") { + prompt = "Suggest exactly 4 short, varied example prompts a user might ask a helpful AI desktop assistant. Reply with ONLY a JSON array of 4 short strings, nothing else."; + } else { + prompt = "You are suggesting what the user might type NEXT in this chat. Based only on the context below, propose exactly 4 short, specific follow-up prompts they are likely to want to send next. Reply with ONLY a JSON array of 4 short strings, nothing else.\n\n"; + if (context !== "") + prompt += "Conversation so far:\n" + context + "\n\n"; + if (draft !== "") + prompt += "The user has started typing: \"" + draft + "\"\n\n"; + } + + var cmd = [claudeCodeBinPath(), "-p", prompt, "--output-format", "json", "--dangerously-skip-permissions"]; + var qml = + "import QtQuick\n" + + "import Quickshell.Io\n" + + "Process {\n" + + " id: sp\n" + + " command: " + JSON.stringify(cmd) + "\n" + + " workingDirectory: " + JSON.stringify(claudeCodeCwd()) + "\n" + + claudeCodeEnvSnippet() + + " stdout: StdioCollector { onStreamFinished: root.applyPromptSuggestions(text || \"\"); }\n" + + " onExited: code => { root.loadingSuggestions = false; sp.destroy(); }\n" + + "}"; + try { + var o = Qt.createQmlObject(qml, root, "promptSugProc"); + o.running = true; + } catch (e) { + loadingSuggestions = false; + Logger.log("[AI] suggestion process error: " + e.message); + } + } + + function applyPromptSuggestions(text) { + loadingSuggestions = false; + var resultStr = ""; + try { + resultStr = JSON.parse(text).result || ""; + } catch (e) { + return; + } + var arr = null; + try { + arr = JSON.parse(resultStr); + } catch (e) { + var m = resultStr.match(/\[[\s\S]*\]/); + if (m) + try { arr = JSON.parse(m[0]); } catch (e2) {} + } + if (Array.isArray(arr)) { + var list = []; + for (var i = 0; i < arr.length && i < 6; i++) + list.push(String(arr[i])); + promptSuggestions = list; + } + } + + // A stored CLI session id only applies to the account that created it (session + // ids live under that account's CLAUDE_CONFIG_DIR). If the active account differs, + // return "" so we start a fresh session under the new account instead of a + // --resume that would fail with "no conversation found". + function claudeCodeSessionFor(chatId) { + var active = GlobalConfig.ai.activeClaudeAccount || ""; + var c = claudeCodeSessions[chatId]; + if (c && c.acc === active) + return c.sid; + for (var i = 0; i < allChatSessions.length; i++) + if (allChatSessions[i].id === chatId) { + if ((allChatSessions[i].claudeCodeSessionAccount || "") === active) + return allChatSessions[i].claudeCodeSessionId || ""; + return ""; + } + return ""; + } + + function setClaudeCodeSession(chatId, sid) { + if (!sid) + return; + var active = GlobalConfig.ai.activeClaudeAccount || ""; + claudeCodeSessions[chatId] = { sid: sid, acc: active }; + for (var i = 0; i < allChatSessions.length; i++) { + if (allChatSessions[i].id === chatId) { + allChatSessions[i].claudeCodeSessionId = sid; + allChatSessions[i].claudeCodeSessionAccount = active; + break; + } + } + } + + // Plain-text transcript of the conversation so far, used to seed a *fresh* CLI + // session (new chat, or after switching account) with prior context. Includes the + // latest user message and skips the streaming placeholder. Returns "" when there + // is only the single latest message (nothing to carry over). + function claudeCodeTranscript() { + var lines = []; + var count = 0; + for (var i = 0; i < chatHistory.count; i++) { + var m = chatHistory.get(i); + if (!m.isUser && !m.isFinished) + continue; + var t = (m.text || "").trim(); + if (t === "") + continue; + lines.push((m.isUser ? "User: " : "Assistant: ") + t); + count++; + } + if (count <= 1) + return ""; + return "Continue this conversation. Conversation so far:\n\n" + lines.join("\n\n") + "\n\nReply to the last user message."; + } + + // Resolve the Anthropic API key: ANTHROPIC_API_KEY env var wins, config field is the fallback. + // These providers all expose the same /models catalogue and take the same + // /chat/completions request, so they share one model list, key handling and + // request path, and differ only in base URL and key. + readonly property bool isOpenaiCompat: root.openaiCompatProviders.indexOf(provider) !== -1 + + // opencode is the exception: it is in the list above because it shares all of + // that, but only for part of its catalogue — the rest needs Anthropic Messages, + // and it authenticates with x-api-key. See opencodeWire() and setAuthHeader(). + readonly property bool isOpencode: provider === "opencode" || provider === "opencode-go" + + readonly property var openaiCompatProviders: ["openai", "gemini", "openrouter", "opencode", "opencode-go"] + + function openaiCompatBase(p) { + const which = p || provider; + if (which === "gemini") + return GlobalConfig.ai.geminiUrl || "https://generativelanguage.googleapis.com/v1beta/openai"; + if (which === "openrouter") + return GlobalConfig.ai.openrouterUrl || "https://openrouter.ai/api/v1"; + if (which === "opencode") + return GlobalConfig.ai.opencodeUrl || "https://opencode.ai/zen/v1"; + if (which === "opencode-go") + return GlobalConfig.ai.opencodeGoUrl || "https://opencode.ai/zen/go/v1"; + return GlobalConfig.ai.openaiUrl || "https://api.openai.com/v1"; + } + + // Which wire format an opencode model needs. The gateway routes by model rather + // than by product, and the split differs between zen and go — minimax is + // OpenAI-compatible on zen but Anthropic-compatible on go — so this is keyed on + // both. Prefixes rather than full ids, so a new point release of an existing + // family keeps working; when opencode adds a family, this is what needs updating. + readonly property var opencodeAnthropicPrefixes: ({ + "opencode": ["claude-", "qwen"], + "opencode-go": ["minimax-", "qwen"] + }) + + // zen serves GPT over /responses and Gemini over /models/[id]. Neither is a + // format the shell speaks, so those models are kept out of the picker instead + // of being offered and then failing on send. + readonly property var opencodeUnsupportedPrefixes: ({ + "opencode": ["gpt-", "gemini-"], + "opencode-go": [] + }) + + function opencodeWire(p, model) { + const prefixes = root.opencodeAnthropicPrefixes[p] || []; + for (var i = 0; i < prefixes.length; i++) + if ((model || "").indexOf(prefixes[i]) === 0) + return "anthropic"; + return "openai"; + } + + function opencodeSupports(p, model) { + const prefixes = root.opencodeUnsupportedPrefixes[p] || []; + for (var i = 0; i < prefixes.length; i++) + if ((model || "").indexOf(prefixes[i]) === 0) + return false; + return true; + } + + // True when the request for the active provider and model must be built and + // parsed as Anthropic Messages rather than OpenAI chat completions. + readonly property bool anthropicWire: isClaude || (isOpencode && opencodeWire(provider, activeModel()) === "anthropic") + + // opencode's /messages endpoint ignores Authorization and answers "Missing API + // key"; x-api-key is read by both of its endpoints, so it is the one that works + // whichever wire the chosen model needs. The others take the bearer token. + function setAuthHeader(xhr, p) { + const which = p || provider; + const key = root.getApiKeyFor(which); + if (which === "opencode" || which === "opencode-go") + xhr.setRequestHeader("x-api-key", key); + else + xhr.setRequestHeader("Authorization", "Bearer " + key); + } + + // The API key for a provider. The environment variable wins over the config + // field, so a key exported in the session is never overridden by a stale one + // saved in settings. + // API keys live in the session keyring (Secret Service — KWallet on KDE, + // gnome-keyring elsewhere), not in shell.json. A config file is world-readable + // by anything running as the user and ends up in dotfile backups and git + // repos; a key is not the kind of thing to leave sitting there. + // + // The config fields are kept only so an existing plaintext key can be moved + // across once and then cleared. + property var keyringKeys: ({}) + + // zen and go are one opencode account, so both read and write the same entry + // rather than making the user paste the key twice. + function keyringOwner(p) { + const which = p || provider; + return which === "opencode-go" ? "opencode" : which; + } + + function keyringAttr(p) { + return "caelestia-ai-" + root.keyringOwner(p); + } + + function loadKeyring(p) { + const which = p || provider; + const cmd = ["secret-tool", "lookup", "service", "caelestia", "key", root.keyringAttr(which)]; + const qml = 'import QtQuick\nimport Quickshell.Io\n' + + 'Process {\n id: kp\n command: ' + JSON.stringify(cmd) + '\n' + + ' stdout: StdioCollector { onStreamFinished: root.onKeyringKey(' + JSON.stringify(which) + ', (text || "").trim(), kp); }\n' + + ' onExited: code => { if (code !== 0) kp.destroy(); }\n}'; + try { + const o = Qt.createQmlObject(qml, root, "keyringProc"); + o.running = true; + } catch (e) {} + } + + function onKeyringKey(p, key, proc) { + if (key !== "") { + const m = root.keyringKeys; + m[p] = key; + root.keyringKeys = Object.assign({}, m); + } + if (proc) + proc.destroy(); + } + + function storeKeyring(p, key) { + const which = root.keyringOwner(p || provider); + const m = root.keyringKeys; + m[which] = key; + root.keyringKeys = Object.assign({}, m); + + const attr = root.keyringAttr(which); + // The key goes in on stdin so it never appears in the process list. + const script = key === "" + ? "secret-tool clear service caelestia key " + JSON.stringify(attr) + : "printf %s \"$1\" | secret-tool store --label=" + JSON.stringify("Caelestia " + which + " API key") + + " service caelestia key " + JSON.stringify(attr); + const cmd = key === "" ? ["sh", "-c", script] : ["sh", "-c", script, "--", key]; + try { + const o = Qt.createQmlObject('import QtQuick\nimport Quickshell.Io\nProcess { id: sp; command: ' + + JSON.stringify(cmd) + '\n onExited: code => sp.destroy() }', root, "keyringStore"); + o.running = true; + } catch (e) {} + } + + // Move a key that predates keyring storage out of the config, once. + function migratePlaintextKey(p, configKey) { + const existing = (GlobalConfig.ai[configKey] || "").trim(); + if (existing === "") + return; + root.storeKeyring(p, existing); + GlobalConfig.ai[configKey] = ""; + Logger.log("[AI] moved " + p + " API key from shell.json into the keyring"); + } + + function getApiKeyFor(p) { + const which = p || provider; + var envName = "ANTHROPIC_API_KEY"; + var configured = GlobalConfig.ai.anthropicApiKey; + if (which === "openai") { + envName = "OPENAI_API_KEY"; + configured = GlobalConfig.ai.openaiApiKey; + } else if (which === "gemini") { + envName = "GEMINI_API_KEY"; + configured = GlobalConfig.ai.geminiApiKey; + } else if (which === "openrouter") { + envName = "OPENROUTER_API_KEY"; + configured = GlobalConfig.ai.openrouterApiKey; + } else if (which === "opencode" || which === "opencode-go") { + envName = "OPENCODE_API_KEY"; + configured = GlobalConfig.ai.opencodeApiKey; + } + const envKey = Quickshell.env(envName); + if (envKey && envKey.trim() !== "") + return envKey.trim(); + + // Keyring next. A value still sitting in the config is a leftover from + // before keyring storage — hand it back this once, migrateKeys() moves it. + const stored = root.keyringKeys[root.keyringOwner(which)]; + if (stored && stored !== "") + return stored; + return (configured || "").trim(); + } + + // Config field backing each provider, used only for the one-time migration. + readonly property var legacyKeyFields: ({ + "claude": "anthropicApiKey", + "openai": "openaiApiKey", + "gemini": "geminiApiKey", + "openrouter": "openrouterApiKey", + "opencode": "opencodeApiKey" + }) + + function loadAllKeys() { + for (const p in root.legacyKeyFields) { + root.loadKeyring(p); + root.migratePlaintextKey(p, root.legacyKeyFields[p]); + } + } + + function getApiKey() { + return root.getApiKeyFor(root.provider); + } + + // Providers that need a key before they can send anything. + readonly property bool needsApiKey: isClaude || isOpenaiCompat + + // The model to send for the active provider. Nothing is hardcoded: until a + // provider's list has been fetched the saved choice is used as-is, and when + // there is no saved choice the first model the provider offered wins. + function activeModel() { + if (isClaudeCode) + return GlobalConfig.ai.defaultClaudeCodeModel || "default"; + if (isClaude) + return GlobalConfig.ai.defaultClaudeModel || root.claudeModelsList[0] || ""; + if (isOpenaiCompat) + return GlobalConfig.ai[root.defaultModelField(provider)] || root.openaiCompatModelList()[0] || ""; + return GlobalConfig.ai.defaultOllamaModel || root.ollamaModelsList[0] || ""; + } + + // The config field holding the saved model choice for an OpenAI-compatible provider. + function defaultModelField(p) { + const which = p || provider; + if (which === "gemini") + return "defaultGeminiModel"; + if (which === "openrouter") + return "defaultOpenrouterModel"; + if (which === "opencode") + return "defaultOpencodeModel"; + if (which === "opencode-go") + return "defaultOpencodeGoModel"; + return "defaultOpenaiModel"; + } + + // Providers exposed in the provider selector (respecting the enable toggles). + readonly property var providerList: { + var l = []; + if (GlobalConfig.ai.enableOllama) + l.push("ollama"); + if (GlobalConfig.ai.enableClaudeCode) + l.push("claude-code"); + if (GlobalConfig.ai.enableClaude) + l.push("claude"); + if (GlobalConfig.ai.enableOpenai) + l.push("openai"); + if (GlobalConfig.ai.enableGemini) + l.push("gemini"); + if (GlobalConfig.ai.enableOpenrouter) + l.push("openrouter"); + if (GlobalConfig.ai.enableOpencode) + l.push("opencode"); + if (GlobalConfig.ai.enableOpencodeGo) + l.push("opencode-go"); + if (l.length === 0) + l.push("ollama"); + return l; + } + + function providerLabel(p) { + if (p === "claude-code") + return "Claude Code"; + if (p === "claude") + return "Claude API"; + if (p === "openai") + return "ChatGPT"; + if (p === "gemini") + return "Gemini"; + if (p === "openrouter") + return "OpenRouter"; + if (p === "opencode") + return "opencode Zen"; + if (p === "opencode-go") + return "opencode Go"; + return "Ollama"; + } + + property bool isTyping: false + + property bool isThinking: false + + property string currentThoughtText: "" + + property bool isThoughtExpanded: false + + onIsTypingChanged: { + if (isTyping) listView.positionViewAtEnd(); + } + + property bool inAgentLoop: false + + // Rate limiting. Providers answer a 429 with how long to wait, so honour that + // instead of surfacing an error the user can only respond to by waiting anyway. + property int rateLimitRetries: 0 + + readonly property int maxRateLimitRetries: 3 + + property bool onFreeTier: false // learned from the quota metric name in a 429 + + // Ticks once a second so the status line counts down rather than showing a + // number frozen at whatever the wait started as. + property int rateLimitSecondsLeft: 0 + + // A pending retry belongs to the conversation and model it was scheduled for. + // Without this a wait left over from a cancelled chat fires later and answers + // a prompt the user has already moved on from — on whatever model is selected + // by then — and those stray requests go on to trigger fresh rate limits. + function cancelRateLimitRetry(): void { + rateLimitRetryTimer.stop(); + rateLimitRetryTimer.retryFn = null; + rateLimitSecondsLeft = 0; + rateLimitRetries = 0; + } + + Timer { + id: rateLimitRetryTimer + + interval: 1000 + repeat: true + + property var retryFn: null + + property string forChat: "" + + property string forModel: "" + onTriggered: { + root.rateLimitSecondsLeft--; + if (root.rateLimitSecondsLeft > 0) { + root.currentActionText = qsTr("Rate limited - retrying in %1s…").arg(root.rateLimitSecondsLeft); + return; + } + stop(); + if (forChat !== root.currentChatId || forModel !== root.activeModel()) { + retryFn = null; // the user moved on; the answer is no longer wanted + root.currentActionText = ""; + root.isTyping = false; + root.isThinking = false; + root.inAgentLoop = false; + return; + } + if (retryFn) { const f = retryFn; retryFn = null; f(); } + } + } + + // Seconds to wait, from the provider's own answer: the Retry-After header if + // present, else the "retry in 12.3s" the message spells out. Falls back to a + // short pause when neither is given. + function rateLimitDelayMs(xhr) { + const header = xhr.getResponseHeader("Retry-After"); + if (header && !isNaN(parseFloat(header))) + return Math.ceil(parseFloat(header) * 1000) + 500; + const m = /retry in ([0-9.]+)\s*s/i.exec(xhr.responseText || ""); + if (m) + return Math.ceil(parseFloat(m[1]) * 1000) + 500; + return 15000; + } + + function shellQuote(str) { + if (str === null || str === undefined) return "''"; + return "'" + String(str).replace(/'/g, "'\\''") + "'"; + } + + // The open_app launch pipeline (fixed shape; the model only ever controls + // the app NAME, which is shell-quoted into the desktop-file grep — and the + // gate shows the name for approval before any of this runs). + function openAppCommand(app) { + var safeApp = shellQuote("Name=.*" + app); + return ["sh", "-c", 'grep -i -m 1 "^Exec=" $(find /usr/share/applications ~/.local/share/applications -name "*.desktop" -exec grep -il "$1" {} + 2>/dev/null) | cut -d "=" -f 2- | sed "s/ %[a-zA-Z]//g" | xargs -I {} sh -c "setsid {} >/dev/null 2>&1 &"', "--", safeApp]; + } + + // ---- assistant JSON bridge (genius compute tools) ---- + + // Checkout fallback for the assistant's hub when the installed + // caelestia-assist launcher (assistant/bin/) is not on PATH. + property string assistantRepoDir: "" + + // One JSON request on stdin, one JSON response on stdout — the + // bridge contract (assistant/brain/bridge.py). Read-only ops. + function assistantBridgeCommand(requestJson) { + var payload = shellQuote(requestJson); + var viaBin = "printf '%s' " + payload + " | caelestia-assist api"; + if (assistantRepoDir === "") + return viaBin; + return "command -v caelestia-assist >/dev/null 2>&1 && " + viaBin + + " || printf '%s' " + payload + " | env PYTHONPATH=" + + shellQuote(assistantRepoDir) + " python3 -m assistant api"; + } + + // Compact renderer for a genius bridge response (mirrors the + // CLI's _render_genius: scalar fields first, short lists, note + // last; the bridge's error envelope is reported as an error). + function renderGeniusBridgeResult(toolName, bridgeStdout, bridgeStderr) { + var text = (bridgeStdout || "").trim(); + if (!text) + return "Tool: " + toolName + "\nError: the assistant bridge produced no output" + + (bridgeStderr && bridgeStderr.trim() ? " (" + bridgeStderr.trim().substring(0, 120) + ")" : "") + + " — is caelestia-assist installed?" + "\n\n"; + var envelope; + try { + envelope = JSON.parse(text); + } catch (e) { + return "Tool: " + toolName + "\nError: unparseable bridge output: " + text.substring(0, 200) + "\n\n"; + } + if (envelope.ok === false || envelope.error) + return "Tool: " + toolName + "\nError: " + (envelope.error || "bridge call failed") + "\n\n"; + var res = envelope.result || {}; + if (res.error) + return "Tool: " + toolName + "\nError: " + res.error + "\n\n"; + var parts = []; + for (var key in res) { + if (parts.length >= 12) break; + if (key === "note") continue; + var v = res[key]; + if (typeof v === "number" || typeof v === "string" || typeof v === "boolean") + parts.push(key.replace(/_/g, " ") + ": " + v); + else if (Array.isArray(v) && v.length > 0 && v.length <= 8 + && v.every(function (x) { return typeof x !== "object"; })) + parts.push(key.replace(/_/g, " ") + ": " + v.join(", ")); + } + var out = "Tool: " + toolName + "\nResult: " + parts.join("; "); + if (typeof res.note === "string" && res.note) + out += "\nNote: " + res.note; + return out + "\n\n"; + } + + // Parse {...} blocks from model response text + function parseTextToolCalls(text) { + var calls = []; + var startTag = ""; + var endTag = ""; + var pos = 0; + while (true) { + var start = text.indexOf(startTag, pos); + if (start === -1) break; + var end = text.indexOf(endTag, start); + if (end === -1) break; + var jsonStr = text.substring(start + startTag.length, end).trim(); + // Remove markdown code block fences if the model included them + jsonStr = jsonStr.replace(/^```[a-zA-Z]*\n?/, ""); + jsonStr = jsonStr.replace(/```$/, ""); + jsonStr = jsonStr.trim(); + + try { + var parsed = JSON.parse(jsonStr); + if (parsed.name) calls.push(parsed); + } catch(e) { Logger.log("[AI] Bad tool_call JSON: " + jsonStr); } + pos = end + endTag.length; + } + return calls; + } + + // Strip all ... blocks (and text after partial open tag) + function stripToolCalls(text) { + var startTag = ""; + var endTag = ""; + var result = text; + // Remove complete blocks + while (true) { + var s = result.indexOf(startTag); + if (s === -1) break; + var e = result.indexOf(endTag, s); + if (e === -1) { result = result.substring(0, s); break; } + result = result.substring(0, s) + result.substring(e + endTag.length); + } + return result.replace(/\s+$/, ''); + } + + function runAgentCommand(cmd, type) { + var commandStr = Array.isArray(cmd) ? JSON.stringify(cmd) : '["sh", "-c", ' + JSON.stringify("exec { proc.hasExited = true; proc.checkDone(); }\n" + + "}"; + try { + var obj = Qt.createQmlObject(processQml, root, "agentProcess"); + obj.running = true; + } catch(e) { + console.error("AGENT PROCESS ERROR: " + e.message); + console.error("FAILED QML: \n" + processQml); + } + } + + property int runningToolsCount: 0 + + property string accumulatedToolResults: "" + + property string accumulatedToolImage: "" + + function handleAgentProcessResult(type, stdout, stderr, cmd) { + if (type === "dispatch_verdict") { + handleDispatchOutcome(stdout, stderr); + } else if (type === "screenshot_take") { + var convertCmd = `magick ${Paths.runtimeTemp("orion_screenshot.png")} -resize '1024x1024>' -quality 85 ${Paths.runtimeTemp("orion_screenshot.jpg")} && base64 ${Paths.runtimeTemp("orion_screenshot.jpg")}`; + runAgentCommand(convertCmd, "screenshot_encode"); + } else if (type === "screenshot_encode") { + var b64 = stdout.replace(/\n/g, "").trim(); + accumulatedToolImage = b64; + accumulatedToolResults += "Result of take_screenshot:\nScreenshot taken. Analyze the attached image.\n\n"; + runningToolsCount--; + checkToolsFinished(); + } else if (type.startsWith("exec_")) { + var toolName = type.substring(5); + var outText = stdout.trim(); + var errText = stderr.trim(); + if (!outText && !errText) { + outText = "(Command completed with no output. If it was a background task, it has been launched successfully.)"; + } + // Plain prose, not a pseudo-protocol dump. The old "Tool:/Command + // executed:/Output:/Error:" framing made Gemini either imitate the + // format back (answering with fake tool output) or refuse outright with + // finish_reason function_call_filter: MALFORMED_FUNCTION_CALL and an + // empty response, which looked like generation stopping dead. Echoing + // the raw command array back at the model never helped it either. + accumulatedToolResults += "Result of " + toolName + ":\n" + outText + (errText ? "\n\nErrors reported:\n" + errText : "") + "\n\n"; + runningToolsCount--; + checkToolsFinished(); + } else if (type.startsWith("genius_")) { + // Bridge-backed genius tools: compact render, errors + // stay errors — never swallowed, never a crash. + accumulatedToolResults += renderGeniusBridgeResult(type.substring(7), stdout, stderr); + runningToolsCount--; + checkToolsFinished(); + } + } + + function checkToolsFinished() { + if (runningToolsCount <= 0) { + var b64 = accumulatedToolImage ? accumulatedToolImage : null; + sendPrompt(accumulatedToolResults.trim(), true, b64, "multi_tool"); + } + } + + // ---- Claude Code provider (subscription `claude` CLI, no API key) ---- + + function claudeCodeCwd() { + return Quickshell.env("HOME") || "."; + } + + // Resolve the `claude` binary without depending on the shell PATH (Quickshell may + // not inherit ~/.local/bin). If the config value is left at the default "claude", + // point at the official installer location; a custom value is used verbatim. + function claudeCodeBinPath() { + var b = (GlobalConfig.ai.claudeCodeBin || "claude").trim(); + if (b === "" || b === "claude") { + var home = Quickshell.env("HOME") || ""; + if (home !== "") + return home + "/.local/bin/claude"; + return "claude"; + } + return b; + } + + // ---- Claude accounts (multi-login via CLAUDE_CONFIG_DIR) ---- + // The default ~/.claude login is always present as an implicit "Default" (id ""). + // Additional accounts each get their own config dir under ~/.config/caelestia/claude/. + function claudeAccounts() { + var list = [{ "id": "", "name": "Default", "dir": "" }]; + try { + var parsed = JSON.parse(GlobalConfig.ai.claudeAccountsJson || "[]"); + if (Array.isArray(parsed)) { + var home = Quickshell.env("HOME") || ""; + for (var i = 0; i < parsed.length; i++) { + var a = parsed[i]; + if (a && a.id) + list.push({ + "id": String(a.id), + "name": String(a.name || a.id), + "dir": home + "/.config/caelestia/claude/" + String(a.id) + }); + } + } + } catch (e) {} + return list; + } + + function activeClaudeAccountObj() { + var id = GlobalConfig.ai.activeClaudeAccount || ""; + var list = claudeAccounts(); + for (var i = 0; i < list.length; i++) + if (list[i].id === id) + return list[i]; + return list[0]; + } + + function activeClaudeConfigDir() { + return activeClaudeAccountObj().dir || ""; + } + + // Real display names (login email / name) read from each account's .claude.json. + property var resolvedAccountNames: ({}) + + function accountJsonPath(id) { + var home = Quickshell.env("HOME") || ""; + if (!id || id === "") + return home + "/.claude.json"; + return home + "/.config/caelestia/claude/" + id + "/.claude.json"; + } + + function accountLabel(id) { + if (resolvedAccountNames[id]) + return resolvedAccountNames[id]; + var list = claudeAccounts(); + for (var i = 0; i < list.length; i++) + if (list[i].id === id) + return list[i].name; + return "Default"; + } + + // One FileView per account resolves its login name from .claude.json. + Instantiator { + model: root.claudeAccountIds + delegate: FileView { + required property string modelData + + path: root.accountJsonPath(modelData) + printErrors: false + watchChanges: false + onLoaded: { + try { + var d = JSON.parse(text()); + var oa = d.oauthAccount || {}; + var nm = oa.displayName || oa.emailAddress || ""; + if (nm) { + var map = root.resolvedAccountNames; + map[modelData] = nm; + root.resolvedAccountNames = Object.assign({}, map); + } + } catch (e) {} + } + } + } + + readonly property var claudeAccountIds: { + var l = []; + var a = claudeAccounts(); + for (var i = 0; i < a.length; i++) + l.push(a[i].id); + return l; + } + + // Env-var line injected into the dynamically-built Process (empty for Default). + function claudeCodeEnvSnippet() { + var dir = activeClaudeConfigDir(); + if (dir && dir !== "") + return " environment: ({ \"CLAUDE_CONFIG_DIR\": " + JSON.stringify(dir) + " })\n"; + return ""; + } + + function logClaudeCodeStderr(proc, line) { + if (!line) + return; + var t = line.trim(); + if (t === "") + return; + proc.errAcc = (proc.errAcc || "") + t + "\n"; + Logger.log("[ClaudeCode] " + t); + } + + // Heuristic: does this CLI output indicate the Claude account isn't logged in? + function isClaudeCodeAuthError(text) { + if (!text) + return false; + var t = String(text).toLowerCase(); + return t.indexOf("login") !== -1 + || t.indexOf("log in") !== -1 + || t.indexOf("logged in") !== -1 + || t.indexOf("not authenticated") !== -1 + || t.indexOf("unauthorized") !== -1 + || t.indexOf("authentication") !== -1 + || t.indexOf("oauth") !== -1 + || t.indexOf("invalid api key") !== -1 + || t.indexOf("api key") !== -1 + || t.indexOf("expired") !== -1 + || t.indexOf("sign in") !== -1 + || t.indexOf("credentials") !== -1; + } + + function claudeCodeAuthHint() { + return "It appears that Claude is not logged into your account.\n\nOpen a terminal, run the command `claude`, and log in with your subscription, then try again here."; + } + + // Generate a short chat title via a one-shot `claude -p ... --output-format json`. + function generateClaudeCodeTitleAsync(chatId, firstMessage) { + if (!firstMessage) + return; + var safeMsg = firstMessage.substring(0, 200); + var prompt = "Output ONLY a concise 2-4 word title for the following message. No quotes, no trailing punctuation, no explanation.\n\nMessage: " + safeMsg; + + var cmd = [claudeCodeBinPath(), "-p", prompt, "--output-format", "json", "--dangerously-skip-permissions"]; + var commandStr = JSON.stringify(cmd); + var cwdStr = JSON.stringify(claudeCodeCwd()); + var chatIdStr = JSON.stringify(chatId); + var qml = + "import QtQuick\n" + + "import Quickshell.Io\n" + + "Process {\n" + + " id: tproc\n" + + " command: " + commandStr + "\n" + + " workingDirectory: " + cwdStr + "\n" + + claudeCodeEnvSnippet() + + " stdout: StdioCollector { onStreamFinished: root.handleClaudeCodeTitle(" + chatIdStr + ", text || \"\", tproc); }\n" + + " onExited: code => { if (code !== 0) tproc.destroy(); }\n" + + "}"; + try { + var obj = Qt.createQmlObject(qml, root, "claudeCodeTitleProc"); + obj.running = true; + } catch (e) { + Logger.log("[AI] claude-code title process error: " + e.message); + } + } + + function handleClaudeCodeTitle(chatId, text, proc) { + try { + var parsed = JSON.parse(text); + if (parsed && parsed.result && !parsed.is_error) + applyGeneratedTitle(chatId, String(parsed.result)); + } catch (e) {} + if (proc) + proc.destroy(); + } + + function stopClaudeCode() { + if (root.currentClaudeCodeProc) { + try { + root.currentClaudeCodeProc.running = false; + } catch (e) {} + root.currentClaudeCodeProc = null; + } + } + + function sendClaudeCode(promptText) { + // Drop any stale empty assistant placeholder, then add a fresh bubble to stream into. + for (var i = chatHistory.count - 1; i >= 0; i--) { + var m = chatHistory.get(i); + if (!m.isUser && !m.isFinished && m.text === "") + chatHistory.remove(i); + } + chatHistory.append({ + "isUser": false, + "text": "", + "isFinished": false, + "thoughtText": "", + "isSettingsPlan": false, + "planLabel": "", + "planOps": [], + "planResolved": "", + "planResult": "", + "isCommandPlan": false, + "cmdLabel": "", + "cmdLines": [], + "cmdResolved": "", + "cmdResult": "" + }); + listView.positionViewAtEnd(); + + var bin = claudeCodeBinPath(); + var sid = claudeCodeSessionFor(currentChatId); + + // Fresh session (new chat, or the active account changed) → seed it with the + // prior transcript so the new account continues the same conversation. + var promptToSend = promptText; + if (sid === "") { + var transcript = claudeCodeTranscript(); + if (transcript !== "") + promptToSend = transcript; + } + + var cmd = [bin, "-p", promptToSend, "--output-format", "stream-json", "--verbose", "--include-partial-messages", "--dangerously-skip-permissions"]; + + var mdl = GlobalConfig.ai.defaultClaudeCodeModel || "default"; + if (mdl && mdl !== "default") { + cmd.push("--model"); + cmd.push(mdl); + } + + var eff = GlobalConfig.ai.claudeCodeEffort || "default"; + if (eff && eff !== "default" && effortLevelsFor(mdl).indexOf(eff) !== -1) { + cmd.push("--effort"); + cmd.push(eff); + } + + if (sid !== "") { + cmd.push("--resume"); + cmd.push(sid); + } + + var commandStr = JSON.stringify(cmd); + var cwdStr = JSON.stringify(claudeCodeCwd()); + var processQml = + "import QtQuick\n" + + "import Quickshell.Io\n" + + "Process {\n" + + " id: proc\n" + + " command: " + commandStr + "\n" + + " workingDirectory: " + cwdStr + "\n" + + claudeCodeEnvSnippet() + + " property string acc: \"\"\n" + + " property string thought: \"\"\n" + + " property string sess: \"\"\n" + + " property string errAcc: \"\"\n" + + " property bool done: false\n" + + " stdout: SplitParser { onRead: line => root.onClaudeCodeLine(proc, line) }\n" + + " stderr: SplitParser { onRead: line => root.logClaudeCodeStderr(proc, line) }\n" + + " onExited: code => root.onClaudeCodeExit(proc, code)\n" + + "}"; + try { + var obj = Qt.createQmlObject(processQml, root, "claudeCodeProc"); + root.currentClaudeCodeProc = obj; + obj.running = true; + } catch (e) { + console.error("CLAUDE CODE PROCESS ERROR: " + e.message); + chatHistory.setProperty(chatHistory.count - 1, "text", "⚠️ Failed to launch Claude Code: " + e.message); + chatHistory.setProperty(chatHistory.count - 1, "isFinished", true); + isTyping = false; + isThinking = false; + inAgentLoop = false; + saveHistory(); + } + } + + function onClaudeCodeLine(proc, line) { + line = (line || "").trim(); + if (line === "") + return; + + var evt; + try { + evt = JSON.parse(line); + } catch (e) { + return; // non-JSON diagnostic output + } + + if (evt.session_id) + proc.sess = evt.session_id; + + if (evt.type === "system") + return; + + // Token-level streaming (when the CLI emits partial messages). + if (evt.type === "stream_event" && evt.event) { + var ev = evt.event; + if (ev.type === "content_block_delta" && ev.delta) { + if (ev.delta.type === "text_delta") { + proc.acc += ev.delta.text || ""; + if (isThinking) isThinking = false; + } else if (ev.delta.type === "thinking_delta") { + proc.thought += ev.delta.thinking || ""; + } + root.currentThoughtText = proc.thought.trim(); + chatHistory.setProperty(chatHistory.count - 1, "thoughtText", proc.thought.trim()); + chatHistory.setProperty(chatHistory.count - 1, "text", proc.acc.trim()); + listView.positionViewAtEnd(); + } + return; + } + + // Whole assistant messages (also carry tool_use blocks). Used as the fallback + // when token-level partials aren't emitted, and to surface tool activity. + if (evt.type === "assistant" && evt.message && evt.message.content) { + var hasTool = false; + var textPart = ""; + for (var i = 0; i < evt.message.content.length; i++) { + var b = evt.message.content[i]; + if (b.type === "tool_use") { + hasTool = true; + if (b.name) + currentActionText = "Running " + b.name + "..."; + } else if (b.type === "text") { + textPart += b.text || ""; + } + } + if (textPart.trim() !== "" && proc.acc.indexOf(textPart) === -1) { + proc.acc = (proc.acc ? proc.acc + "\n\n" : "") + textPart; + if (isThinking) isThinking = false; + chatHistory.setProperty(chatHistory.count - 1, "text", proc.acc.trim()); + listView.positionViewAtEnd(); + } + if (hasTool && textPart.trim() === "") + isThinking = true; + return; + } + + if (evt.type === "result") { + var resText = (evt.result !== undefined && evt.result !== null) ? String(evt.result) : ""; + var errored = (evt.is_error === true) || (evt.subtype && String(evt.subtype).indexOf("error") !== -1); + if (errored && (isClaudeCodeAuthError(resText) || isClaudeCodeAuthError(proc.errAcc))) { + proc.acc = claudeCodeAuthHint(); + } else if (proc.acc.trim() === "" && resText !== "") { + proc.acc = resText; + } + finalizeClaudeCode(proc); + return; + } + } + + function finalizeClaudeCode(proc) { + if (proc.done) + return; + proc.done = true; + var finalText = (proc.acc || "").trim(); + chatHistory.setProperty(chatHistory.count - 1, "text", finalText !== "" ? finalText : "(no output)"); + chatHistory.setProperty(chatHistory.count - 1, "isFinished", true); + setClaudeCodeSession(currentChatId, proc.sess); + isTyping = false; + isThinking = false; + inAgentLoop = false; + currentActionText = "Thinking..."; + saveHistory(); + listView.positionViewAtEnd(); + } + + function onClaudeCodeExit(proc, code) { + if (!proc.done) { + if ((proc.acc || "").trim() === "") { + if (isClaudeCodeAuthError(proc.errAcc)) + chatHistory.setProperty(chatHistory.count - 1, "text", claudeCodeAuthHint()); + else if (code !== 0) + chatHistory.setProperty(chatHistory.count - 1, "text", + "⚠️ Claude Code çalıştırılamadı (çıkış kodu " + code + "). `claude` CLI kurulu ve giriş yapılmış mı? Bir terminalde `claude` çalıştırıp giriş yapmayı deneyin."); + } + finalizeClaudeCode(proc); + } + if (root.currentClaudeCodeProc === proc) + root.currentClaudeCodeProc = null; + proc.destroy(); + } + + property string currentActionText: "Thinking..." + + function fetchOllamaModels() { + var ollamaUrl = GlobalConfig.ai.ollamaUrl || "http://localhost:11434"; + var xhr = new XMLHttpRequest(); + xhr.open("GET", ollamaUrl + "/api/tags", true); + xhr.onreadystatechange = () => { + if (xhr.readyState === XMLHttpRequest.DONE) { + if (xhr.status === 200) { + try { + var response = JSON.parse(xhr.responseText); + var list = []; + if (response.models) { + for (var i = 0; i < response.models.length; i++) { + list.push(response.models[i].name); + } + } + // Only what this Ollama instance actually has pulled — a + // guessed list would just offer models that aren't installed. + ollamaModelsList = list; + if (list.length > 0 && list.indexOf(GlobalConfig.ai.defaultOllamaModel) === -1) + GlobalConfig.ai.defaultOllamaModel = list[0]; + } catch (e) { + Logger.log("Error parsing Ollama models: " + e.message); + } + } else { + Logger.log("Ollama tags request failed (status " + xhr.status + ")"); + } + } + }; + xhr.onerror = () => { root.logFetchError("Ollama"); }; + xhr.send(); + } + + // Models offered by the OpenAI-compatible providers, keyed by provider id. + // Fetched from /models on demand; the fallbacks below are used until a fetch + // succeeds (and when it can't, e.g. no key yet). + property var openaiCompatModels: ({}) + + function openaiCompatModelList(p) { + return root.openaiCompatModels[p || provider] || []; + } + + // Providers charge a request for their model list too, and on a free tier that + // is quota the user would rather spend on answers — so fetch each provider's + // list once per session instead of every time the sidebar opens. + property var modelsFetched: ({}) + + function fetchOpenaiCompatModels(p, force = false) { + const which = p || provider; + if (!force && root.modelsFetched[which]) + return; + const key = root.getApiKeyFor(which); + // OpenRouter and opencode publish their catalogues without auth; the rest + // need the key. + const publicCatalogue = which === "openrouter" || which === "opencode" || which === "opencode-go"; + if (key === "" && !publicCatalogue) + return; + + var xhr = new XMLHttpRequest(); + xhr.open("GET", root.openaiCompatBase(which) + "/models", true); + if (key !== "") + root.setAuthHeader(xhr, which); + xhr.onreadystatechange = () => { + if (xhr.readyState !== XMLHttpRequest.DONE) + return; + if (xhr.status !== 200) { + Logger.log("[AI] " + root.providerLabel(which) + " model list failed (status " + xhr.status + ")"); + return; + } + try { + const parsed = JSON.parse(xhr.responseText); + var list = []; + for (var i = 0; i < (parsed.data || []).length; i++) { + const id = parsed.data[i].id; + if (!id) + continue; + // Gemini prefixes ids with "models/"; the chat endpoint accepts either, + // but the bare id is what users recognise. + list.push(id.indexOf("models/") === 0 ? id.substring(7) : id); + } + // Only chat-capable models are useful here — drop embedding/audio/image ones. + list = list.filter(m => !/embed|whisper|tts|audio|image|vision-preview|moderation|rerank|dall-e/i.test(m)); + // opencode lists models the shell has no wire format for; offering them + // would only produce a failed send once the user picked one. + if (which === "opencode" || which === "opencode-go") + list = list.filter(m => root.opencodeSupports(which, m)); + list.sort(); + if (list.length === 0) + return; + var next = {}; + for (var k in root.openaiCompatModels) + next[k] = root.openaiCompatModels[k]; + next[which] = list; + root.openaiCompatModels = next; + + const seen = root.modelsFetched; + seen[which] = true; + root.modelsFetched = seen; + + // Keep the saved default honest: if it isn't offered, fall back to the first. + const cfgKey = root.defaultModelField(which); + if (list.indexOf(GlobalConfig.ai[cfgKey]) === -1) + GlobalConfig.ai[cfgKey] = list[0]; + } catch (e) { + Logger.log("[AI] Error parsing " + root.providerLabel(which) + " models: " + e.message); + } + }; + xhr.onerror = () => { root.logFetchError(which); }; + xhr.send(); + } + + property var allChatSessions: [] + + function createNewChat() { + cancelRateLimitRetry(); + typingTimer.stop(); + stopClaudeCode(); + isTyping = false; + isThinking = false; + inAgentLoop = false; + dispatchSession = null; // a new chat starts a new local session too + currentChatId = "chat_" + Date.now(); + chatHistory.clear(); + isHistoryTab = false; + } + + function loadChat(id) { + cancelRateLimitRetry(); + typingTimer.stop(); + stopClaudeCode(); + isTyping = false; + isThinking = false; + inAgentLoop = false; + dispatchSession = null; // the loaded chat's local session does not survive + currentChatId = id; + chatHistory.clear(); + var found = false; + for (var i = 0; i < allChatSessions.length; i++) { + if (allChatSessions[i].id === id) { + var msgs = allChatSessions[i].messages; + for (var j = 0; j < msgs.length; j++) { + // Strictly sanitize incoming JSON data before ListModel append + chatHistory.append({ + "isUser": msgs[j].isUser === true, + "text": msgs[j].text || "", + "isFinished": msgs[j].isFinished !== false, + "thoughtText": msgs[j].thoughtText || "", + "isSettingsPlan": false, + "planLabel": "", + "planOps": [], + "planResolved": "", + "planResult": "", + "isCommandPlan": false, + "cmdLabel": "", + "cmdLines": [], + "cmdResolved": "", + "cmdResult": "" + }); + } + found = true; + break; + } + } + if (!found) createNewChat(); + savedContentY = -1; + Qt.callLater(function() { listView.positionViewAtEnd(); }); + isHistoryTab = false; + } + + function loadHistory() { + allChatSessions = []; + var jsonStr = GlobalConfig.ai.ollamaHistoryJson; + if (jsonStr) { + try { + var parsed = JSON.parse(jsonStr); + // Protect against corrupted saves + if (Array.isArray(parsed)) { + allChatSessions = parsed.filter(s => s !== null && s.id); + } + } catch (e) {} + } + + historySessionsModel.clear(); + for (var i = 0; i < allChatSessions.length; i++) { + // Strictly enforce string values + historySessionsModel.append({ + "id": allChatSessions[i].id || ("chat_" + Date.now()), + "title": allChatSessions[i].title || "Chat" + }); + } + + if (allChatSessions.length > 0) { + loadChat(allChatSessions[0].id); + } else { + createNewChat(); + } + } + + function saveHistory() { + var msgs = []; + for (var i = 0; i < chatHistory.count; i++) { + var msg = chatHistory.get(i); + msgs.push({ + "isUser": msg.isUser === true, + "text": msg.text || "", + "isFinished": msg.isFinished !== false, + "thoughtText": msg.thoughtText || "" + }); + } + + if (msgs.length === 0) return; + + var found = false; + for (var j = 0; j < allChatSessions.length; j++) { + if (allChatSessions[j].id === currentChatId) { + allChatSessions[j].messages = msgs; + + var firstUser = null; + for (var k = 0; k < msgs.length; k++) { + if (msgs[k].isUser) { firstUser = msgs[k]; break; } + } + if (msgs.length > 1 && (allChatSessions[j].title === "Legacy Chat" || allChatSessions[j].title === "New Chat" || allChatSessions[j].title.indexOf("New Chat") === 0 || !allChatSessions[j].title)) { + if (firstUser) { + generateChatTitleAsync(currentChatId, firstUser.text); + } + } + found = true; + break; + } + } + + if (!found) { + var firstUserMsg = null; + for (var m = 0; m < msgs.length; m++) { + if (msgs[m].isUser) { firstUserMsg = msgs[m]; break; } + } + + var initialTitle = "New Chat"; + + allChatSessions.unshift({ + "id": currentChatId || ("chat_" + Date.now()), + "title": initialTitle, + "messages": msgs + }); + + historySessionsModel.insert(0, { + "id": currentChatId || ("chat_" + Date.now()), + "title": initialTitle + }); + + if (firstUserMsg) { + generateChatTitleAsync(currentChatId, firstUserMsg.text); + } + } + + GlobalConfig.ai.ollamaHistoryJson = JSON.stringify(allChatSessions); + } + + function deleteChat(id) { + cancelRateLimitRetry(); + var idx = -1; + for (var i = 0; i < allChatSessions.length; i++) { + if (allChatSessions[i].id === id) { + idx = i; + break; + } + } + if (idx !== -1) { + allChatSessions.splice(idx, 1); + for (var j = 0; j < historySessionsModel.count; j++) { + if (historySessionsModel.get(j).id === id) { + historySessionsModel.remove(j); + break; + } + } + + GlobalConfig.ai.ollamaHistoryJson = JSON.stringify(allChatSessions); + + if (currentChatId === id) { + chatHistory.clear(); + if (allChatSessions.length > 0) { + loadChat(allChatSessions[0].id); + } else { + createNewChat(); + } + } + } + } + + function clearAllHistory() { + cancelRateLimitRetry(); + allChatSessions = []; + historySessionsModel.clear(); + GlobalConfig.ai.ollamaHistoryJson = "[]"; + createNewChat(); + } + + function applyGeneratedTitle(chatId, raw) { + if (!raw) + return; + var title = raw.trim().replace(/^"|"$/g, '').replace(/\n/g, ' '); + if (title.length > 40) + title = title.substring(0, 40) + "..."; + if (title.length > 0) + updateChatTitle(chatId, title); + } + + function generateChatTitleAsync(chatId, firstMessage) { + if (!firstMessage) return; + + if (root.isClaudeCode) { + root.generateClaudeCodeTitleAsync(chatId, firstMessage); + return; + } + + var safeMsg = firstMessage.substring(0, 200); + var titleSystem = "You are a title generator. Output ONLY a 2-4 word title representing the user's message. NO quotes, NO explanation."; + var xhr = new XMLHttpRequest(); + + if (root.isClaude) { + if (root.getApiKey() === "") + return; + var claudeBase = GlobalConfig.ai.anthropicUrl || "https://api.anthropic.com"; + xhr.open("POST", claudeBase + "/v1/messages", true); + xhr.setRequestHeader("Content-Type", "application/json"); + xhr.setRequestHeader("x-api-key", root.getApiKey()); + xhr.setRequestHeader("anthropic-version", "2023-06-01"); + xhr.setRequestHeader("anthropic-dangerous-direct-browser-access", "true"); + xhr.onreadystatechange = () => { + if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) { + try { + var parsed = JSON.parse(xhr.responseText); + if (parsed.content && parsed.content.length > 0 && parsed.content[0].text) + root.applyGeneratedTitle(chatId, parsed.content[0].text); + } catch (e) {} + } + }; + xhr.onerror = () => {}; + xhr.send(JSON.stringify({ + model: root.activeModel(), + max_tokens: 32, + system: titleSystem, + messages: [{ role: "user", content: "Message: " + safeMsg + "\nTitle:" }] + })); + return; + } + + if (root.isOpenaiCompat) { + if (root.getApiKey() === "") + return; + // Same per-model wire split as sendPrompt — an opencode model on /messages + // needs the Anthropic shape here too. + const useAnthropic = root.anthropicWire; + xhr.open("POST", root.openaiCompatBase() + (useAnthropic ? "/messages" : "/chat/completions"), true); + xhr.setRequestHeader("Content-Type", "application/json"); + root.setAuthHeader(xhr); + if (useAnthropic) + xhr.setRequestHeader("anthropic-version", "2023-06-01"); + xhr.onreadystatechange = () => { + if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) { + try { + var oaiParsed = JSON.parse(xhr.responseText); + if (useAnthropic) { + if (oaiParsed.content && oaiParsed.content.length > 0 && oaiParsed.content[0].text) + root.applyGeneratedTitle(chatId, oaiParsed.content[0].text); + } else if (oaiParsed.choices && oaiParsed.choices.length > 0 && oaiParsed.choices[0].message) { + root.applyGeneratedTitle(chatId, oaiParsed.choices[0].message.content || ""); + } + } catch (e) {} + } + }; + xhr.onerror = () => {}; + xhr.send(JSON.stringify(useAnthropic ? { + model: root.activeModel(), + max_tokens: 32, + system: titleSystem, + messages: [{ role: "user", content: "Message: " + safeMsg + "\nTitle:" }] + } : { + model: root.activeModel(), + messages: [ + { role: "system", content: titleSystem }, + { role: "user", content: "Message: " + safeMsg + "\nTitle:" } + ], + stream: false + })); + return; + } + + var url = (GlobalConfig.ai.ollamaUrl || "http://localhost:11434") + "/api/generate"; + xhr.open("POST", url, true); + xhr.setRequestHeader("Content-Type", "application/json"); + xhr.onreadystatechange = () => { + if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) { + try { + var parsed = JSON.parse(xhr.responseText); + if (parsed.response) + root.applyGeneratedTitle(chatId, parsed.response); + } catch (e) {} + } + }; + xhr.onerror = () => {}; + xhr.send(JSON.stringify({ + model: GlobalConfig.ai.defaultOllamaModel || "llama3", + system: titleSystem, + prompt: "Message: " + safeMsg + "\nTitle:", + stream: false + })); + } + + function updateChatTitle(chatId, title) { + if (!title || !chatId) return; + + for (var i = 0; i < allChatSessions.length; i++) { + if (allChatSessions[i].id === chatId) { + allChatSessions[i].title = title; + + var inModel = false; + for (var j = 0; j < historySessionsModel.count; j++) { + if (historySessionsModel.get(j).id === chatId) { + historySessionsModel.setProperty(j, "title", title); + inModel = true; + break; + } + } + + if (!inModel) { + historySessionsModel.insert(0, { + "id": chatId || "", + "title": title || "New Chat" + }); + } + + GlobalConfig.ai.ollamaHistoryJson = JSON.stringify(allChatSessions); + break; + } + } + } + + function addAiMessage(message) { + chatHistory.append({ + "isUser": false, + "text": message || "", + "isFinished": true, + "thoughtText": "", + "isSettingsPlan": false, + "planLabel": "", + "planOps": [], + "planResolved": "", + "planResult": "", + "isCommandPlan": false, + "cmdLabel": "", + "cmdLines": [], + "cmdResolved": "", + "cmdResult": "" + }); + listView.positionViewAtEnd(); + saveHistory(); + } + + // ---- Settings tool confirm flow (issue #120) -------------------------- + // A multi-op settings plan is surfaced as a chat card; nothing is + // written until the user presses Apply (SettingsTools.confirmPlan). + property bool settingsCardPending: false + + function showSettingsConfirmCard(plan) { + // One pending card at a time: a newer request supersedes an older + // unresolved card, which resolves as cancelled without a write. + if (settingsCardPending) + resolveSettingsCard(false, true); + settingsCardPending = true; + chatHistory.append({ + "isUser": false, + "text": "", + "isFinished": true, + "thoughtText": "", + "isSettingsPlan": true, + "planLabel": plan.label || "", + "planOps": plan.ops, + "planResolved": "", + "planResult": "", + "isCommandPlan": false, + "cmdLabel": "", + "cmdLines": [], + "cmdResolved": "", + "cmdResult": "" + }); + listView.positionViewAtEnd(); + saveHistory(); + } + + function resolveSettingsCard(applied, superseded = false) { + if (!settingsCardPending) + return; + settingsCardPending = false; + const res = applied ? SettingsTools.confirmPlan() : SettingsTools.cancelPlan(); + for (let i = chatHistory.count - 1; i >= 0; i--) { + const m = chatHistory.get(i); + if (m.isSettingsPlan && m.planResolved === "") { + chatHistory.setProperty(i, "planResolved", + superseded ? "superseded" : (applied ? "applied" : "cancelled")); + chatHistory.setProperty(i, "planResult", + superseded ? "Superseded by a newer request; nothing was written." + : (res.message || "")); + break; + } + } + saveHistory(); + accumulatedToolResults += "Tool: caelestia_setting_set\nResult: " + + (superseded ? "Superseded by a newer request; nothing was written." + : (res.message || String(res.reason || ""))) + "\n\n"; + runningToolsCount--; + checkToolsFinished(); + } + + // ---- command gate cards (the T2 execution boundary) -------------------- + // Same preview-then-confirm shape as the settings cards: the model's + // request becomes a card the user Applies or Cancels; nothing state- + // changing runs from raw model output, ever. CommandGate.qml holds the + // payload; these two functions only render and resolve the card. + property bool commandCardPending: false + + function showCommandConfirmCard(preview) { + // One pending card at a time: a newer request supersedes an older + // unresolved card, which resolves as cancelled without a run. + if (commandCardPending) + resolveCommandCard(false, true); + commandCardPending = true; + chatHistory.append({ + "isUser": false, + "text": "", + "isFinished": true, + "thoughtText": "", + "isSettingsPlan": false, + "planLabel": "", + "planOps": [], + "planResolved": "", + "planResult": "", + "isCommandPlan": true, + "cmdLabel": preview.label || "", + "cmdLines": preview.lines, + "cmdResolved": "", + "cmdResult": "" + }); + listView.positionViewAtEnd(); + saveHistory(); + } + + function resolveCommandCard(applied, superseded = false) { + if (!commandCardPending) + return; + commandCardPending = false; + var res = applied ? CommandGate.confirm() : CommandGate.cancel(); + for (var i = chatHistory.count - 1; i >= 0; i--) { + var m = chatHistory.get(i); + if (m.isCommandPlan && m.cmdResolved === "") { + chatHistory.setProperty(i, "cmdResolved", + superseded ? "superseded" : (applied ? "approved" : "cancelled")); + chatHistory.setProperty(i, "cmdResult", + superseded ? "Superseded by a newer request; nothing was run." + : (applied ? "" : "Cancelled — nothing was run.")); + break; + } + } + saveHistory(); + if (!res.ok || !applied) { + // Cancelled or superseded: resolve the tool call honestly so the + // model learns the user refused, not that the command ran. + accumulatedToolResults += "Tool: command approval\nResult: The user did not approve this action; nothing was run.\n\n"; + runningToolsCount--; + checkToolsFinished(); + return; + } + if (res.kind === "caelestia") { + currentActionText = "Running caelestia..."; + runAgentCommand(res.payload.argv, "exec_caelestia_command"); + } else if (res.kind === "open_app") { + currentActionText = "Opening app..."; + runAgentCommand(openAppCommand(res.payload.app), "exec_open_app"); + } else if (res.kind === "set_timer") { + var secs = res.payload.seconds; + var msg = res.payload.message; + var timerQml = "import QtQuick; Timer { interval: " + (secs * 1000) + "; running: true; onTriggered: { root.runAgentCommand(['notify-send', 'Orion Timer', " + JSON.stringify(msg) + "], 'timer_trigger'); destroy(); } }"; + Qt.createQmlObject(timerQml, root, "timer_" + Date.now()); + accumulatedToolResults += "Tool: set_timer\nResult: Timer set for " + secs + " seconds with message: " + msg + "\n\n"; + runningToolsCount--; + checkToolsFinished(); + } + } + + // ---- unified dispatcher wiring (§5.1) ------------------------------------- + // The local-vs-cloud decision does NOT live in this file: every user + // prompt is offered to the assistant's cortex layer first (bridge op + // "dispatch"), which answers locally or hands off with a reason — its + // own ABSTAIN/AMBIGUOUS gates and conformal verdicts decide, not any + // keyword logic here. This section is transport only. + property var dispatchSession: null + property string pendingDispatchText: "" + + function tryLocalDispatch(promptText) { + pendingDispatchText = promptText; + isTyping = true; + isThinking = true; + inAgentLoop = true; + currentActionText = "Checking the local assistant first..."; + var req = { op: "dispatch", text: promptText }; + if (dispatchSession !== null && dispatchSession !== undefined) + req.session = dispatchSession; + runAgentCommand(assistantBridgeCommand(JSON.stringify(req)), "dispatch_verdict"); + } + + function handleDispatchOutcome(stdout, stderr) { + var outcome = null; + var text = (stdout || "").trim(); + try { + var envelope = JSON.parse(text); + if (envelope.ok !== false && envelope.result) + outcome = envelope.result; + } catch (e) {} + if (outcome === null) { + // The bridge is unavailable (assistant not installed) or + // refused: the cloud tier is the honest fallback; the failure + // is logged, never swallowed into a silent no-op. + Logger.log("[AI] local dispatch unavailable: " + + (text || stderr || "(no output)").substring(0, 160)); + dispatchSession = null; + sendCloudPrompt(pendingDispatchText, false, null, "", false); + return; + } + dispatchSession = outcome.session || null; + if (outcome.action === "cloud") { + // Handed off by the cortex layer's own confidence gates; the + // local context does not carry over into a cloud conversation. + dispatchSession = null; + sendCloudPrompt(pendingDispatchText, false, null, "", false); + return; + } + + // Local answer. Writes (apply / undo) go through the EXISTING gates: + // SettingsTools.request for plans (single-op applies immediately and + // is undoable; multi-op shows the preview card) and SettingsTools + // undo/undoById for restores — this transport never writes directly. + var answerText = (outcome.answer || []).join("\n").trim() + || "(the local assistant had nothing to say)"; + if (outcome.undo !== undefined) { + var uRes = (outcome.undo.id !== undefined) + ? SettingsTools.undoById(Number(outcome.undo.id)) + : SettingsTools.undo(Number(outcome.undo.steps || 1)); + answerText += "\n(" + (uRes.ok ? (uRes.message || "undone") + : (uRes.reason || "undo failed")) + ")"; + } + if (outcome.apply !== undefined) { + var aRes = SettingsTools.request(outcome.apply.calls || [], + outcome.apply.label || ""); + if (aRes.needsConfirm) { + showSettingsConfirmCard(aRes.plan); + } else if (!aRes.ok) { + answerText += "\n(apply failed: " + (aRes.reason || "unknown") + ")"; + } else if (aRes.applied) { + answerText += "\n(" + (aRes.message || "applied") + ")"; + } + } + chatHistory.append({ + "isUser": false, + "text": "", + "isFinished": false, + "thoughtText": "", + "isSettingsPlan": false, + "planLabel": "", + "planOps": [], + "planResolved": "", + "planResult": "", + "isCommandPlan": false, + "cmdLabel": "", + "cmdLines": [], + "cmdResolved": "", + "cmdResult": "" + }); + startTypingAnimation(answerText); + } + + function sendPrompt(promptText, isSystemToolResult = false, base64Image = null, toolName = "", isRetry = false) { + if (!promptText.trim() && !base64Image) return; + + // Sending a message dismisses any open prompt suggestions. + promptSuggestions = []; + + if (!isRetry) + cancelRateLimitRetry(); // a new send supersedes any wait still pending + + if (!isSystemToolResult && !isRetry) { + chatHistory.append({ + "isUser": true, + "text": promptText || "", + "isFinished": true, + "thoughtText": "", + "isSettingsPlan": false, + "planLabel": "", + "planOps": [], + "planResolved": "", + "planResult": "", + "isCommandPlan": false, + "cmdLabel": "", + "cmdLines": [], + "cmdResolved": "", + "cmdResult": "" + }); + listView.positionViewAtEnd(); + saveHistory(); + + // Local first: the unified dispatcher decides (bridge op + // "dispatch"); this file only transports the verdict. + tryLocalDispatch(promptText); + return; + } + + sendCloudPrompt(promptText, isSystemToolResult, base64Image, toolName, isRetry); + } + + function sendCloudPrompt(promptText, isSystemToolResult = false, base64Image = null, toolName = "", isRetry = false) { + if (!promptText.trim() && !base64Image) return; + if (root.needsApiKey && root.getApiKey() === "") { + const envNames = { + "claude": "ANTHROPIC_API_KEY", + "openai": "OPENAI_API_KEY", + "gemini": "GEMINI_API_KEY", + "openrouter": "OPENROUTER_API_KEY", + "opencode": "OPENCODE_API_KEY", + "opencode-go": "OPENCODE_API_KEY" + }; + addAiMessage("⚠️ No " + root.providerLabel(root.provider) + " API key configured. Set the " + + (envNames[root.provider] || "API") + " environment variable, or add a key in the AI settings."); + return; + } + + isTyping = true; + isThinking = true; + inAgentLoop = true; + currentThoughtText = ""; + isThoughtExpanded = false; + + if (isSystemToolResult) { + if (toolName === "web_search" || toolName === "read_webpage") { + currentActionText = "Reading results..."; + } else if (toolName === "take_screenshot") { + currentActionText = "Analyzing screen..."; + } else if (toolName === "get_weather") { + currentActionText = "Analyzing weather..."; + } else { + currentActionText = "Thinking..."; + } + } else { + currentActionText = "Thinking..."; + } + + // Claude Code (subscription CLI) uses a Process, not XMLHttpRequest. + if (root.isClaudeCode) { + root.sendClaudeCode(promptText); + return; + } + + var xhr = new XMLHttpRequest(); + root.currentRequest = xhr; + + var model = root.activeModel(); + // Anthropic Messages vs OpenAI chat completions is a property of the model on + // opencode, not of the provider, so the endpoint, body and stream parsing all + // key off this rather than off isClaude. + const useAnthropic = root.anthropicWire; + if (root.isClaude) { + var claudeBase = GlobalConfig.ai.anthropicUrl || "https://api.anthropic.com"; + xhr.open("POST", claudeBase + "/v1/messages", true); + xhr.setRequestHeader("Content-Type", "application/json"); + xhr.setRequestHeader("x-api-key", root.getApiKey()); + xhr.setRequestHeader("anthropic-version", "2023-06-01"); + // QML's XMLHttpRequest presents a browser-like origin; this header opts into direct access. + xhr.setRequestHeader("anthropic-dangerous-direct-browser-access", "true"); + } else if (root.isOpenaiCompat) { + xhr.open("POST", root.openaiCompatBase() + (useAnthropic ? "/messages" : "/chat/completions"), true); + xhr.setRequestHeader("Content-Type", "application/json"); + root.setAuthHeader(xhr); + if (useAnthropic) + xhr.setRequestHeader("anthropic-version", "2023-06-01"); + if (root.provider === "openrouter") { + // OpenRouter attributes requests to an app via these; harmless elsewhere. + xhr.setRequestHeader("HTTP-Referer", "https://github.com/ladybug-me/caelestia-kde"); + xhr.setRequestHeader("X-Title", "Caelestia Shell"); + } + } else { + var ollamaUrl = GlobalConfig.ai.ollamaUrl || "http://localhost:11434"; + xhr.open("POST", ollamaUrl + "/api/chat", true); + xhr.setRequestHeader("Content-Type", "application/json"); + } + + var processedTextLength = 0; + var accumulatedThoughtText = ""; + var accumulatedContentText = ""; + var rawAccumulatedContentText = ""; + var finalToolCalls = null; + + for (var i = chatHistory.count - 1; i >= 0; i--) { + var m = chatHistory.get(i); + if (!m.isUser && !m.isFinished && m.text === "") { + chatHistory.remove(i); + } + } + + chatHistory.append({ + "isUser": false, + "text": "", + "isFinished": false, + "thoughtText": "", + "isSettingsPlan": false, + "planLabel": "", + "planOps": [], + "planResolved": "", + "planResult": "", + "isCommandPlan": false, + "cmdLabel": "", + "cmdLines": [], + "cmdResolved": "", + "cmdResult": "" + }); + + listView.positionViewAtEnd(); + + xhr.onerror = () => { root.handleSendError(); }; + xhr.onreadystatechange = () => { + if (xhr.readyState === 3 || xhr.readyState === XMLHttpRequest.DONE) { + if (xhr.status === 200) { + var currentText = xhr.responseText; + var unparsed = currentText.substring(processedTextLength); + var lines = unparsed.split('\n'); + + var linesToProcess = (xhr.readyState === XMLHttpRequest.DONE) ? lines.length : lines.length - 1; + + for (var i = 0; i < linesToProcess; i++) { + var rawLine = lines[i]; + var line = rawLine.trim(); + if (line === "") { + processedTextLength += rawLine.length + 1; + continue; + } + + var chunkContent = ""; + var chunkReasoning = ""; + + if (useAnthropic) { + // Anthropic streams Server-Sent Events; only "data:" lines carry JSON. + if (line.indexOf("event:") === 0) { + processedTextLength += rawLine.length + 1; + continue; + } + if (line.indexOf("data:") !== 0) { + processedTextLength += rawLine.length + 1; + continue; + } + var jsonStr = line.substring(5).trim(); + if (jsonStr === "" || jsonStr === "[DONE]") { + processedTextLength += rawLine.length + 1; + continue; + } + try { + var evt = JSON.parse(jsonStr); + processedTextLength += rawLine.length + 1; + if (evt.type === "content_block_delta" && evt.delta) { + if (evt.delta.type === "text_delta") + chunkContent = evt.delta.text || ""; + else if (evt.delta.type === "thinking_delta") + chunkReasoning = evt.delta.thinking || ""; + } else if (evt.type === "error") { + Logger.log("[AI] Claude stream error: " + JSON.stringify(evt.error || {})); + } + } catch (e) { + break; + } + } else if (root.isOpenaiCompat) { + // OpenAI-compatible streaming: SSE where each "data:" line is a + // chunk holding choices[0].delta. "[DONE]" ends the stream. + if (line.indexOf("data:") !== 0) { + processedTextLength += rawLine.length + 1; + continue; + } + var oaiJson = line.substring(5).trim(); + if (oaiJson === "" || oaiJson === "[DONE]") { + processedTextLength += rawLine.length + 1; + continue; + } + try { + var oaiEvt = JSON.parse(oaiJson); + processedTextLength += rawLine.length + 1; + if (oaiEvt.error) { + Logger.log("[AI] " + root.providerLabel(root.provider) + " stream error: " + JSON.stringify(oaiEvt.error)); + } else if (oaiEvt.choices && oaiEvt.choices.length > 0) { + var delta = oaiEvt.choices[0].delta || {}; + chunkContent = delta.content || ""; + // Reasoning models expose their thinking under different + // keys depending on the provider. + chunkReasoning = delta.reasoning_content || delta.reasoning || ""; + } + } catch (e) { + break; + } + } else { + // Ollama streams newline-delimited JSON objects. + try { + var parsed = JSON.parse(line); + processedTextLength += rawLine.length + 1; + if (parsed.message) { + chunkReasoning = parsed.message.thinking || parsed.message.reasoning || parsed.message.reasoning_content || ""; + chunkContent = parsed.message.content || ""; + } + } catch (e) { + break; + } + } + + if (chunkReasoning) + accumulatedThoughtText += chunkReasoning; + if (chunkContent) + rawAccumulatedContentText += chunkContent; + + if (chunkContent === "" && chunkReasoning === "") + continue; + + var displayContent = stripToolCalls(rawAccumulatedContentText); + var displayThought = accumulatedThoughtText; + + if (accumulatedThoughtText === "") { + var openThinkIdx = displayContent.indexOf(""); + var closeThinkIdx = displayContent.indexOf(""); + + if (openThinkIdx !== -1) { + if (closeThinkIdx !== -1) { + displayThought = displayContent.substring(openThinkIdx + 7, closeThinkIdx).trim(); + displayContent = displayContent.substring(0, openThinkIdx) + displayContent.substring(closeThinkIdx + 8); + } else { + displayThought = displayContent.substring(openThinkIdx + 7).trim(); + displayContent = displayContent.substring(0, openThinkIdx); + } + } + } + + root.currentThoughtText = displayThought.trim(); + + if (displayContent.trim() !== "") { + if (isThinking) isThinking = false; + } + + chatHistory.setProperty(chatHistory.count - 1, "thoughtText", displayThought.trim()); + chatHistory.setProperty(chatHistory.count - 1, "text", displayContent.trim()); + listView.positionViewAtEnd(); + } + } + + if (xhr.readyState === XMLHttpRequest.DONE) { + if (xhr.status === 200) { + root.rateLimitRetries = 0; + chatHistory.setProperty(chatHistory.count - 1, "isFinished", true); + saveHistory(); + + var enableTools = GlobalConfig.ai.enableCelestialMode; + var textToolCalls = enableTools ? parseTextToolCalls(rawAccumulatedContentText) : []; + + if (textToolCalls.length > 0) { + if (enableTools) { + currentActionText = "Using tools..."; + accumulatedToolResults = ""; + accumulatedToolImage = ""; + runningToolsCount = 0; + + for (var t = 0; t < textToolCalls.length; t++) { + var toolCall = textToolCalls[t]; + var toolName = toolCall.name; + var args = toolCall.args || {}; + + // Count async tools (get_weather is synchronous; the others + // resolve through execution or the approval card — set_timer + // included, since its result now arrives at card-Apply time). + if (toolName === "take_screenshot" || toolName === "web_search" || toolName === "read_webpage" || toolName === "open_app" || toolName === "caelestia_command" || toolName === "set_timer" || toolName === "caelestia_genius_math" || toolName === "caelestia_genius_stats" || toolName === "caelestia_genius_logic" || toolName === "caelestia_genius_decide" || toolName === "caelestia_genius_palette" || toolName === "caelestia_genius_graphs" || toolName === "caelestia_genius_units" || toolName === "caelestia_genius_optimize" || toolName === "caelestia_genius_fsbrain_summary") { + runningToolsCount++; + } + + if (toolName === "take_screenshot") { + currentActionText = "Analyzing screen..."; + var screenCmd = `spectacle -b -m -n -o ${Paths.runtimeTemp("orion_screenshot.png")}`; + runAgentCommand(screenCmd, "screenshot_take"); + + } else if (toolName === "web_search") { + currentActionText = "Searching the web..."; + var query = String(args.query || ""); + var page = args.page || 1; + runAgentCommand(["env", "PYTHONIOENCODING=utf8", "python3", Quickshell.shellDir + "/scripts/orion_search.py", "--mode", "search", "--query", query, "--page", String(page)], "exec_" + toolName); + + } else if (toolName === "read_webpage") { + currentActionText = "Reading webpage..."; + var url = String(args.url || ""); + runAgentCommand(["env", "PYTHONIOENCODING=utf8", "python3", Quickshell.shellDir + "/scripts/orion_search.py", "--mode", "read", "--url", url], "exec_" + toolName); + + } else if (toolName === "open_app") { + // Gated: the card's Apply runs the launch; raw model + // output can only ever produce a preview. + var app = String(args.app_name || ""); + var appGate = CommandGate.requestOpenApp(app); + if (!appGate.ok) { + runningToolsCount--; // counted above; the error resolves it + accumulatedToolResults += "Tool: open_app\nError: " + appGate.reason + "\n\n"; + } else { + currentActionText = "Waiting for your approval..."; + showCommandConfirmCard(appGate.preview); + } + + } else if (toolName === "set_timer") { + // Gated: a timer is a user-visible action (a notification + // will fire), so it waits for the card's Apply too. + var secs = Number(args.seconds) || 5; + var msg = String(args.message || "Timer finished"); + var timerGate = CommandGate.requestTimer(secs, msg); + if (!timerGate.ok) { + runningToolsCount--; // counted above; the error resolves it + accumulatedToolResults += "Tool: set_timer\nError: " + timerGate.reason + "\n\n"; + } else { + currentActionText = "Waiting for your approval..."; + showCommandConfirmCard(timerGate.preview); + } + + } else if (toolName === "get_weather") { + currentActionText = "Checking weather..."; + var weatherStr = Weather.city + ": " + Weather.temp + " (" + Weather.description + "). Humidity: " + Weather.humidity + "%, Wind: " + Weather.windSpeed + " km/h"; + accumulatedToolResults += "Tool: get_weather\nResult: Local weather from system dashboard: " + weatherStr + "\n\n"; + + } else if (toolName === "caelestia_command") { + // Gated: verified read-only subcommands run; everything + // else waits for the card's Apply. + var subcmd = String(args.subcommand || ""); + var subargs = String(args.args || "").trim(); + var cmdArr = ["caelestia", subcmd]; + if (subargs) cmdArr = cmdArr.concat(subargs.split(/\s+/)); + var cmdGate = CommandGate.requestCaelestia(cmdArr); + if (!cmdGate.ok) { + runningToolsCount--; // counted above; the error resolves it + accumulatedToolResults += "Tool: caelestia_command\nError: " + cmdGate.reason + "\n\n"; + } else if (cmdGate.needsConfirm) { + currentActionText = "Waiting for your approval..."; + showCommandConfirmCard(cmdGate.preview); + } else { + currentActionText = "Running caelestia..."; + runAgentCommand(cmdArr, "exec_" + toolName); + } + + } else if (toolName === "caelestia_setting_list") { + // Synchronous, in-process (SettingsTools singleton). + currentActionText = "Listing settings tools..."; + var listRes = SettingsTools.listTools(args.group !== undefined ? String(args.group) : null); + accumulatedToolResults += listRes.ok + ? "Tool: caelestia_setting_list\nResult: groups: " + listRes.groups.join(", ") + "\n" + listRes.lines.join("\n") + "\n\n" + : "Tool: caelestia_setting_list\nError: " + listRes.reason + "\n\n"; + + } else if (toolName === "caelestia_setting_get") { + currentActionText = "Reading setting..."; + var getRes = SettingsTools.get(String(args.path || "")); + accumulatedToolResults += getRes.ok + ? "Tool: caelestia_setting_get\nResult: " + getRes.path + " = " + getRes.value + " (" + getRes.kind + ", " + getRes.validation + ", default " + getRes.default + ")\n\n" + : "Tool: caelestia_setting_get\nError: " + getRes.reason + "\n\n"; + + } else if (toolName === "caelestia_setting_explain") { + currentActionText = "Explaining setting..."; + var expRes = SettingsTools.explain(String(args.path || "")); + accumulatedToolResults += expRes.ok + ? "Tool: caelestia_setting_explain\nResult: " + expRes.answer + "\n\n" + : "Tool: caelestia_setting_explain\nError: " + expRes.reason + "\n\n"; + + } else if (toolName === "caelestia_setting_history") { + currentActionText = "Reading undo history..."; + var hist = SettingsTools.historyEntries(); + var histLines = hist.map(function(e) { + return "#" + e.id + " " + e.at + " — " + (e.label || e.ops + " change(s)") + " (" + e.ops + " change(s))"; + }); + accumulatedToolResults += "Tool: caelestia_setting_history\nResult: " + + (histLines.length ? "\n" + histLines.join("\n") : "(empty)") + "\n\n"; + + } else if (toolName === "caelestia_setting_undo") { + currentActionText = "Undoing settings change..."; + var undoRes; + if (args.id !== undefined) + undoRes = SettingsTools.undoById(Number(args.id)); + else + undoRes = SettingsTools.undo(args.steps !== undefined ? Number(args.steps) : 1); + accumulatedToolResults += undoRes.ok + ? "Tool: caelestia_setting_undo\nResult: " + undoRes.message + "\n\n" + : "Tool: caelestia_setting_undo\nError: " + undoRes.reason + "\n\n"; + + } else if (toolName === "caelestia_setting_set") { + // Issue #120 confirmation policy: one op applies + // directly (undoable); more than one op waits + // for the user's Apply on the preview card. + var setCalls = args.calls || []; + var setRes = SettingsTools.request(setCalls, String(args.label || "")); + if (setRes.needsConfirm) { + runningToolsCount++; // resolved by the card buttons + showSettingsConfirmCard(setRes.plan); + } else { + accumulatedToolResults += setRes.ok + ? "Tool: caelestia_setting_set\nResult: " + setRes.message + "\n\n" + : "Tool: caelestia_setting_set\nError: " + setRes.reason + "\n\n"; + } + + } else if (toolName === "caelestia_preset_list") { + currentActionText = "Listing presets..."; + var pres = SettingsTools.presetList(); + var presLines = pres.map(function(p) { + return p.name + " — " + p.description + " (" + p.calls + " changes)"; + }); + accumulatedToolResults += "Tool: caelestia_preset_list\nResult: \n" + presLines.join("\n") + "\n\n"; + + } else if (toolName === "caelestia_preset_apply") { + var presetRes = SettingsTools.requestPreset(String(args.name || "")); + if (presetRes.needsConfirm) { + runningToolsCount++; // resolved by the card buttons + showSettingsConfirmCard(presetRes.plan); + } else { + accumulatedToolResults += presetRes.ok + ? "Tool: caelestia_preset_apply\nResult: " + presetRes.message + "\n\n" + : "Tool: caelestia_preset_apply\nError: " + presetRes.reason + "\n\n"; + } + + } else if (toolName === "caelestia_genius_math") { + // Deterministic on-device compute through the assistant's JSON + // bridge: the model builds the expression, the bridge evaluates it — + // Ollama is never contacted (the op is allow-listed, read-only). + currentActionText = "Computing..."; + runAgentCommand(assistantBridgeCommand(JSON.stringify({ op: "genius_math", expr: String(args.expr || "") })), "genius_" + toolName); + } else if (toolName === "caelestia_genius_stats") { + currentActionText = "Crunching numbers..."; + runAgentCommand(assistantBridgeCommand(JSON.stringify({ op: "genius_stats", numbers: Array.isArray(args.numbers) ? args.numbers : [] })), "genius_" + toolName); + } else if (toolName === "caelestia_genius_logic") { + currentActionText = "Checking logic..."; + runAgentCommand(assistantBridgeCommand(JSON.stringify({ op: "genius_logic", formula: String(args.formula || "") })), "genius_" + toolName); + } else if (toolName === "caelestia_genius_decide") { + currentActionText = "Comparing options..."; + runAgentCommand(assistantBridgeCommand(JSON.stringify({ op: "genius_decide", matrix: Array.isArray(args.matrix) ? args.matrix : [], labels: Array.isArray(args.labels) ? args.labels : [], criteria: Array.isArray(args.criteria) ? args.criteria : [], weights: Array.isArray(args.weights) ? args.weights : null, benefits: Array.isArray(args.benefits) ? args.benefits : null, method: String(args.method || "wsm") })), "genius_" + toolName); + } else if (toolName === "caelestia_genius_fsbrain_summary") { + // REPORT only: staleness summary is read-only; + // the tidy mover is never reachable from here + currentActionText = "Summarizing folder..."; + runAgentCommand(assistantBridgeCommand(JSON.stringify({ op: "genius_fsbrain_summary", path: String(args.path || ""), top: Number(args.top) || 10, half_life_days: Number(args.half_life_days) || 30 })), "genius_" + toolName); + } else if (toolName === "caelestia_genius_optimize") { + // read-only PREVIEW: ranks profiles via Pareto/AC-3; + // nothing is applied here + currentActionText = "Optimizing..."; + runAgentCommand(assistantBridgeCommand(JSON.stringify({ op: "optimize_recommend", profile: String(args.profile || "gaming"), k: Number(args.k) || 6 })), "genius_" + toolName); + } else if (toolName === "caelestia_genius_units") { + currentActionText = "Converting units..."; + runAgentCommand(assistantBridgeCommand(JSON.stringify({ op: "genius_units", text: String(args.text || "") })), "genius_" + toolName); + } else if (toolName === "caelestia_genius_graphs") { + currentActionText = "Running graph algorithms..."; + runAgentCommand(assistantBridgeCommand(JSON.stringify({ op: "genius_graphs", method: String(args.method || "dijkstra"), graph: args.graph || {}, source: String(args.source || ""), target: args.target || null, nodes: Array.isArray(args.nodes) ? args.nodes : [], edges: Array.isArray(args.edges) ? args.edges : [], cost: Array.isArray(args.cost) ? args.cost : [] })), "genius_" + toolName); + } else if (toolName === "caelestia_genius_palette") { + // Contrast-check before suggesting: the palette op only + // computes; any scheme/wallpaper change stays an inert + // SUGGESTED_NOT_EXECUTED suggestion downstream. + currentActionText = "Building palette..."; + runAgentCommand(assistantBridgeCommand(JSON.stringify({ op: "genius_palette", hex: String(args.hex || ""), harmony: String(args.harmony || "analogous"), n: Number(args.n) || 5 })), "genius_" + toolName); + + } else { + Logger.log("[AI] Unknown tool: " + toolName); + runningToolsCount--; // don't block on unknown tools + } + } + + // set_timer is synchronous — check if all async tools are already done + if (runningToolsCount === 0) { + if (accumulatedToolResults !== "") { + checkToolsFinished(); + } else { + currentActionText = "Thinking..."; + isTyping = false; + isThinking = false; + inAgentLoop = false; + } + } + } else { + currentActionText = "Thinking..."; + isTyping = false; + isThinking = false; + inAgentLoop = false; + } + } else { + currentActionText = "Thinking..."; + isTyping = false; + isThinking = false; + inAgentLoop = false; + } + } else { + var providerName = root.providerLabel(root.provider); + // Providers explain themselves in the error body — a rate limit + // even says how long to wait. Surfacing that beats a bare status + // code the user can do nothing with. + var apiDetail = ""; + try { + const errBody = JSON.parse(xhr.responseText); + const e = Array.isArray(errBody) ? (errBody[0] || {}).error : errBody.error; + if (e) { + // OpenRouter wraps the upstream provider's error: its own + // message is just "Provider returned error", and the part + // worth reading (which model, which provider, what to do) + // sits in metadata.raw. + const raw = e.metadata && e.metadata.raw ? String(e.metadata.raw) : ""; + const provider = e.metadata && e.metadata.provider_name ? String(e.metadata.provider_name) : ""; + if (raw) + apiDetail = " " + (provider ? provider + ": " : "") + raw.split("\n")[0]; + else if (e.message) + apiDetail = " " + String(e.message).split("\n")[0]; + } + } catch (e) {} + // A rate limit is not really a failure — the provider told us + // when it will accept the next request, so wait that long and + // finish the answer instead of dropping it on the user. + // A daily quota does not come back in the seconds the provider + // suggests retrying after, so retrying just spends more of the + // very allowance that ran out. Only wait out short-term limits. + const perDayQuota = /PerDay|per day/i.test(xhr.responseText || ""); + if (xhr.status === 429 && perDayQuota) + root.cancelRateLimitRetry(); + + if (xhr.status === 429 && !perDayQuota && root.rateLimitRetries < root.maxRateLimitRetries) { + if ((xhr.responseText || "").indexOf("free_tier") !== -1) + root.onFreeTier = true; + const waitMs = root.rateLimitDelayMs(xhr); + root.rateLimitRetries++; + root.rateLimitSecondsLeft = Math.max(1, Math.round(waitMs / 1000)); + root.currentActionText = qsTr("Rate limited - retrying in %1s…").arg(root.rateLimitSecondsLeft); + root.isTyping = true; + root.isThinking = true; + rateLimitRetryTimer.forChat = root.currentChatId; + rateLimitRetryTimer.forModel = root.activeModel(); + rateLimitRetryTimer.retryFn = () => root.sendPrompt(promptText, isSystemToolResult, base64Image, toolName, true); + rateLimitRetryTimer.restart(); + return; + } + + var hint = ""; + if (xhr.status === 429 && perDayQuota) + hint = " This model's daily free quota is used up - it resets tomorrow. Pick another model, or use Claude Code, which is not on this quota."; + else if (xhr.status === 429) + hint = " Rate limit reached and still limited after " + root.maxRateLimitRetries + " retries - wait a minute and try again."; + else if (root.needsApiKey && (xhr.status === 401 || xhr.status === 403)) + hint = " Check your API key."; + var errMsg = (xhr.status === 0) ? "Generation canceled" : (providerName + " request failed (status " + xhr.status + ")." + hint + apiDetail); + var currentText = chatHistory.get(chatHistory.count - 1).text; + if (currentText.trim() === "") { + chatHistory.setProperty(chatHistory.count - 1, "text", errMsg); + } else { + chatHistory.setProperty(chatHistory.count - 1, "text", currentText + "\n\n*[" + errMsg + "]*"); + } + chatHistory.setProperty(chatHistory.count - 1, "isFinished", true); + isTyping = false; + isThinking = false; + inAgentLoop = false; + saveHistory(); + } + } + } + }; + + var enableTools = GlobalConfig.ai.enableCelestialMode; + var sysPrompt = "You are a helpful AI assistant integrated into the user's desktop OS shell (Caelestia, running on KDE Plasma/Wayland)."; + if (enableTools) { + sysPrompt += "\n\nYou have access to the following tools. To call a tool, output a block containing ONLY valid JSON. Do not output any text inside the block other than the JSON object.\n\nFORMAT:\n\n{\"name\": \"TOOL_NAME\", \"args\": {ARGUMENTS}}\n\n\nAVAILABLE TOOLS:\n- take_screenshot: Captures the user's screen for visual analysis. Args: none.\n Example: \n{\"name\": \"take_screenshot\", \"args\": {}}\n\n\n- web_search: Searches the web. Args: query (string, required), page (number, optional).\n Example: \n{\"name\": \"web_search\", \"args\": {\"query\": \"latest news\"}}\n\n\n- read_webpage: Fetches and reads the text of a URL. Args: url (string, required).\n Example: \n{\"name\": \"read_webpage\", \"args\": {\"url\": \"https://example.com\"}}\n\n\n- open_app: Launches an installed desktop application. Args: app_name (string, required).\n Example: \n{\"name\": \"open_app\", \"args\": {\"app_name\": \"dolphin\"}}\n\n\n- set_timer: Sets a countdown timer that fires a desktop notification. Args: seconds (number, required), message (string, required).\n Example: \n{\"name\": \"set_timer\", \"args\": {\"seconds\": 300, \"message\": \"Break time!\"}}\n\n\n- get_weather: Gets the current local weather from the system dashboard. Args: none.\n Example: \n{\"name\": \"get_weather\", \"args\": {}}\n\n\n- caelestia_command: Runs a caelestia CLI command. Valid subcommands: shell, install, update, wallpaper, scheme (list/get/set), screenshot, record, version, help. Args: subcommand (string, required), args (string, optional extra flags). State-changing commands show the user an approval card and run only if they approve; only the tool result tells you whether it ran — never claim it ran before that.\n Example: \n{\"name\": \"caelestia_command\", \"args\": {\"subcommand\": \"wallpaper\", \"args\": \"--random\"}}\n\n\n- caelestia_setting_list: Lists the shell's validated settings tools (277 tools in 19 feature-area groups) with their exact value ranges/enums. Args: group (string, optional — one of bar, dock, appearance, effects, animations, notifications, launcher, lockscreen, wallpaper-scheme, overview, osd, dashboard, sidebar, nexus, border, general, services, utilities, audio). Call this FIRST when a settings request names a key you are not sure about.\n Example: \n{\"name\": \"caelestia_setting_list\", \"args\": {\"group\": \"effects\"}}\n\n\n- caelestia_setting_get: Reads one setting's current live value, validation and default. Args: path (string, required — the dotted config path, e.g. \"bar.scale\").\n Example: \n{\"name\": \"caelestia_setting_get\", \"args\": {\"path\": \"bar.scale\"}}\n\n\n- caelestia_setting_explain: Explains why a setting currently looks the way it does, grounded in the shell's own code. Args: path (string, required).\n Example: \n{\"name\": \"caelestia_setting_explain\", \"args\": {\"path\": \"appearance.blur\"}}\n\n\n- caelestia_setting_set: Changes shell settings. Args: calls (array of {name, value}, required — tool names from caelestia_setting_list and validated values), label (string, optional — short description of the request). A single change applies immediately; multiple changes are shown to the user as a preview they must confirm — never claim a multi-change request is done until the tool result confirms it. Out-of-range or invalid values are rejected, never clamped.\n Example: \n{\"name\": \"caelestia_setting_set\", \"args\": {\"calls\": [{\"name\": \"setBarScale\", \"value\": 1.2}], \"label\": \"make the bar bigger\"}}\n\n\n- caelestia_setting_undo: Undoes previous settings applies. Args: steps (number, optional, default 1), id (number, optional — a specific history entry id from caelestia_setting_history, for \"restore the theme I had yesterday\"-style requests).\n Example: \n{\"name\": \"caelestia_setting_undo\", \"args\": {}}\n\n\n- caelestia_setting_history: Lists the recent settings applies (newest first) that can be undone. Args: none.\n Example: \n{\"name\": \"caelestia_setting_history\", \"args\": {}}\n\n\n- caelestia_preset_list: Lists the named settings presets (compact, minimal, gaming, battery-saver, macos-like). Args: none.\n Example: \n{\"name\": \"caelestia_preset_list\", \"args\": {}}\n\n\n- caelestia_preset_apply: Applies a named preset as a bundle of validated setting changes (the user confirms it before anything is written). Args: name (string, required).\n Example: \n{\"name\": \"caelestia_preset_apply\", \"args\": {\"name\": \"minimal\"}}\n\n\n\n- caelestia_genius_math: Evaluates a math expression deterministically on-device — no model in the loop (arithmetic, ^, sqrt, sin/cos/tan, log, factorial, pi and e). Args: expr (string, required — e.g. \"840*0.15\" or \"2^10 + sqrt(144)\").\n Example: \n{\"name\": \"caelestia_genius_math\", \"args\": {\"expr\": \"840*0.15\"}}\n\n\n\n- caelestia_genius_stats: Computes full descriptive statistics for a list of numbers on-device (mean, median, quartiles, spread, outliers, normality when n >= 8). Args: numbers (array of numbers, required — e.g. [3, 9, 12, 1, 44]).\n Example: \n{\"name\": \"caelestia_genius_stats\", \"args\": {\"numbers\": [3, 9, 12, 1, 44]}}\n\n\n\n- caelestia_genius_logic: Classifies a propositional logic formula as tautology, contradiction or contingency and shows the truth table — deterministic, no model. Args: formula (string, required — e.g. \"(p and q) -> p\").\n Example: \n{\"name\": \"caelestia_genius_logic\", \"args\": {\"formula\": \"(p and q) -> p\"}}\n\n\n\n- caelestia_genius_decide: Ranks options against weighted criteria with a classical decision method (WSM/TOPSIS/...) and returns a winner with the full ranking — deterministic and auditable, no model judgement. Use it when the user asks which of several options to pick. Args: matrix (array of number rows, required — one row per option, e.g. [[8,256],[6,512]]), labels (array of strings, required — one per option, e.g. [\"air\",\"pro\"]), criteria (array of strings, required — one per column, e.g. [\"battery\",\"storage\"]), weights (array of numbers, optional — one per criterion, defaults to equal), benefits (array of booleans, optional — true = more is better; mark cost criteria like storage-in-GB as false), method (string, optional — wsm (default), wpm, topsis, pareto, regret).\n Example: \n{\"name\": \"caelestia_genius_decide\", \"args\": {\"matrix\": [[8, 256], [6, 512]], \"labels\": [\"air\", \"pro\"], \"criteria\": [\"battery\", \"storage\"], \"weights\": [0.5, 0.5], \"benefits\": [true, false], \"method\": \"topsis\"}}\n\n\n\n- caelestia_genius_palette: Builds an OKLch harmony palette from a hex color and checks WCAG contrast — run it BEFORE proposing an accent or scheme change so the suggestion is grounded (scheme changes themselves stay inert suggestions the user applies). Args: hex (string, required — e.g. \"#3b7dd8\"), harmony (string, optional — analogous (default), complementary, triadic, tetradic, split_complementary), n (number, optional — palette size, default 5).\n Example: \n{\"name\": \"caelestia_genius_palette\", \"args\": {\"hex\": \"#3b7dd8\", \"harmony\": \"triadic\"}}\n\n\n\n- caelestia_genius_graphs: Runs classical graph algorithms on-device (Dijkstra shortest paths, Kruskal minimum spanning tree, Hungarian assignment) — exact and deterministic, no model. Args: method (string, optional — dijkstra (default), mst, assign), graph (object, for dijkstra — {node: {neighbor: weight}}), source (string, for dijkstra), target (string, optional — dijkstra), nodes (array of strings, for mst), edges (array of [u, v, weight], for mst), cost (array of number rows, for assign).\n Example: \n{\"name\": \"caelestia_genius_graphs\", \"args\": {\"method\": \"dijkstra\", \"graph\": {\"a\": {\"b\": 2.0}}, \"source\": \"a\"}}\n\n\n\n- caelestia_genius_units: Converts units and does dimension-checked arithmetic on-device — mismatched dimensions are rejected, never coerced (SI prefixes, compound units, affine temperature conversion). Args: text (string, required — e.g. \"convert 5 m to cm\", \"3 km in m\" or \"3 km + 200 m\").\n Example: \n{\"name\": \"caelestia_genius_units\", \"args\": {\"text\": \"convert 5 m to cm\"}}\n\n\n\n- caelestia_genius_optimize: Runs the read-only settings optimizer preview on-device — Pareto fronts and AC-3 constraint propagation rank which preset profile fits the stated priority; PREVIEW ONLY, it changes nothing (apply stays a separate, confirmed action). Args: profile (string, required — one of compact, minimal, gaming, battery-saver, macos-like), k (number, optional — how many recommendations to return, default 6).\n Example: \n{\"name\": \"caelestia_genius_optimize\", \"args\": {\"profile\": \"battery-saver\", \"k\": 3}}\n\n\n\n- caelestia_genius_fsbrain_summary: Reads the filesystem second-brain staleness REPORT for a folder on-device (frecency-ranked stale files, read-only). This is the report only — it never moves, renames or deletes anything (the tidy mover is a separate, confirmed tool). Args: path (string, required — the directory to summarize), top (number, optional — rows kept, default 10), half_life_days (number, optional — frecency half-life, default 30).\n Example: \n{\"name\": \"caelestia_genius_fsbrain_summary\", \"args\": {\"path\": \"~/documents\", \"top\": 5}}\n\n\n\nCRITICAL RULES:\n1. ALWAYS use a block to call a tool. NEVER pretend to perform actions in plain text.\n2. You may output a brief acknowledgment before the block (e.g. 'Opening Dolphin for you!') but you MUST include the block.\n3. You can include multiple blocks in one response.\n4. After receiving tool results, respond naturally to the user based on what the tool returned."; + } + + var requestBody; + if (useAnthropic) { + // Anthropic Messages API: system prompt is a top-level field; messages must + // carry non-empty content and cannot include the streaming placeholder. + var claudeMessages = []; + for (var i = 0; i < chatHistory.count; i++) { + var msg = chatHistory.get(i); + if (!msg.isUser && !msg.isFinished && (msg.text || "") === "") + continue; + if ((msg.text || "") === "") + continue; + claudeMessages.push({ + "role": msg.isUser ? "user" : "assistant", + "content": msg.text + }); + } + + if (isSystemToolResult) { + var claudeContent; + if (base64Image) { + claudeContent = [ + { "type": "text", "text": promptText }, + { "type": "image", "source": { "type": "base64", "media_type": "image/jpeg", "data": base64Image } } + ]; + } else { + claudeContent = promptText; + } + claudeMessages.push({ "role": "user", "content": claudeContent }); + } + + requestBody = { + "model": model, + "max_tokens": 4096, + "system": sysPrompt, + "messages": claudeMessages, + "stream": true + }; + } else { + var messages = []; + messages.push({ + "role": "system", + "content": sysPrompt + }); + + for (var j = 0; j < chatHistory.count; j++) { + var m = chatHistory.get(j); + messages.push({ + "role": m.isUser ? "user" : "assistant", + "content": m.text || "" + }); + } + + if (isSystemToolResult) { + var toolMsg = { + "role": "user", + "content": promptText + }; + if (base64Image) { + if (root.isOpenaiCompat) { + // OpenAI carries images inline in the content array as data URLs; + // Ollama takes a separate base64 "images" field. + toolMsg["content"] = [ + { "type": "text", "text": promptText }, + { "type": "image_url", "image_url": { "url": "data:image/jpeg;base64," + base64Image } } + ]; + } else { + toolMsg["images"] = [base64Image]; + } + } + messages.push(toolMsg); + } + + // Native tool-calling API removed; using text-based parsing instead, + // which is compatible with all models including llama3, mistral, phi, etc. + requestBody = { + "model": model, + "messages": messages, + "stream": true + }; + } + + xhr.send(JSON.stringify(requestBody)); + } + + Item { + id: mainWrapper + + anchors.fill: parent + anchors.margins: Tokens.padding.medium + + // Mode Switcher Row (Chat / History) + RowLayout { + id: modeSwitcherRow + + anchors.top: parent.top + anchors.left: parent.left + anchors.right: parent.right + anchors.rightMargin: 0 + z: 10 + spacing: Tokens.spacing.small + + StyledRect { + id: modeSwitcherBg + + implicitWidth: modeRow.width + implicitHeight: 32 + radius: Tokens.rounding.full + color: Colours.tPalette.m3surfaceContainer + + StyledClippingRect { + z: -1 + anchors.fill: parent + radius: Tokens.rounding.full + + ShaderEffectSource { + id: switcherBlurSource + + sourceItem: contentStack + sourceRect: { + var p = parent.mapToItem(contentStack, 0, 0); + return Qt.rect(p.x, p.y, parent.width, parent.height); + } + } + MultiEffect { + anchors.fill: parent + source: switcherBlurSource + blurEnabled: true + blurMax: 32 + } + } + + StyledRect { + width: isHistoryTab ? historyTab.width : chatTab.width + height: parent.height + radius: Tokens.rounding.full + color: Colours.palette.m3primary + x: isHistoryTab ? historyTab.x : chatTab.x + + Behavior on x { NumberAnimation { duration: 250; easing.type: Easing.OutCubic } } + Behavior on width { NumberAnimation { duration: 250; easing.type: Easing.OutCubic } } + } + + Row { + id: modeRow + + height: parent.height + + Item { + id: chatTab + + height: parent.height + width: !isHistoryTab ? 40 : chatContent.implicitWidth + Tokens.padding.medium * 2 + + + Behavior on width { NumberAnimation { duration: 250; easing.type: Easing.OutCubic } } + + StateLayer { + radius: Tokens.rounding.full + onClicked: isHistoryTab = false + } + + Row { + id: chatContent + + anchors.centerIn: parent + spacing: Tokens.spacing.small + + MaterialIcon { + anchors.verticalCenter: parent.verticalCenter + text: "chat" + color: !isHistoryTab ? Colours.palette.m3onPrimary : Colours.palette.m3onSurfaceVariant + font: Tokens.font.icon.small + } + Text { + anchors.verticalCenter: parent.verticalCenter + text: "Chat" + color: !isHistoryTab ? Colours.palette.m3onPrimary : Colours.palette.m3onSurfaceVariant + font: Tokens.font.body.small + visible: isHistoryTab + } + } + } + + Item { + id: historyTab + + height: parent.height + width: isHistoryTab ? 40 : historyContent.implicitWidth + Tokens.padding.medium * 2 + + + Behavior on width { NumberAnimation { duration: 250; easing.type: Easing.OutCubic } } + + StateLayer { + radius: Tokens.rounding.full + onClicked: isHistoryTab = true + } + + Row { + id: historyContent + + anchors.centerIn: parent + spacing: Tokens.spacing.small + + MaterialIcon { + anchors.verticalCenter: parent.verticalCenter + text: "history" + color: isHistoryTab ? Colours.palette.m3onPrimary : Colours.palette.m3onSurfaceVariant + font: Tokens.font.icon.small + } + Text { + anchors.verticalCenter: parent.verticalCenter + text: "History" + color: isHistoryTab ? Colours.palette.m3onPrimary : Colours.palette.m3onSurfaceVariant + font: Tokens.font.body.small + visible: !isHistoryTab + } + } + } + } + } + + } + + // Provider + model (+ account) selectors on their own row; a Flow so the + // pills wrap to a second line instead of overflowing a narrow sidebar. + Flow { + id: selectorRow + + anchors.top: modeSwitcherRow.bottom + anchors.left: parent.left + anchors.right: parent.right + anchors.topMargin: Tokens.spacing.small + z: 10 + spacing: Tokens.spacing.small + + // Provider Selector Split Button (Ollama / Claude Code) + SplitButton { + id: providerSelector + + type: SplitButton.Tonal + verticalPadding: 4 + visible: root.providerList.length > 1 + Layout.preferredWidth: implicitWidth + + active: menuItems.find(m => m.modelData === root.provider) ?? menuItems[0] ?? null + menu.onItemSelected: item => { + GlobalConfig.ai.defaultProvider = item.modelData; + } + + menuItems: providerVariants.instances + + fallbackIcon: "cloud" + fallbackText: qsTr("Provider") + stateLayer.disabled: true + + Variants { + id: providerVariants + + model: root.providerList + + delegate: MenuItem { + required property string modelData + + text: root.providerLabel(modelData) + } + } + } + + // Model Selector Split Button + SplitButton { + id: modelSelector + + type: SplitButton.Tonal + verticalPadding: 4 + Layout.preferredWidth: implicitWidth + + active: menuItems.find(m => m.modelData === root.activeModel()) ?? menuItems[0] ?? null + menu.onItemSelected: item => { + if (root.isClaudeCode) { + GlobalConfig.ai.defaultClaudeCodeModel = item.modelData; + // Effort levels differ per model — reset to default on model change. + GlobalConfig.ai.claudeCodeEffort = "default"; + } else if (root.isClaude) + GlobalConfig.ai.defaultClaudeModel = item.modelData; + else if (root.isOpenaiCompat) + GlobalConfig.ai[root.defaultModelField(root.provider)] = item.modelData; + else + GlobalConfig.ai.defaultOllamaModel = item.modelData; + } + + menuItems: modelVariants.instances + + fallbackIcon: "smart_toy" + fallbackText: qsTr("Select Model") + stateLayer.disabled: true + + Variants { + id: modelVariants + + model: { + if (root.isClaudeCode) + return root.claudeCodeModelsList; + if (root.isClaude) + return root.claudeModelsList; + if (root.isOpenaiCompat) + return root.openaiCompatModelList(); + return root.ollamaModelsList; + } + + delegate: MenuItem { + required property string modelData + + text: modelData + } + } + } + + // Effort / thinking-level Selector (Claude Code). + SplitButton { + id: effortSelector + + type: SplitButton.Tonal + verticalPadding: 4 + visible: root.isClaudeCode && root.claudeCodeEffortOptions.length > 0 + + active: menuItems.find(m => m.modelData === (GlobalConfig.ai.claudeCodeEffort || "default")) ?? menuItems[0] ?? null + menu.onItemSelected: item => { + GlobalConfig.ai.claudeCodeEffort = item.modelData; + } + + menuItems: effortVariants.instances + + fallbackIcon: "neurology" + fallbackText: qsTr("Effort") + stateLayer.disabled: true + + Variants { + id: effortVariants + + model: root.claudeCodeEffortOptions + + delegate: MenuItem { + required property string modelData + + text: modelData + } + } + } + + // Account Selector (Claude Code multi-login) — only when >1 account exists. + SplitButton { + id: accountSelector + + type: SplitButton.Tonal + verticalPadding: 4 + visible: root.isClaudeCode && root.claudeAccountIds.length > 1 + + active: menuItems.find(m => m.modelData === (GlobalConfig.ai.activeClaudeAccount || "")) ?? menuItems[0] ?? null + menu.onItemSelected: item => { + GlobalConfig.ai.activeClaudeAccount = item.modelData; + } + + menuItems: accountVariants.instances + + fallbackIcon: "person" + fallbackText: qsTr("Account") + stateLayer.disabled: true + + Variants { + id: accountVariants + + model: root.claudeAccountIds + + delegate: MenuItem { + required property string modelData + + text: root.accountLabel(modelData) + } + } + } + + + } + + Item { + id: contentStack + + anchors.top: selectorRow.bottom + anchors.bottom: parent.bottom + anchors.left: parent.left + anchors.right: parent.right + anchors.topMargin: Tokens.spacing.medium + + // Chat View + Item { + anchors.fill: parent + opacity: !isHistoryTab ? 1 : 0 + visible: opacity > 0 + + Behavior on opacity { NumberAnimation { duration: 250; easing.type: Easing.InOutQuad } } + + VerticalFadeListView { + id: listView + + anchors.top: parent.top + anchors.bottom: inputBoxRow.top + anchors.left: parent.left + anchors.right: parent.right + anchors.bottomMargin: Tokens.spacing.medium + spacing: Tokens.spacing.medium + model: chatHistory + boundsBehavior: Flickable.StopAtBounds + + ColumnLayout { + anchors.centerIn: parent + opacity: chatHistory.count === 0 && !isTyping && !isThinking ? 1.0 : 0.0 + visible: opacity > 0 + + Behavior on opacity { NumberAnimation { duration: 250; easing.type: Easing.InOutQuad } } + + spacing: Tokens.spacing.large + + Item { + Layout.alignment: Qt.AlignHCenter + implicitWidth: 72 + implicitHeight: 72 + + Logo { + id: emptyStateLogo + + anchors.fill: parent + visible: false // hide original for MultiEffect to take over + } + + MultiEffect { + anchors.fill: parent + source: emptyStateLogo + colorization: 1.0 + colorizationColor: Colours.palette.m3primary + } + } + + StyledText { + id: greetingText + Layout.alignment: Qt.AlignHCenter + Layout.maximumWidth: listView.width - (Tokens.padding.large * 2) + + horizontalAlignment: Text.AlignHCenter + wrapMode: Text.Wrap + font: Tokens.font.title.medium + color: Colours.palette.m3onSurfaceVariant + + property var phrases: [ + "Ask away, %1!", + "How can I help you today, %1?", + "What's on your mind, %1?", + "Ready when you are, %1!", + "Let's get started, %1.", + "What shall we explore today, %1?", + "I'm all ears, %1!" + ] + + Component.onCompleted: { + var user = Quickshell.env("USER") || "user"; + var userCapitalized = user.charAt(0).toUpperCase() + user.slice(1); + var phrase = phrases[Math.floor(Math.random() * phrases.length)]; + text = phrase.replace("%1", userCapitalized); + } + } + } + + ScrollBar.vertical: StyledScrollBar { + flickable: listView + } + + footer: Item { + width: listView.width + height: isThinking ? bubbleBg.height + Tokens.spacing.medium : 0 + visible: opacity > 0 + opacity: isThinking ? 1 : 0 + + Behavior on height { Anim { type: Anim.DefaultSpatial } } + Behavior on opacity { Anim { type: Anim.DefaultSpatial } } + + StyledRect { + id: bubbleBg + + y: Tokens.spacing.medium / 2 + width: Math.min(listView.width * 0.85, footerCol.implicitWidth + Tokens.padding.medium * 2 + 8) + height: footerCol.implicitHeight + Tokens.padding.medium * 2 + radius: Tokens.rounding.large + color: Colours.tPalette.m3surfaceContainer + + // Asymmetric corners + topLeftRadius: Tokens.rounding.large + topRightRadius: Tokens.rounding.large + bottomLeftRadius: 4 + bottomRightRadius: Tokens.rounding.large + + Column { + id: footerCol + + anchors.fill: parent + anchors.margins: Tokens.padding.medium + spacing: Tokens.spacing.small + + Row { + spacing: Tokens.spacing.small + + LoadingIndicator { + width: 20 + height: 20 + color: Colours.palette.m3primary + } + + // M3 Expressive Animated Text Wrapper + Item { + width: mainText.implicitWidth + height: mainText.implicitHeight + // The bubble smoothly expands/shrinks as the text width changes + + Behavior on width { NumberAnimation { duration: 300; easing.type: Easing.OutCubic } } + + StyledText { + id: mainText + + text: displayedText + color: Colours.palette.m3onSurfaceVariant + font: Tokens.font.body.small + + property string displayedText: root.currentActionText + + property string nextText: "" + + transform: Translate { id: textTrans; y: 0 } + opacity: 1.0 + + Connections { + target: root + + function onCurrentActionTextChanged() { + if (root.currentActionText !== mainText.displayedText) { + mainText.nextText = root.currentActionText; + switchAnim.restart(); + } + } + } + + SequentialAnimation { + id: switchAnim + + ParallelAnimation { + NumberAnimation { target: textTrans; property: "y"; to: -8; duration: 150; easing.type: Easing.InCubic } + NumberAnimation { target: mainText; property: "opacity"; to: 0.0; duration: 150; easing.type: Easing.InCubic } + } + PropertyAction { target: mainText; property: "displayedText"; value: mainText.nextText } + PropertyAction { target: textTrans; property: "y"; value: 8 } + ParallelAnimation { + NumberAnimation { target: textTrans; property: "y"; to: 0; duration: 400; easing.type: Easing.OutBack; easing.overshoot: 1.5 } + NumberAnimation { target: mainText; property: "opacity"; to: 1.0; duration: 250; easing.type: Easing.OutQuad } + } + } + + SequentialAnimation { + running: isThinking && !switchAnim.running + loops: Animation.Infinite + + NumberAnimation { target: mainText; property: "opacity"; from: 1.0; to: 0.4; duration: 800; easing.type: Easing.InOutSine } + NumberAnimation { target: mainText; property: "opacity"; from: 0.4; to: 1.0; duration: 800; easing.type: Easing.InOutSine } + } + } + } + + Item { + visible: root.currentThoughtText !== "" + width: Tokens.spacing.medium + height: 1 + } + + Item { + visible: root.currentThoughtText !== "" + width: thoughtRowFooter.implicitWidth + height: thoughtRowFooter.implicitHeight + + Row { + id: thoughtRowFooter + + spacing: Tokens.spacing.small + + MaterialIcon { + text: "expand_more" + color: Colours.palette.m3onSurfaceVariant + font: Tokens.font.icon.small + rotation: root.isThoughtExpanded ? 180 : 0 + + Behavior on rotation { NumberAnimation { duration: 150; easing.type: Easing.OutQuad } } + } + } + MouseArea { + anchors.fill: parent + anchors.margins: -10 + cursorShape: Qt.PointingHandCursor + onClicked: root.isThoughtExpanded = !root.isThoughtExpanded + } + } + } + Item { + id: footerThoughtContentWrapper + + width: footerThoughtContent.width + height: root.isThoughtExpanded ? footerThoughtContent.implicitHeight : 0 + clip: true + + Behavior on height { NumberAnimation { duration: 200; easing.type: Easing.InOutQuad } } + + TextEdit { + id: footerThoughtContent + + width: Math.min(implicitWidth, listView.width * 0.85 - Tokens.padding.medium * 2) + textFormat: Text.MarkdownText + text: root.currentThoughtText + color: Colours.palette.m3onSurfaceVariant + font: Tokens.font.body.small + wrapMode: Text.Wrap + readOnly: true + selectByMouse: true + selectionColor: Colours.palette.m3primary + selectedTextColor: Colours.palette.m3onPrimary + opacity: root.isThoughtExpanded ? 1.0 : 0.0 + + Behavior on opacity { + SequentialAnimation { + PauseAnimation { duration: root.isThoughtExpanded ? 100 : 0 } + NumberAnimation { duration: 150; easing.type: Easing.InOutQuad } + } + } + } + } + } + } + } + + delegate: Item { + id: delegateItem + + required property string text + required property bool isUser + required property bool isFinished + required property string thoughtText + required property bool isSettingsPlan + required property string planLabel + required property var planOps + required property string planResolved + required property string planResult + required property bool isCommandPlan + required property string cmdLabel + required property var cmdLines + required property string cmdResolved + required property string cmdResult + + width: listView.width - Tokens.padding.large + visible: (!delegateItem.isFinished && isThinking) ? false : (delegateItem.text !== "" || delegateItem.thoughtText !== "" || delegateItem.isSettingsPlan || delegateItem.isCommandPlan) + height: visible ? bubbleRect.height : 0 + + scale: 0.0 + opacity: 0.0 + + Component.onCompleted: { + popInAnim.start(); + } + + ParallelAnimation { + id: popInAnim + + NumberAnimation { target: delegateItem; property: "scale"; from: 0.8; to: 1.0; duration: 300; easing.type: Easing.OutBack } + NumberAnimation { target: delegateItem; property: "opacity"; from: 0.0; to: 1.0; duration: 200; easing.type: Easing.OutQuad } + } + + SequentialAnimation { + id: popDoneAnim + + NumberAnimation { target: delegateItem; property: "scale"; from: 1.0; to: 1.02; duration: 100; easing.type: Easing.OutQuad } + NumberAnimation { target: delegateItem; property: "scale"; from: 1.02; to: 1.0; duration: 150; easing.type: Easing.OutSine } + } + + onIsFinishedChanged: { + if (isFinished) popDoneAnim.start(); + } + + StyledRect { + id: bubbleRect + + readonly property real maxBubbleWidth: delegateItem.width * 0.85 + + anchors.right: delegateItem.isUser ? parent.right : undefined + anchors.left: delegateItem.isUser ? undefined : parent.left + + // Let implicitWidth dictate width (with +8 buffer for layout engine) to stop short words from splitting line breaks + width: Math.min(maxBubbleWidth, bubbleLayout.implicitWidth + Tokens.padding.medium * 2 + 8) + height: bubbleLayout.implicitHeight + Tokens.padding.medium * 2 + radius: Tokens.rounding.large + color: delegateItem.isUser ? Colours.palette.m3primary : Colours.tPalette.m3surfaceContainer + + // Asymmetric corners + topLeftRadius: Tokens.rounding.large + topRightRadius: Tokens.rounding.large + bottomLeftRadius: delegateItem.isUser ? Tokens.rounding.large : 4 + bottomRightRadius: delegateItem.isUser ? 4 : Tokens.rounding.large + + Column { + id: bubbleLayout + + anchors.top: parent.top + anchors.left: parent.left + anchors.margins: Tokens.padding.medium + spacing: Tokens.spacing.small + + property string delegateThought: delegateItem.thoughtText + + property bool isExpanded: false + + Item { + visible: bubbleLayout.delegateThought !== "" + implicitWidth: thoughtRow.implicitWidth + implicitHeight: thoughtRow.implicitHeight + height: visible ? implicitHeight : 0 + + Row { + id: thoughtRow + + spacing: Tokens.spacing.small + + Text { + text: qsTr("Thought Process") + color: Colours.palette.m3onSurfaceVariant + font: Tokens.font.body.small + } + MaterialIcon { + id: thoughtArrow + + text: "expand_more" + color: Colours.palette.m3onSurfaceVariant + font: Tokens.font.icon.small + rotation: bubbleLayout.isExpanded ? 180 : 0 + + Behavior on rotation { NumberAnimation { duration: 150; easing.type: Easing.OutQuad } } + } + } + MouseArea { + anchors.fill: parent + cursorShape: Qt.PointingHandCursor + onClicked: bubbleLayout.isExpanded = !bubbleLayout.isExpanded + } + } + + Item { + id: thoughtContentWrapper + + width: thoughtContent.width + height: bubbleLayout.isExpanded ? thoughtContent.implicitHeight : 0 + clip: true + + Behavior on height { NumberAnimation { duration: 200; easing.type: Easing.InOutQuad } } + + TextEdit { + id: thoughtContent + + width: Math.min(implicitWidth, bubbleRect.maxBubbleWidth - Tokens.padding.medium * 2) + textFormat: Text.MarkdownText + + property string fullThought: bubbleLayout.delegateThought + + property bool cursorVisible: true + + Timer { + running: !delegateItem.isFinished + repeat: true + interval: 400 + onTriggered: thoughtContent.cursorVisible = !thoughtContent.cursorVisible + } + + text: delegateItem.isFinished ? fullThought : fullThought + (cursorVisible ? "▌" : "") + + color: Colours.palette.m3onSurfaceVariant + + font: Tokens.font.body.small + + wrapMode: Text.Wrap + + readOnly: true + + selectByMouse: true + + selectionColor: Colours.palette.m3primary + + selectedTextColor: Colours.palette.m3onPrimary + + opacity: bubbleLayout.isExpanded ? 1.0 : 0.0 + + Behavior on opacity { + SequentialAnimation { + PauseAnimation { duration: bubbleLayout.isExpanded ? 100 : 0 } + NumberAnimation { duration: 150; easing.type: Easing.InOutQuad } + } + } + } + } + + // Settings plan confirm card (issue #120): + // the preview-then-confirm flow for multi-op plans. + Column { + id: settingsPlanCard + + visible: delegateItem.isSettingsPlan + width: bubbleRect.maxBubbleWidth - Tokens.padding.medium * 2 + spacing: Tokens.spacing.small + + StyledText { + width: parent.width + wrapMode: Text.Wrap + text: delegateItem.planResolved === "" + ? (delegateItem.planLabel !== "" + ? qsTr("I found several changes that match your request (%1):").arg(delegateItem.planLabel) + : qsTr("I found several changes that match your request:")) + : (delegateItem.planResolved === "applied" + ? qsTr("Applied:") + : (delegateItem.planResolved === "superseded" + ? qsTr("Superseded by a newer request:") + : qsTr("Cancelled — nothing was written:"))) + color: Colours.palette.m3onSurface + font: Tokens.font.body.small + } + + Repeater { + model: delegateItem.planOps + + delegate: StyledText { + required property var modelData + width: settingsPlanCard.width + wrapMode: Text.Wrap + text: (modelData.noOp ? "· " : "– ") + + modelData.path + ": " + + modelData.from + " → " + modelData.to + + (modelData.noOp ? " (already set)" : "") + color: modelData.noOp + ? Colours.palette.m3onSurfaceVariant + : Colours.palette.m3onSurface + font: Tokens.font.body.small + } + } + + Row { + visible: delegateItem.planResolved === "" + spacing: Tokens.spacing.small + + TextButton { + text: qsTr("Apply changes") + type: TextButton.Filled + font: Tokens.font.body.small + onClicked: root.resolveSettingsCard(true) + } + + TextButton { + text: qsTr("Cancel") + type: TextButton.Text + font: Tokens.font.body.small + onClicked: root.resolveSettingsCard(false) + } + } + + StyledText { + visible: delegateItem.planResult !== "" + width: parent.width + wrapMode: Text.Wrap + text: delegateItem.planResult + color: Colours.palette.m3onSurfaceVariant + font: Tokens.font.body.small + } + } + + // Command approval card (the execution gate for + // caelestia_command / open_app / set_timer): the exact + // command the model asked for, verbatim, with the + // user's Apply or Cancel as the only way forward. + Column { + id: commandPlanCard + + visible: delegateItem.isCommandPlan + width: bubbleRect.maxBubbleWidth - Tokens.padding.medium * 2 + spacing: Tokens.spacing.small + + StyledText { + width: parent.width + wrapMode: Text.Wrap + text: delegateItem.cmdResolved === "" + ? (delegateItem.cmdLabel !== "" + ? qsTr("%1 — needs your approval:").arg(delegateItem.cmdLabel) + : qsTr("This needs your approval:")) + : (delegateItem.cmdResolved === "superseded" + ? qsTr("Superseded by a newer request — nothing was run:") + : (delegateItem.cmdResolved === "approved" + ? qsTr("Approved:") + : qsTr("Cancelled — nothing was run:"))) + color: Colours.palette.m3onSurface + font: Tokens.font.body.small + } + + Repeater { + model: delegateItem.cmdLines + + delegate: StyledText { + required property var modelData + + width: commandPlanCard.width + wrapMode: Text.Wrap + text: "– " + modelData + color: Colours.palette.m3onSurface + font: Tokens.font.body.small + } + } + + Row { + visible: delegateItem.cmdResolved === "" + spacing: Tokens.spacing.small + + TextButton { + text: qsTr("Run it") + type: TextButton.Filled + font: Tokens.font.body.small + onClicked: root.resolveCommandCard(true) + } + + TextButton { + text: qsTr("Cancel") + type: TextButton.Text + font: Tokens.font.body.small + onClicked: root.resolveCommandCard(false) + } + } + + StyledText { + visible: delegateItem.cmdResult !== "" + width: parent.width + wrapMode: Text.Wrap + text: delegateItem.cmdResult + color: Colours.palette.m3onSurfaceVariant + font: Tokens.font.body.small + } + } + + TextEdit { + id: messageText + + visible: !delegateItem.isSettingsPlan && !delegateItem.isCommandPlan + textFormat: Text.MarkdownText + width: Math.min(implicitWidth, bubbleRect.maxBubbleWidth - Tokens.padding.medium * 2) + + property string fullText: delegateItem.text !== undefined ? delegateItem.text : "" + + property bool cursorVisible: true + + Timer { + running: !delegateItem.isFinished + repeat: true + interval: 400 + onTriggered: messageText.cursorVisible = !messageText.cursorVisible + } + + text: delegateItem.isFinished ? fullText : fullText + (cursorVisible ? "▌" : "") + + color: delegateItem.isUser ? Colours.palette.m3onPrimary : Colours.palette.m3onSurface + + font: Tokens.font.body.small + + wrapMode: Text.Wrap + + readOnly: true + + selectByMouse: true + + selectionColor: Colours.palette.m3primary + + selectedTextColor: Colours.palette.m3onPrimary + + MouseArea { + anchors.fill: parent + hoverEnabled: true + cursorShape: Qt.IBeamCursor + propagateComposedEvents: true + onPressed: mouse => mouse.accepted = false + } + } + } + } + } + } + + // Scroll to bottom button + Item { + id: scrollBtnWrapper + + anchors.bottom: inputBoxRow.top + anchors.bottomMargin: Tokens.spacing.large + anchors.right: parent.right + anchors.rightMargin: Tokens.padding.large + width: 36 + height: 36 + z: 20 + opacity: (!listView.atYEnd && chatHistory.count > 0) ? 1.0 : 0.0 + visible: opacity > 0 + + Behavior on opacity { NumberAnimation { duration: 200; easing.type: Easing.InOutQuad } } + + StyledRect { + id: scrollBtnBg + + anchors.fill: parent + radius: 18 + color: Colours.tPalette.m3surfaceContainerHigh + } + + MultiEffect { + anchors.fill: scrollBtnBg + source: scrollBtnBg + shadowEnabled: true + shadowOpacity: 0.3 + shadowBlur: 0.5 + shadowVerticalOffset: 2 + } + + MaterialIcon { + anchors.centerIn: parent + text: "arrow_downward" + font: Tokens.font.icon.small + color: Colours.palette.m3onSurface + } + + MouseArea { + anchors.fill: parent + cursorShape: Qt.PointingHandCursor + onClicked: listView.positionViewAtEnd() + } + } + + // Prompt suggestion chips (Claude Code) — float just above the input. + ColumnLayout { + id: suggestionBox + + anchors.bottom: inputBoxRow.top + anchors.bottomMargin: Tokens.spacing.small + anchors.left: parent.left + anchors.right: parent.right + z: 11 + spacing: Tokens.spacing.small + visible: root.isClaudeCode && root.promptSuggestions.length > 0 + + // Header with a close button. + RowLayout { + Layout.fillWidth: true + spacing: Tokens.spacing.small + + StyledText { + Layout.fillWidth: true + text: qsTr("Suggestions") + color: Colours.palette.m3onSurfaceVariant + font: Tokens.font.label.small + } + + Item { + Layout.preferredWidth: 24 + Layout.preferredHeight: 24 + + MaterialIcon { + anchors.centerIn: parent + text: "close" + color: closeSugMouse.containsMouse ? Colours.palette.m3onSurface : Colours.palette.m3onSurfaceVariant + font: Tokens.font.icon.small + } + + MouseArea { + id: closeSugMouse + + anchors.fill: parent + hoverEnabled: true + cursorShape: Qt.PointingHandCursor + onClicked: root.promptSuggestions = [] + } + } + } + + Repeater { + model: root.promptSuggestions + + StyledRect { + required property string modelData + Layout.fillWidth: true + + implicitHeight: sugChipText.implicitHeight + Tokens.padding.medium * 2 + radius: Tokens.rounding.large + color: Colours.tPalette.m3surfaceContainerHigh + + StateLayer { + radius: Tokens.rounding.large + onClicked: { + inputArea.text = modelData; + root.promptSuggestions = []; + inputArea.forceActiveFocus(); + } + } + + StyledText { + id: sugChipText + + anchors.left: parent.left + anchors.right: parent.right + anchors.top: parent.top + anchors.leftMargin: Tokens.padding.medium + anchors.rightMargin: Tokens.padding.medium + anchors.topMargin: Tokens.padding.medium + text: parent.modelData + color: Colours.palette.m3onSurface + font: Tokens.font.body.small + wrapMode: Text.Wrap + } + } + } + } + + // Input Box Row + StyledRect { + id: inputBoxRow + + anchors.bottom: parent.bottom + anchors.left: parent.left + anchors.right: parent.right + z: 10 + implicitHeight: Math.max(48, inputArea.implicitHeight + Tokens.padding.medium * 2) + color: Colours.tPalette.m3surfaceContainer + radius: 24 + + StyledClippingRect { + z: -1 + anchors.fill: parent + radius: 24 + + ShaderEffectSource { + id: inputBlurSource + + sourceItem: contentStack + sourceRect: { + var p = parent.mapToItem(contentStack, 0, 0); + return Qt.rect(p.x, p.y, parent.width, parent.height); + } + } + MultiEffect { + anchors.fill: parent + source: inputBlurSource + blurEnabled: true + blurMax: 32 + } + } + + StateLayer { + id: inputStateLayer + + anchors.fill: parent + radius: 24 + hoverEnabled: false + cursorShape: Qt.IBeamCursor + onClicked: inputArea.forceActiveFocus() + } + + RowLayout { + anchors.fill: parent + anchors.leftMargin: Tokens.padding.large + anchors.rightMargin: Tokens.padding.small + spacing: Tokens.spacing.small + + ScrollView { + id: inputScroll + Layout.fillWidth: true + Layout.fillHeight: true + + TextArea { + id: inputArea + + verticalAlignment: TextInput.AlignVCenter + placeholderText: qsTr("Ask assistant...") + color: Colours.palette.m3onSurface + placeholderTextColor: Colours.palette.m3outline + font: Tokens.font.body.small + wrapMode: Text.Wrap + selectByMouse: true + background: null + + MouseArea { + anchors.fill: parent + hoverEnabled: true + cursorShape: Qt.IBeamCursor + propagateComposedEvents: true + onPressed: mouse => { + var mapped = mapToItem(inputStateLayer, mouse.x, mouse.y); + inputStateLayer.press(mapped.x, mapped.y); + mouse.accepted = false; + } + } + + Keys.onPressed: event => { + if (event.key === Qt.Key_Return && !(event.modifiers & Qt.ShiftModifier)) { + event.accepted = true; + root.sendPrompt(inputArea.text); + inputArea.clear(); + } + } + } + } + + // Prompt suggestions trigger (Claude Code). + Item { + visible: root.isClaudeCode + Layout.preferredWidth: visible ? 32 : 0 + Layout.preferredHeight: 32 + + MaterialIcon { + anchors.centerIn: parent + text: root.loadingSuggestions ? "hourglass_empty" : "lightbulb" + color: sugMouse.containsMouse ? Colours.palette.m3primary : Colours.palette.m3onSurfaceVariant + font: Tokens.font.icon.small + } + + MouseArea { + id: sugMouse + + anchors.fill: parent + hoverEnabled: true + cursorShape: Qt.PointingHandCursor + onClicked: root.fetchPromptSuggestions() + } + } + + Item { + Layout.preferredWidth: 36 + Layout.preferredHeight: 36 + + MaterialShape { + anchors.fill: parent + color: root.isTyping ? Colours.palette.m3error : (inputArea.text.length > 0 ? Colours.palette.m3primary : Colours.layer(Colours.tPalette.m3surfaceContainerHigh, 2)) + shape: root.isTyping ? MaterialShape.Cookie4Sided : (inputArea.text.length > 0 ? MaterialShape.Arrow : MaterialShape.Circle) + scale: (inputArea.text.length === 0 && !root.isTyping) ? 1 : sendMouse.pressed ? 0.6 : sendMouse.containsMouse ? 0.8 : 0.7 + rotation: 0 + + Behavior on scale { Anim { type: Anim.FastSpatial } } + Behavior on color { CAnim {} } + + MouseArea { + id: sendMouse + + anchors.fill: parent + hoverEnabled: true + cursorShape: (inputArea.text.length > 0 || root.isTyping) ? Qt.PointingHandCursor : Qt.ArrowCursor + onClicked: { + if (root.isTyping) { + root.cancelRateLimitRetry(); + if (root.currentRequest) { + root.currentRequest.abort(); + } + root.stopClaudeCode(); + root.isTyping = false; + root.isThinking = false; + root.inAgentLoop = false; + typingTimer.stop(); + chatHistory.setProperty(chatHistory.count - 1, "isFinished", true); + saveHistory(); + } else if (inputArea.text.length > 0) { + root.sendPrompt(inputArea.text); + inputArea.clear(); + } + } + } + } + + MaterialIcon { + anchors.centerIn: parent + text: "arrow_upward" + color: Colours.palette.m3onSurfaceVariant + font: Tokens.font.icon.small + opacity: (inputArea.text.length > 0 || root.isTyping) ? 0 : 1 + + Behavior on opacity { Anim { type: Anim.DefaultEffects } } + } + } + } + } + } + + // History Grid View + Item { + anchors.fill: parent + opacity: isHistoryTab ? 1 : 0 + visible: opacity > 0 + + Behavior on opacity { NumberAnimation { duration: 250; easing.type: Easing.InOutQuad } } + + GridView { + anchors.top: parent.top + anchors.left: parent.left + anchors.right: parent.right + anchors.bottom: newChatButton.top + anchors.bottomMargin: Tokens.spacing.medium + + cellWidth: width / 2 + cellHeight: 90 + model: historySessionsModel + + delegate: Item { + required property var model + property string chatId: model && model.id ? String(model.id) : "" + property string chatTitle: model && model.title ? String(model.title) : "" + + width: GridView.view.cellWidth + height: GridView.view.cellHeight + + StyledRect { + anchors.fill: parent + anchors.margins: Tokens.spacing.small + radius: Tokens.rounding.medium + color: Colours.tPalette.m3surfaceContainerHigh + + StateLayer { + radius: Tokens.rounding.medium + onClicked: loadChat(chatId) + } + + RowLayout { + anchors.fill: parent + anchors.margins: Tokens.padding.small + spacing: Tokens.spacing.medium + + StyledRect { + Layout.preferredWidth: 32 + Layout.preferredHeight: 32 + radius: 16 + color: Colours.tPalette.m3surfaceContainerHighest + + MaterialIcon { + anchors.centerIn: parent + text: "chat" + color: Colours.palette.m3onSurfaceVariant + font: Tokens.font.icon.small + } + } + + ColumnLayout { + Layout.fillWidth: true + spacing: 0 + + Text { + Layout.fillWidth: true + Layout.alignment: Qt.AlignVCenter + text: chatTitle ? chatTitle : "New Chat" + color: Colours.palette.m3onSurface + font: Tokens.font.label.small + elide: Text.ElideRight + wrapMode: Text.Wrap + maximumLineCount: 3 + } + } + + Item { + Layout.alignment: Qt.AlignTop | Qt.AlignRight + Layout.preferredWidth: 24 + Layout.preferredHeight: 24 + + StyledRect { + anchors.fill: parent + radius: 12 + color: Colours.palette.m3onSurfaceVariant + opacity: deleteMouseArea.containsMouse ? 0.12 : 0.0 + + Behavior on opacity { NumberAnimation { duration: 150 } } + } + + MaterialIcon { + anchors.centerIn: parent + text: "close" + font: Tokens.font.icon.small + color: Colours.palette.m3onSurfaceVariant + } + + MouseArea { + id: deleteMouseArea + + anchors.fill: parent + hoverEnabled: true + cursorShape: Qt.PointingHandCursor + onClicked: deleteChat(chatId) + } + } + } + } + } + } + + // "Clear All" button + StyledRect { + id: clearAllButton + + anchors.bottom: parent.bottom + anchors.left: parent.left + width: clearAllLayout.implicitWidth + Tokens.padding.large * 2 + height: 32 + radius: 16 + color: Colours.palette.m3errorContainer + + StateLayer { + radius: 16 + onClicked: clearAllHistory() + } + + RowLayout { + id: clearAllLayout + + anchors.centerIn: parent + spacing: Tokens.spacing.small + + MaterialIcon { + text: "delete" + color: Colours.palette.m3onErrorContainer + font: Tokens.font.icon.small + } + Text { + text: qsTr("Clear All") + color: Colours.palette.m3onErrorContainer + font: Tokens.font.body.small + } + } + } + + // "New Chat" button + StyledRect { + id: newChatButton + + anchors.bottom: parent.bottom + anchors.right: parent.right + width: newChatLayout.implicitWidth + Tokens.padding.large * 2 + height: 32 + radius: 16 + color: Colours.palette.m3primaryContainer + + StateLayer { + radius: 16 + onClicked: createNewChat() + } + + RowLayout { + id: newChatLayout + + anchors.centerIn: parent + spacing: Tokens.spacing.small + + MaterialIcon { + text: "add" + color: Colours.palette.m3onPrimaryContainer + font: Tokens.font.icon.small + } + Text { + text: qsTr("New Chat") + color: Colours.palette.m3onPrimaryContainer + font: Tokens.font.body.small + } + } + } + } + } + } +} \ No newline at end of file diff --git a/plugins/caelestia-assistant/assistant/adapters/caelestia/shell/services/CommandGate.qml b/plugins/caelestia-assistant/assistant/adapters/caelestia/shell/services/CommandGate.qml new file mode 100644 index 0000000..da4cda3 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/adapters/caelestia/shell/services/CommandGate.qml @@ -0,0 +1,122 @@ +pragma Singleton +pragma ComponentBehavior: Bound + +// Caelestia in-shell command gate — the execution boundary for the sidebar +// AI's state-changing tools. +// +// The settings tools have their validated gate (SettingsTools.qml: allow-list, +// preview, explicit confirm). This is the SAME gate shape for every other +// state-changing tool the sidebar's model can request: `caelestia_command`, +// `open_app`, `set_timer`. Nothing here executes anything — the gate only +// decides whether a request may run immediately (verified read-only +// allow-list) or must wait for the user's explicit approval on a preview +// card, and holds the pending payload until then. The caller executes; the +// gate never does. This closes the prompt-injection-to-execution path: a +// webpage's text can at worst produce a card the user ignores, never a +// silently-launched command. +// +// Allow-list provenance (verified 2026-09-26 against upstream +// src/bin/caelestia @ dev, read in full): +// - `version` / `help` print and exit (cmd_version / usage bodies). +// - `scheme list` / `scheme get` are the CLI usage's declared read forms +// ("scheme [...] manage the color scheme"); `set` is the +// write form and is NOT allow-listed. Only the bare read forms are +// allow-listed — any extra argument falls back to confirmation. +// - NOT allow-listed, each for a verified reason: `shell` (runs +// `caelestia-shell-ipc start` on EVERY invocation, even for -s/-l), +// `install` (runs the installer), `update` (updates and re-applies), +// `wallpaper` (sets the wallpaper and derives the palette), +// `screenshot` (spawns a capture), `record` (screen recording). +// +// One pending command at a time; a newer request supersedes an older +// unresolved one (which resolves as cancelled), mirroring SettingsTools. + +import QtQuick +import Quickshell + +Singleton { + id: root + + // The payload of the request waiting for the user's Apply. + property var pending: null + + // Verified read-only `caelestia` subcommands (see header for provenance). + readonly property var caelestiaReadOnly: ["version", "help"] + + function isReadOnlyCaelestia(argv) { + if (!argv || argv.length < 2 || String(argv[0]) !== "caelestia") + return false; + var sub = String(argv[1]); + if (caelestiaReadOnly.indexOf(sub) !== -1) + return true; // `caelestia version`, `caelestia help` + if (sub === "scheme" && argv.length === 3) { + // bare read forms only: `caelestia scheme list`, `caelestia scheme get` + var mode = String(argv[2]); + return mode === "list" || mode === "get"; + } + return false; + } + + // argv: the exact array that would run (["caelestia", sub, ...]). + // Returns {ok, needsConfirm?, preview?, reason?}; the preview carries + // what the confirmation card shows — the command itself, verbatim. + function requestCaelestia(argv) { + if (!Array.isArray(argv) || argv.length < 2) { + return { ok: false, reason: "caelestia_command needs a subcommand" }; + } + if (isReadOnlyCaelestia(argv)) { + return { ok: true, needsConfirm: false }; // verified read-only: runs + } + pending = { kind: "caelestia", argv: argv.slice() }; + return { ok: true, needsConfirm: true, preview: { + kind: "caelestia", + label: qsTr("Run a caelestia command"), + lines: [argv.join(" ")] + } }; + } + + function requestOpenApp(appName) { + var name = String(appName || "").trim(); + if (!name) { + return { ok: false, reason: "open_app needs an app name" }; + } + pending = { kind: "open_app", app: name }; + return { ok: true, needsConfirm: true, preview: { + kind: "open_app", + label: qsTr("Open an application"), + lines: [name] + } }; + } + + function requestTimer(seconds, message) { + var secs = Number(seconds) || 0; + if (secs <= 0) { + return { ok: false, reason: "set_timer needs a positive number of seconds" }; + } + pending = { kind: "set_timer", seconds: secs, + message: String(message || "Timer finished") }; + return { ok: true, needsConfirm: true, preview: { + kind: "set_timer", + label: qsTr("Set a timer"), + lines: [Math.round(secs) + " s — " + String(message || "Timer finished")] + } }; + } + + // The card's Apply: hands the payload back for the CALLER to execute. + // The gate itself still executes nothing. + function confirm() { + if (!pending) + return { ok: false, reason: "no pending command to confirm" }; + var p = pending; + pending = null; + return { ok: true, kind: p.kind, payload: p }; + } + + // The card's Cancel (or supersede): nothing runs, nothing is kept. + function cancel() { + if (!pending) + return { ok: false, reason: "no pending command to cancel" }; + pending = null; + return { ok: true, applied: false }; + } +} diff --git a/plugins/caelestia-assistant/assistant/adapters/caelestia/shell/services/SettingsTools.qml b/plugins/caelestia-assistant/assistant/adapters/caelestia/shell/services/SettingsTools.qml new file mode 100755 index 0000000..fd4372b --- /dev/null +++ b/plugins/caelestia-assistant/assistant/adapters/caelestia/shell/services/SettingsTools.qml @@ -0,0 +1,828 @@ +pragma Singleton +pragma ComponentBehavior: Bound + +// Caelestia in-shell settings tool service (issue #120). +// +// One native QML boundary between the sidebar AI assistant's tool loop and +// ConfigObject: the same 277-tool validated registry the offline Python CLI +// uses (assistant/settings/tools.json), applied through the same property +// writes every Nexus page performs (GlobalConfig. = value), with +// these behaviors: +// - preview-then-confirm for any request resolving to more than one tool +// call (single-setting requests apply directly, exactly as the issue +// frames it); +// - a bounded undo history (12 applies, oldest evicted first) persisted at +// ~/.local/state/caelestia/assistant-settings-history.json; +// - read-only explainability grounded in the same registry + citations; +// - named presets as bundles of validated tool calls, never bespoke code. +// +// The registry/preset/explain tables below are GENERATED from tools.json +// and committed verbatim; a Python unittest (test_qml_service.py) asserts +// the shipped table matches tools.json byte-for-byte. Validation mirrors +// assistant/settings/planner.py's set-branch semantics: out-of-range values +// are rejected, never clamped; type mismatches are rejected, never coerced. + +import QtQuick +import Quickshell +import Quickshell.Io +import Caelestia.Config +import qs.services +import qs.utils + +Singleton { + id: root + + // How many applies the undo history remembers (issue #120: "a small + // history"; >= 10 required — 12 chosen). + readonly property int maxHistory: 12 + readonly property string historyPath: `${Paths.state}/assistant-settings-history.json` + + // A pending multi-op plan awaiting the user's Apply/Cancel (the + // preview-then-confirm flow). Null when none is pending. + property var pendingPlan: null + + property var history: [] + + property var toolsByName: ({}) + property var toolsByPath: ({}) + property var groups: [] + + // Generated from assistant/settings/tools.json by + // scripts/assemble_settings_tools.py — DO NOT EDIT BY HAND. + // A unittest re-renders this block from tools.json and asserts + // byte-identity; regenerate via the script after rebuilding tools.json. + // Fields: n name, p path, g group, k kind, d default, lo/hi range, + // st step, en enum (array|null), sl stringMaxLen, go globalOnly. + readonly property var toolTable: [ + { n: "setBarDragThreshold", p: "bar.dragThreshold", g: "bar", k: "int", d: 20, lo: 0, hi: 200, st: 5, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/barconfig.hpp:224", "CONFIG declaration: int dragThreshold = 20"], ["shell/modules/nexus/pages/panels/TaskbarPanel.qml:107", "shipped Nexus control (StepperRow)"]] }, + { n: "setBarPersistent", p: "bar.persistent", g: "bar", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/barconfig.hpp:220", "CONFIG declaration: bool persistent = true"], ["shell/modules/nexus/pages/panels/TaskbarPanel.qml:67", "shipped Nexus control (ToggleRow)"], ["shell/modules/bar/BarWrapper.qml:27", "persistent reader"]] }, + { n: "setBarPosition", p: "bar.position", g: "bar", k: "enum", d: "bottom", lo: null, hi: null, st: null, en: ["top", "bottom", "left", "right"], sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/barconfig.hpp:225", "CONFIG declaration: QString position = u\"bottom\"_s"], ["shell/modules/nexus/pages/panels/TaskbarPanel.qml:91", "shipped Nexus control (SelectRow)"], ["shell/modules/bar/BarWrapper.qml:23", "position-driven anchoring"]] }, + { n: "setBarScale", p: "bar.scale", g: "bar", k: "float", d: 1.0, lo: 0.6, hi: 1.6, st: 0.1, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/barconfig.hpp:211", "CONFIG declaration: qreal scale = 1.0"], ["shell/modules/nexus/pages/panels/TaskbarPanel.qml:157", "shipped Nexus control (StepperRow)"], ["shell/modules/bar/BarWrapper.qml:24", "contentWidth = innerWidth * barScale; floor 0.6"]] }, + { n: "setBarShowOnHover", p: "bar.showOnHover", g: "bar", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/barconfig.hpp:223", "CONFIG declaration: bool showOnHover = true"], ["shell/modules/nexus/pages/panels/TaskbarPanel.qml:100", "shipped Nexus control (ToggleRow)"]] }, + { n: "setClockBackground", p: "bar.clock.background", g: "bar", k: "bool", d: false, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/barconfig.hpp:139", "CONFIG declaration: bool background = false"], ["shell/modules/nexus/pages/panels/taskbar/BarClock.qml:19", "shipped Nexus control (ToggleRow)"]] }, + { n: "setClockShowDate", p: "bar.clock.showDate", g: "bar", k: "bool", d: false, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/barconfig.hpp:140", "CONFIG declaration: bool showDate = false"], ["shell/modules/nexus/pages/panels/taskbar/BarClock.qml:26", "shipped Nexus control (ToggleRow)"]] }, + { n: "setClockShowIcon", p: "bar.clock.showIcon", g: "bar", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/barconfig.hpp:141", "CONFIG declaration: bool showIcon = true"], ["shell/modules/nexus/pages/panels/taskbar/BarClock.qml:32", "shipped Nexus control (ToggleRow)"]] }, + { n: "setClockShowSeconds", p: "bar.clock.showSeconds", g: "bar", k: "bool", d: false, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/barconfig.hpp:143", "CONFIG declaration: bool showSeconds = false"], ["shell/modules/nexus/pages/panels/taskbar/BarClock.qml:38", "shipped Nexus control (ToggleRow)"]] }, + { n: "setDodgeFocusedOnly", p: "bar.dodgeFocusedOnly", g: "bar", k: "bool", d: false, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/barconfig.hpp:222", "CONFIG declaration: bool dodgeFocusedOnly = false"], ["shell/modules/nexus/pages/panels/TaskbarPanel.qml:83", "shipped Nexus control (ToggleRow)"]] }, + { n: "setDodgeWindows", p: "bar.dodgeWindows", g: "bar", k: "bool", d: false, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/barconfig.hpp:221", "CONFIG declaration: bool dodgeWindows = false"], ["shell/modules/nexus/pages/panels/TaskbarPanel.qml:75", "shipped Nexus control (ToggleRow)"]] }, + { n: "setFontScaleOffset", p: "bar.fontScaleOffset", g: "bar", k: "float", d: 0.0, lo: -1.0, hi: 1.0, st: 0.05, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/barconfig.hpp:216", "CONFIG declaration: qreal fontScaleOffset = 0.0"], ["shell/modules/nexus/pages/panels/TaskbarPanel.qml:192", "shipped Nexus control (StepperRow)"]] }, + { n: "setGithubBackground", p: "bar.github.background", g: "bar", k: "bool", d: false, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/barconfig.hpp:161", "CONFIG declaration: bool background = false"], ["shell/modules/nexus/pages/panels/taskbar/BarGithub.qml:99", "shipped Nexus control (ToggleRow)"]] }, + { n: "setGreeterAfternoonStart", p: "bar.greeter.afternoonStart", g: "bar", k: "int", d: 12, lo: 0, hi: 23, st: 1, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/barconfig.hpp:83", "CONFIG declaration: int afternoonStart = 12"], ["shell/modules/nexus/pages/panels/taskbar/BarGreeter.qml:228", "shipped Nexus control (StepperRow)"]] }, + { n: "setGreeterCompact", p: "bar.greeter.compact", g: "bar", k: "bool", d: false, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/barconfig.hpp:71", "CONFIG declaration: bool compact = false"], ["shell/modules/nexus/pages/panels/taskbar/BarGreeter.qml:97", "shipped Nexus control (ToggleRow)"]] }, + { n: "setGreeterEveningStart", p: "bar.greeter.eveningStart", g: "bar", k: "int", d: 17, lo: 0, hi: 23, st: 1, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/barconfig.hpp:84", "CONFIG declaration: int eveningStart = 17"], ["shell/modules/nexus/pages/panels/taskbar/BarGreeter.qml:273", "shipped Nexus control (StepperRow)"]] }, + { n: "setGreeterInverted", p: "bar.greeter.inverted", g: "bar", k: "bool", d: false, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/barconfig.hpp:72", "CONFIG declaration: bool inverted = false"], ["shell/modules/nexus/pages/panels/taskbar/BarGreeter.qml:107", "shipped Nexus control (ToggleRow)"]] }, + { n: "setGreeterMode", p: "bar.greeter.mode", g: "bar", k: "enum", d: "timeOfDay", lo: null, hi: null, st: null, en: ["timeOfDay", "slideshow"], sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/barconfig.hpp:75", "CONFIG declaration: QString mode = u\"timeOfDay\"_s"], ["shell/modules/nexus/pages/panels/taskbar/BarGreeter.qml:141", "shipped Nexus control (SelectRow)"]] }, + { n: "setGreeterMorningStart", p: "bar.greeter.morningStart", g: "bar", k: "int", d: 5, lo: 0, hi: 23, st: 1, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/barconfig.hpp:82", "CONFIG declaration: int morningStart = 5"], ["shell/modules/nexus/pages/panels/taskbar/BarGreeter.qml:183", "shipped Nexus control (StepperRow)"]] }, + { n: "setGreeterNightStart", p: "bar.greeter.nightStart", g: "bar", k: "int", d: 20, lo: 0, hi: 23, st: 1, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/barconfig.hpp:85", "CONFIG declaration: int nightStart = 20"], ["shell/modules/nexus/pages/panels/taskbar/BarGreeter.qml:318", "shipped Nexus control (StepperRow)"]] }, + { n: "setGreeterShowOnHover", p: "bar.greeter.showOnHover", g: "bar", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/barconfig.hpp:73", "CONFIG declaration: bool showOnHover = true"], ["shell/modules/nexus/pages/panels/taskbar/BarGreeter.qml:116", "shipped Nexus control (ToggleRow)"]] }, + { n: "setGreeterSlideshowInterval", p: "bar.greeter.slideshowInterval", g: "bar", k: "float", d: 60.0, lo: 5, hi: 3600, st: 5, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/barconfig.hpp:96", "CONFIG declaration: qreal slideshowInterval = 60.0"], ["shell/modules/nexus/pages/panels/taskbar/BarGreeter.qml:352", "shipped Nexus control (StepperRow)"]] }, + { n: "setGreeterSlideshowRandom", p: "bar.greeter.slideshowRandom", g: "bar", k: "bool", d: false, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/barconfig.hpp:97", "CONFIG declaration: bool slideshowRandom = false"], ["shell/modules/nexus/pages/panels/taskbar/BarGreeter.qml:367", "shipped Nexus control (ToggleRow)"]] }, + { n: "setLivePreviews", p: "bar.livePreviews", g: "bar", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/barconfig.hpp:217", "CONFIG declaration: bool livePreviews = true"], ["shell/modules/nexus/pages/panels/TaskbarPanel.qml:178", "shipped Nexus control (ToggleRow)"], ["shell/components/images/WindowPreview.qml:42", "live reader"]] }, + { n: "setPopoutsGreeter", p: "bar.popouts.greeter", g: "bar", k: "bool", d: false, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/barconfig.hpp:27", "CONFIG declaration: bool greeter = false"], ["shell/modules/nexus/pages/panels/taskbar/BarGreeter.qml:126", "shipped Nexus control (ToggleRow)"]] }, + { n: "setPopoutsStatusIcons", p: "bar.popouts.statusIcons", g: "bar", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/barconfig.hpp:29", "CONFIG declaration: bool statusIcons = true"], ["shell/modules/nexus/pages/panels/taskbar/BarStatusIcons.qml:101", "shipped Nexus control (ToggleRow)"]] }, + { n: "setPopoutsTray", p: "bar.popouts.tray", g: "bar", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/barconfig.hpp:28", "CONFIG declaration: bool tray = true"], ["shell/modules/nexus/pages/panels/taskbar/BarTray.qml:39", "shipped Nexus control (ToggleRow)"]] }, + { n: "setPreviewScale", p: "bar.previewScale", g: "bar", k: "float", d: 1.0, lo: 0.5, hi: 1.6, st: 0.05, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/barconfig.hpp:212", "CONFIG declaration: qreal previewScale = 1.0"], ["shell/modules/nexus/pages/panels/TaskbarPanel.qml:168", "shipped Nexus control (StepperRow)"]] }, + { n: "setPreviewScaleWithBar", p: "bar.previewScaleWithBar", g: "bar", k: "bool", d: false, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/barconfig.hpp:213", "CONFIG declaration: bool previewScaleWithBar = false"], ["shell/modules/nexus/pages/panels/TaskbarPanel.qml:185", "shipped Nexus control (ToggleRow)"]] }, + { n: "setPreviewScalesAudio", p: "bar.previewScales.audio", g: "bar", k: "float", d: 0.0, lo: -1.0, hi: 1.0, st: 0.05, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/barconfig.hpp:174", "CONFIG declaration: qreal audio = 0.0"], ["shell/modules/nexus/pages/panels/taskbar/BarPreviewScales.qml:100", "shipped Nexus control (DoubleStepperRow)"]] }, + { n: "setPreviewScalesBattery", p: "bar.previewScales.battery", g: "bar", k: "float", d: 0.0, lo: -1.0, hi: 1.0, st: 0.05, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/barconfig.hpp:175", "CONFIG declaration: qreal battery = 0.0"], ["shell/modules/nexus/pages/panels/taskbar/BarPreviewScales.qml:113", "shipped Nexus control (DoubleStepperRow)"]] }, + { n: "setPreviewScalesBluetooth", p: "bar.previewScales.bluetooth", g: "bar", k: "float", d: 0.0, lo: -1.0, hi: 1.0, st: 0.05, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/barconfig.hpp:176", "CONFIG declaration: qreal bluetooth = 0.0"], ["shell/modules/nexus/pages/panels/taskbar/BarPreviewScales.qml:126", "shipped Nexus control (DoubleStepperRow)"]] }, + { n: "setPreviewScalesDock", p: "bar.previewScales.dock", g: "bar", k: "float", d: 0.0, lo: -1.0, hi: 1.0, st: 0.05, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/barconfig.hpp:178", "CONFIG declaration: qreal dock = 0.0"], ["shell/modules/nexus/pages/panels/taskbar/BarPreviewScales.qml:139", "shipped Nexus control (DoubleStepperRow)"]] }, + { n: "setPreviewScalesGithub", p: "bar.previewScales.github", g: "bar", k: "float", d: 0.0, lo: -1.0, hi: 1.0, st: 0.05, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/barconfig.hpp:179", "CONFIG declaration: qreal github = 0.0"], ["shell/modules/nexus/pages/panels/taskbar/BarPreviewScales.qml:152", "shipped Nexus control (DoubleStepperRow)"]] }, + { n: "setPreviewScalesGreeter", p: "bar.previewScales.greeter", g: "bar", k: "float", d: 0.0, lo: -1.0, hi: 1.0, st: 0.05, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/barconfig.hpp:173", "CONFIG declaration: qreal greeter = 0.0"], ["shell/modules/nexus/pages/panels/taskbar/BarPreviewScales.qml:81", "shipped Nexus control (DoubleStepperRow)"]] }, + { n: "setPreviewScalesLockStatus", p: "bar.previewScales.lockStatus", g: "bar", k: "float", d: 0.0, lo: -1.0, hi: 1.0, st: 0.05, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/barconfig.hpp:181", "CONFIG declaration: qreal lockStatus = 0.0"], ["shell/modules/nexus/pages/panels/taskbar/BarPreviewScales.qml:165", "shipped Nexus control (DoubleStepperRow)"]] }, + { n: "setPreviewScalesNetwork", p: "bar.previewScales.network", g: "bar", k: "float", d: 0.0, lo: -1.0, hi: 1.0, st: 0.05, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/barconfig.hpp:182", "CONFIG declaration: qreal network = 0.0"], ["shell/modules/nexus/pages/panels/taskbar/BarPreviewScales.qml:178", "shipped Nexus control (DoubleStepperRow)"]] }, + { n: "setPreviewScalesNotifications", p: "bar.previewScales.notifications", g: "bar", k: "float", d: 0.0, lo: -1.0, hi: 1.0, st: 0.05, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/barconfig.hpp:183", "CONFIG declaration: qreal notifications = 0.0"], ["shell/modules/nexus/pages/panels/taskbar/BarPreviewScales.qml:191", "shipped Nexus control (DoubleStepperRow)"]] }, + { n: "setPreviewScalesPeripheralBattery", p: "bar.previewScales.peripheralBattery", g: "bar", k: "float", d: 0.0, lo: -1.0, hi: 1.0, st: 0.05, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/barconfig.hpp:184", "CONFIG declaration: qreal peripheralBattery = 0.0"], ["shell/modules/nexus/pages/panels/taskbar/BarPreviewScales.qml:204", "shipped Nexus control (DoubleStepperRow)"]] }, + { n: "setPreviewScalesTrayMenu", p: "bar.previewScales.trayMenu", g: "bar", k: "float", d: 0.0, lo: -1.0, hi: 1.0, st: 0.05, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/barconfig.hpp:185", "CONFIG declaration: qreal trayMenu = 0.0"], ["shell/modules/nexus/pages/panels/taskbar/BarPreviewScales.qml:217", "shipped Nexus control (DoubleStepperRow)"]] }, + { n: "setPreviewScalesWirelessPassword", p: "bar.previewScales.wirelessPassword", g: "bar", k: "float", d: 0.0, lo: -1.0, hi: 1.0, st: 0.05, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/barconfig.hpp:186", "CONFIG declaration: qreal wirelessPassword = 0.0"], ["shell/modules/nexus/pages/panels/taskbar/BarPreviewScales.qml:230", "shipped Nexus control (DoubleStepperRow)"]] }, + { n: "setScrollActionsBrightness", p: "bar.scrollActions.brightness", g: "bar", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/barconfig.hpp:21", "CONFIG declaration: bool brightness = true"], ["shell/modules/nexus/pages/panels/TaskbarPanel.qml:249", "shipped Nexus control (ToggleRow)"]] }, + { n: "setScrollActionsVolume", p: "bar.scrollActions.volume", g: "bar", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/barconfig.hpp:20", "CONFIG declaration: bool volume = true"], ["shell/modules/nexus/pages/panels/TaskbarPanel.qml:242", "shipped Nexus control (ToggleRow)"]] }, + { n: "setScrollActionsWorkspaces", p: "bar.scrollActions.workspaces", g: "bar", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/barconfig.hpp:19", "CONFIG declaration: bool workspaces = true"], ["shell/modules/nexus/pages/panels/TaskbarPanel.qml:234", "shipped Nexus control (ToggleRow)"]] }, + { n: "setStatusShowWifi", p: "bar.status.showWifi", g: "bar", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/barconfig.hpp:126", "CONFIG declaration: bool showWifi = true"], ["shell/modules/nexus/pages/panels/taskbar/BarStatusIcons.qml:88", "shipped Nexus control (ToggleRow)"]] }, + { n: "setTrayBackground", p: "bar.tray.background", g: "bar", k: "bool", d: false, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/barconfig.hpp:112", "CONFIG declaration: bool background = false"], ["shell/modules/nexus/pages/panels/taskbar/BarTray.qml:20", "shipped Nexus control (ToggleRow)"]] }, + { n: "setTrayCompact", p: "bar.tray.compact", g: "bar", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/barconfig.hpp:114", "CONFIG declaration: bool compact = true"], ["shell/modules/nexus/pages/panels/taskbar/BarTray.qml:33", "shipped Nexus control (ToggleRow)"]] }, + { n: "setTrayRecolour", p: "bar.tray.recolour", g: "bar", k: "bool", d: false, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/barconfig.hpp:113", "CONFIG declaration: bool recolour = false"], ["shell/modules/nexus/pages/panels/taskbar/BarTray.qml:27", "shipped Nexus control (ToggleRow)"]] }, + { n: "setWorkspacesActiveIndicator", p: "bar.workspaces.activeIndicator", g: "bar", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/barconfig.hpp:37", "CONFIG declaration: bool activeIndicator = true"], ["shell/modules/nexus/pages/panels/taskbar/BarWorkspaces.qml:77", "shipped Nexus control (ToggleRow)"]] }, + { n: "setWorkspacesActiveTrail", p: "bar.workspaces.activeTrail", g: "bar", k: "bool", d: false, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/barconfig.hpp:43", "CONFIG declaration: bool activeTrail = false"], ["shell/modules/nexus/pages/panels/taskbar/BarWorkspaces.qml:83", "shipped Nexus control (ToggleRow)"]] }, + { n: "setWorkspacesDisplayType", p: "bar.workspaces.displayType", g: "bar", k: "enum", d: "Shapes", lo: null, hi: null, st: null, en: ["Shapes", "Text"], sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/barconfig.hpp:49", "CONFIG declaration: caelestia::config::BarWorkspaceDisplay::Enum displayType = BarWorkspaceDisplay::Shapes"], ["shell/modules/nexus/pages/panels/taskbar/BarWorkspaces.qml:95", "shipped Nexus control (SelectRow)"]] }, + { n: "setWorkspacesMaxWindowIcons", p: "bar.workspaces.maxWindowIcons", g: "bar", k: "int", d: 5, lo: 0, hi: 20, st: 1, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/barconfig.hpp:42", "CONFIG declaration: int maxWindowIcons = 5"], ["shell/modules/nexus/pages/panels/taskbar/BarWorkspaces.qml:126", "shipped Nexus control (StepperRow)"]] }, + { n: "setWorkspacesOccupiedBg", p: "bar.workspaces.occupiedBg", g: "bar", k: "bool", d: false, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/barconfig.hpp:38", "CONFIG declaration: bool occupiedBg = false"], ["shell/modules/nexus/pages/panels/taskbar/BarWorkspaces.qml:89", "shipped Nexus control (ToggleRow)"]] }, + { n: "setWorkspacesPerMonitor", p: "bar.workspaces.perMonitor", g: "bar", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/barconfig.hpp:45", "CONFIG declaration: bool perMonitor = true"], ["shell/modules/nexus/pages/panels/taskbar/BarWorkspaces.qml:137", "shipped Nexus control (ToggleRow)"]] }, + { n: "setWorkspacesShowUnoccupied", p: "bar.workspaces.showUnoccupied", g: "bar", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/barconfig.hpp:39", "CONFIG declaration: bool showUnoccupied = true"], ["shell/modules/nexus/pages/panels/taskbar/BarWorkspaces.qml:112", "shipped Nexus control (ToggleRow)"]] }, + { n: "setWorkspacesShowWindows", p: "bar.workspaces.showWindows", g: "bar", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/barconfig.hpp:40", "CONFIG declaration: bool showWindows = true"], ["shell/modules/nexus/pages/panels/taskbar/BarWorkspaces.qml:104", "shipped Nexus control (ToggleRow)"]] }, + { n: "setWorkspacesShowWindowsOnSpecialWorkspaces", p: "bar.workspaces.showWindowsOnSpecialWorkspaces", g: "bar", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/barconfig.hpp:41", "CONFIG declaration: bool showWindowsOnSpecialWorkspaces = true"], ["shell/modules/nexus/pages/panels/taskbar/BarWorkspaces.qml:120", "shipped Nexus control (ToggleRow)"]] }, + { n: "setWorkspacesShown", p: "bar.workspaces.shown", g: "bar", k: "int", d: 5, lo: 1, hi: 20, st: 1, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/barconfig.hpp:36", "CONFIG declaration: int shown = 5"], ["shell/modules/nexus/pages/panels/taskbar/BarWorkspaces.qml:53", "shipped Nexus control (StepperRow)"]] }, + { n: "setDockBadges", p: "bar.dock.showBadges", g: "dock", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/barconfig.hpp:151", "CONFIG declaration: bool showBadges = true"], ["shell/modules/nexus/pages/panels/taskbar/BarDock.qml:75", "shipped Nexus control (ToggleRow)"], ["shell/modules/bar/components/Dock.qml:630", "badge over LauncherEntry.forApp, ?? true"]] }, + { n: "setDockCurrentDesktopOnly", p: "bar.dock.currentDesktopOnly", g: "dock", k: "bool", d: false, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/barconfig.hpp:153", "CONFIG declaration: bool currentDesktopOnly = false"], ["shell/modules/nexus/pages/panels/taskbar/BarDock.qml:83", "shipped Nexus control (ToggleRow)"]] }, + { n: "setDockIconSize", p: "bar.dock.iconSize", g: "dock", k: "int", d: 32, lo: 16, hi: 96, st: 4, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/barconfig.hpp:152", "CONFIG declaration: int iconSize = 32"], ["shell/modules/nexus/pages/panels/taskbar/BarDock.qml:54", "shipped Nexus control (StepperRow)"], ["shell/modules/bar/components/Dock.qml:38", "QML floor 16"]] }, + { n: "setDockPreviewOnDesktop", p: "bar.dock.previewOnDesktop", g: "dock", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/barconfig.hpp:154", "CONFIG declaration: bool previewOnDesktop = true"], ["shell/modules/nexus/pages/panels/taskbar/BarDock.qml:91", "shipped Nexus control (ToggleRow)"]] }, + { n: "setDockRecolourIcons", p: "bar.dock.recolourIcons", g: "dock", k: "bool", d: false, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/barconfig.hpp:150", "CONFIG declaration: bool recolourIcons = false"], ["shell/modules/nexus/pages/panels/taskbar/BarDock.qml:67", "shipped Nexus control (ToggleRow)"]] }, + { n: "setDeformScale", p: "appearance.deformScale", g: "appearance", k: "float", d: 1.0, lo: 0, hi: 1.5, st: 0.05, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/appearanceconfig.hpp:314", "CONFIG declaration: qreal deformScale = 1"], ["shell/modules/nexus/pages/wallandstyle/AppearancePage.qml:357", "shipped Nexus control (StepperRow)"]] }, + { n: "setFontScale", p: "appearance.font.scale", g: "appearance", k: "float", d: 1.0, lo: 0.5, hi: 2.0, st: 0.1, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/appearanceconfig.hpp:249", "CONFIG declaration: qreal scale = 1"], ["shell/modules/nexus/pages/wallandstyle/AppearancePage.qml:285", "shipped Nexus control (StepperRow)"]] }, + { n: "setPaddingScale", p: "appearance.padding.scale", g: "appearance", k: "float", d: 1.0, lo: 0.5, hi: 2.0, st: 0.1, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/appearanceconfig.hpp:90", "CONFIG declaration: qreal scale = 1"], ["shell/modules/nexus/pages/wallandstyle/AppearancePage.qml:306", "shipped Nexus control (StepperRow)"]] }, + { n: "setRoundingScale", p: "appearance.rounding.scale", g: "appearance", k: "float", d: 1.0, lo: 0.5, hi: 2.0, st: 0.1, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/appearanceconfig.hpp:22", "CONFIG declaration: qreal scale = 1"], ["shell/modules/nexus/pages/wallandstyle/AppearancePage.qml:118", "shipped Nexus control (StepperRow)"]] }, + { n: "setSpacingScale", p: "appearance.spacing.scale", g: "appearance", k: "float", d: 1.0, lo: 0.5, hi: 2.0, st: 0.1, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/appearanceconfig.hpp:57", "CONFIG declaration: qreal scale = 1"], ["shell/modules/nexus/pages/wallandstyle/AppearancePage.qml:296", "shipped Nexus control (StepperRow)"]] }, + { n: "setAmbientColor", p: "appearance.ambientColor", g: "effects", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: true, c: [["shell/plugin/src/Caelestia/Config/appearanceconfig.hpp:326", "CONFIG declaration: bool ambientColor = true"], ["shell/modules/nexus/pages/wallandstyle/AppearancePage.qml:158", "shipped Nexus control (ToggleRow)"]] }, + { n: "setAmbientOpacity", p: "appearance.ambientOpacity", g: "effects", k: "float", d: 0.45, lo: 0, hi: 1, st: null, en: null, sl: null, go: true, c: [["shell/plugin/src/Caelestia/Config/appearanceconfig.hpp:327", "CONFIG declaration: qreal ambientOpacity = 0.45"], ["shell/modules/nexus/pages/wallandstyle/AppearancePage.qml:167", "shipped Nexus control (SliderRow)"]] }, + { n: "setBlurEnabled", p: "appearance.blur", g: "effects", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: true, c: [["shell/plugin/src/Caelestia/Config/appearanceconfig.hpp:324", "CONFIG declaration: bool blur = true"], ["shell/modules/nexus/pages/wallandstyle/AppearancePage.qml:222", "shipped Nexus control (ToggleRow)"], ["shell/modules/drawers/blur/BlurOffsets.qml:17", "isActive = transparency.enabled && blur"]] }, + { n: "setBlurMask", p: "appearance.blurMask", g: "effects", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: true, c: [["shell/plugin/src/Caelestia/Config/appearanceconfig.hpp:325", "CONFIG declaration: bool blurMask = true"], ["shell/modules/nexus/pages/wallandstyle/AppearancePage.qml:246", "shipped Nexus control (ToggleRow)"]] }, + { n: "setIslands", p: "appearance.islands", g: "effects", k: "bool", d: false, lo: null, hi: null, st: null, en: null, sl: null, go: true, c: [["shell/plugin/src/Caelestia/Config/appearanceconfig.hpp:323", "CONFIG declaration: bool islands = false"], ["shell/modules/nexus/pages/wallandstyle/AppearancePage.qml:100", "shipped Nexus control (ToggleRow)"]] }, + { n: "setPitchBlack", p: "appearance.pitchBlack", g: "effects", k: "bool", d: false, lo: null, hi: null, st: null, en: null, sl: null, go: true, c: [["shell/plugin/src/Caelestia/Config/appearanceconfig.hpp:322", "CONFIG declaration: bool pitchBlack = false"], ["shell/modules/nexus/pages/wallandstyle/AppearancePage.qml:92", "shipped Nexus control (ToggleRow)"], ["shell/modules/drawers/ContentWindow.qml:394", "#000000 surface when pitchBlack"]] }, + { n: "setTransparencyBase", p: "appearance.transparency.base", g: "effects", k: "float", d: 0.85, lo: 0.0, hi: 1.0, st: 0.05, en: null, sl: null, go: true, c: [["shell/plugin/src/Caelestia/Config/appearanceconfig.hpp:307", "CONFIG declaration: qreal base = 0.85"], ["shell/modules/nexus/pages/wallandstyle/AppearancePage.qml:141", "shipped Nexus control (SliderRow)"], ["shell/modules/drawers/ContentWindow.qml:383", "surface opacity reader"]] }, + { n: "setTransparencyEnabled", p: "appearance.transparency.enabled", g: "effects", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: true, c: [["shell/plugin/src/Caelestia/Config/appearanceconfig.hpp:306", "CONFIG declaration: bool enabled = true"], ["shell/modules/nexus/pages/wallandstyle/AppearancePage.qml:128", "shipped Nexus control (ToggleRow)"]] }, + { n: "setTransparencyLayers", p: "appearance.transparency.layers", g: "effects", k: "float", d: 0.4, lo: 0, hi: 1, st: null, en: null, sl: null, go: true, c: [["shell/plugin/src/Caelestia/Config/appearanceconfig.hpp:308", "CONFIG declaration: qreal layers = 0.4"], ["shell/modules/nexus/pages/wallandstyle/AppearancePage.qml:149", "shipped Nexus control (SliderRow)"]] }, + { n: "setAnimationSpeed", p: "appearance.anim.durations.scale", g: "animations", k: "float", d: 1.0, lo: 0.25, hi: 4.0, st: 0.25, en: null, sl: null, go: true, c: [["shell/plugin/src/Caelestia/Config/appearanceconfig.hpp:263", "CONFIG declaration: qreal scale = 1"], ["shell/modules/nexus/pages/wallandstyle/AppearancePage.qml:316", "shipped Nexus control (StepperRow)"], ["shell/plugin/src/Caelestia/Config/appearanceconfig.cpp:207", "durations multiplied by scale"]] }, + { n: "setActionOnClick", p: "notifs.actionOnClick", g: "notifications", k: "bool", d: false, lo: null, hi: null, st: null, en: null, sl: null, go: true, c: [["shell/plugin/src/Caelestia/Config/notifsconfig.hpp:20", "CONFIG declaration: bool actionOnClick = false"], ["shell/modules/nexus/pages/services/NotificationPreferencesPage.qml:162", "shipped Nexus control (ToggleRow)"]] }, + { n: "setClearThreshold", p: "notifs.clearThreshold", g: "notifications", k: "float", d: 0.3, lo: 0, hi: 1, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/notifsconfig.hpp:18", "CONFIG declaration: qreal clearThreshold = 0.3"], ["shell/modules/nexus/pages/services/NotificationPreferencesPage.qml:190", "shipped Nexus control (SliderRow)"]] }, + { n: "setDefaultExpireTimeout", p: "notifs.defaultExpireTimeout", g: "notifications", k: "int", d: 5000, lo: 1000, hi: 60000, st: 1000, en: null, sl: null, go: true, c: [["shell/plugin/src/Caelestia/Config/notifsconfig.hpp:16", "CONFIG declaration: int defaultExpireTimeout = 5000"], ["shell/modules/nexus/pages/services/NotificationPreferencesPage.qml:117", "shipped Nexus control (StepperRow)"], ["shell/modules/nexus/pages/services/NotificationPreferencesPage.qml:120", "stepper displays seconds (value: x/1000; onMoved: Math.round(v*1000)); stored unit is ms — range converted x1000"]] }, + { n: "setExpandThreshold", p: "notifs.expandThreshold", g: "notifications", k: "int", d: 20, lo: 5, hi: 100, st: 5, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/notifsconfig.hpp:19", "CONFIG declaration: int expandThreshold = 20"], ["shell/modules/nexus/pages/services/NotificationPreferencesPage.qml:170", "shipped Nexus control (StepperRow)"]] }, + { n: "setExpire", p: "notifs.expire", g: "notifications", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: true, c: [["shell/plugin/src/Caelestia/Config/notifsconfig.hpp:13", "CONFIG declaration: bool expire = true"], ["shell/modules/nexus/pages/services/NotificationPreferencesPage.qml:103", "shipped Nexus control (ToggleRow)"]] }, + { n: "setFullscreen", p: "notifs.fullscreen", g: "notifications", k: "enum", d: "off", lo: null, hi: null, st: null, en: ["off", "on"], sl: null, go: true, c: [["shell/plugin/src/Caelestia/Config/notifsconfig.hpp:14", "CONFIG declaration: QString fullscreen = QStringLiteral(\"off\")"], ["shell/modules/nexus/pages/services/NotificationPreferencesPage.qml:78", "shipped Nexus control (SelectRow)"]] }, + { n: "setFullscreenExpireTimeout", p: "notifs.fullscreenExpireTimeout", g: "notifications", k: "int", d: 2000, lo: 1000, hi: 30000, st: 1000, en: null, sl: null, go: true, c: [["shell/plugin/src/Caelestia/Config/notifsconfig.hpp:17", "CONFIG declaration: int fullscreenExpireTimeout = 2000"], ["shell/modules/nexus/pages/services/NotificationPreferencesPage.qml:180", "shipped Nexus control (StepperRow)"], ["shell/modules/nexus/pages/services/NotificationPreferencesPage.qml:183", "stepper displays seconds (value: x/1000; onMoved: Math.round(value*1000)); stored unit is ms — range converted x1000"]] }, + { n: "setGroupPreviewNum", p: "notifs.groupPreviewNum", g: "notifications", k: "int", d: 3, lo: 1, hi: 10, st: 1, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/notifsconfig.hpp:21", "CONFIG declaration: int groupPreviewNum = 3"], ["shell/modules/nexus/pages/services/NotificationPreferencesPage.qml:127", "shipped Nexus control (StepperRow)"]] }, + { n: "setMonitor", p: "notifs.monitor", g: "notifications", k: "enum", d: "all", lo: null, hi: null, st: null, en: ["all", "focused"], sl: null, go: true, c: [["shell/plugin/src/Caelestia/Config/notifsconfig.hpp:15", "CONFIG declaration: QString monitor = QStringLiteral(\"all\")"], ["shell/modules/nexus/pages/services/NotificationPreferencesPage.qml:87", "shipped Nexus control (SelectRow)"]] }, + { n: "setNotifsMaxNotifs", p: "notifs.maxNotifs", g: "notifications", k: "int", d: 50, lo: 20, hi: 2000, st: 50, en: null, sl: null, go: true, c: [["shell/plugin/src/Caelestia/Config/notifsconfig.hpp:25", "CONFIG declaration: int maxNotifs = 50"], ["shell/modules/nexus/pages/services/NotificationPreferencesPage.qml:147", "shipped Nexus control (StepperRow)"]] }, + { n: "setNotifsMaxPopups", p: "notifs.maxPopups", g: "notifications", k: "int", d: 8, lo: 0, hi: 30, st: 1, en: null, sl: null, go: true, c: [["shell/plugin/src/Caelestia/Config/notifsconfig.hpp:24", "CONFIG declaration: int maxPopups = 8"], ["shell/modules/nexus/pages/services/NotificationPreferencesPage.qml:137", "shipped Nexus control (StepperRow)"]] }, + { n: "setOpenExpanded", p: "notifs.openExpanded", g: "notifications", k: "bool", d: false, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/notifsconfig.hpp:22", "CONFIG declaration: bool openExpanded = false"], ["shell/modules/nexus/pages/services/NotificationPreferencesPage.qml:110", "shipped Nexus control (ToggleRow)"]] }, + { n: "setPosition", p: "notifs.position", g: "notifications", k: "enum", d: "auto", lo: null, hi: null, st: null, en: ["auto", "top-left", "top-center", "top-right", "bottom-left", "bottom-center", "bottom-right"], sl: null, go: true, c: [["shell/plugin/src/Caelestia/Config/notifsconfig.hpp:23", "CONFIG declaration: QString position = QStringLiteral(\"auto\")"], ["shell/modules/nexus/pages/services/NotificationPreferencesPage.qml:95", "shipped Nexus control (SelectRow)"]] }, + { n: "setClipboardMaxEntries", p: "launcher.clipboardMaxEntries", g: "launcher", k: "int", d: 20, lo: 1, hi: 100, st: 1, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/launcherconfig.hpp:46", "CONFIG declaration: int clipboardMaxEntries = 20"], ["shell/modules/nexus/pages/panels/LauncherPanel.qml:193", "shipped Nexus control (StepperRow)"]] }, + { n: "setConfirmClearClipboard", p: "launcher.confirmClearClipboard", g: "launcher", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: true, c: [["shell/plugin/src/Caelestia/Config/launcherconfig.hpp:56", "CONFIG declaration: bool confirmClearClipboard = true"], ["shell/modules/nexus/pages/panels/LauncherPanel.qml:204", "shipped Nexus control (ToggleRow)"]] }, + { n: "setEnableDangerousActions", p: "launcher.enableDangerousActions", g: "launcher", k: "bool", d: false, lo: null, hi: null, st: null, en: null, sl: null, go: true, c: [["shell/plugin/src/Caelestia/Config/launcherconfig.hpp:49", "CONFIG declaration: bool enableDangerousActions = false"], ["shell/modules/nexus/pages/panels/LauncherPanel.qml:225", "shipped Nexus control (ToggleRow)"]] }, + { n: "setLauncherDragThreshold", p: "launcher.dragThreshold", g: "launcher", k: "int", d: 50, lo: 0, hi: 200, st: 5, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/launcherconfig.hpp:50", "CONFIG declaration: int dragThreshold = 50"], ["shell/modules/nexus/pages/panels/LauncherPanel.qml:177", "shipped Nexus control (StepperRow)"]] }, + { n: "setLauncherEnabled", p: "launcher.enabled", g: "launcher", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/launcherconfig.hpp:42", "CONFIG declaration: bool enabled = true"], ["shell/modules/nexus/pages/panels/LauncherPanel.qml:30", "shipped Nexus control (ToggleRow)"]] }, + { n: "setLauncherHoverThickness", p: "launcher.hoverThickness", g: "launcher", k: "int", d: 10, lo: 1, hi: 100, st: 1, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/launcherconfig.hpp:53", "CONFIG declaration: int hoverThickness = 10"], ["shell/modules/nexus/pages/panels/LauncherPanel.qml:157", "shipped Nexus control (StepperRow)"]] }, + { n: "setLauncherHoverWidth", p: "launcher.hoverWidth", g: "launcher", k: "int", d: 50, lo: 10, hi: 100, st: 5, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/launcherconfig.hpp:54", "CONFIG declaration: int hoverWidth = 50"], ["shell/modules/nexus/pages/panels/LauncherPanel.qml:167", "shipped Nexus control (StepperRow)"]] }, + { n: "setLauncherMaxShown", p: "launcher.maxShown", g: "launcher", k: "int", d: 7, lo: 1, hi: 20, st: 1, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/launcherconfig.hpp:44", "CONFIG declaration: int maxShown = 7"], ["shell/modules/nexus/pages/panels/LauncherPanel.qml:139", "shipped Nexus control (StepperRow)"]] }, + { n: "setLauncherShowOnHover", p: "launcher.showOnHover", g: "launcher", k: "bool", d: false, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/launcherconfig.hpp:43", "CONFIG declaration: bool showOnHover = false"], ["shell/modules/nexus/pages/panels/LauncherPanel.qml:111", "shipped Nexus control (ToggleRow)"]] }, + { n: "setLauncherVimKeybinds", p: "launcher.vimKeybinds", g: "launcher", k: "bool", d: false, lo: null, hi: null, st: null, en: null, sl: null, go: true, c: [["shell/plugin/src/Caelestia/Config/launcherconfig.hpp:55", "CONFIG declaration: bool vimKeybinds = false"], ["shell/modules/nexus/pages/panels/LauncherPanel.qml:217", "shipped Nexus control (ToggleRow)"]] }, + { n: "setMaxWallpapers", p: "launcher.maxWallpapers", g: "launcher", k: "int", d: 9, lo: 1, hi: 30, st: 1, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/launcherconfig.hpp:45", "CONFIG declaration: int maxWallpapers = 9"], ["shell/modules/nexus/pages/panels/LauncherPanel.qml:148", "shipped Nexus control (StepperRow)"]] }, + { n: "setShowBrowseOnEmpty", p: "launcher.showBrowseOnEmpty", g: "launcher", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/launcherconfig.hpp:52", "CONFIG declaration: bool showBrowseOnEmpty = true"], ["shell/modules/nexus/pages/panels/LauncherPanel.qml:124", "shipped Nexus control (ToggleRow)"]] }, + { n: "setShowPowerMenu", p: "launcher.showPowerMenu", g: "launcher", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/launcherconfig.hpp:51", "CONFIG declaration: bool showPowerMenu = true"], ["shell/modules/nexus/pages/panels/LauncherPanel.qml:132", "shipped Nexus control (ToggleRow)"]] }, + { n: "setUseFuzzyActions", p: "launcher.useFuzzy.actions", g: "launcher", k: "bool", d: false, lo: null, hi: null, st: null, en: null, sl: null, go: true, c: [["shell/plugin/src/Caelestia/Config/launcherconfig.hpp:19", "CONFIG declaration: bool actions = false"], ["shell/modules/nexus/pages/panels/LauncherPanel.qml:245", "shipped Nexus control (ToggleRow)"]] }, + { n: "setUseFuzzyApps", p: "launcher.useFuzzy.apps", g: "launcher", k: "bool", d: false, lo: null, hi: null, st: null, en: null, sl: null, go: true, c: [["shell/plugin/src/Caelestia/Config/launcherconfig.hpp:18", "CONFIG declaration: bool apps = false"], ["shell/modules/nexus/pages/panels/LauncherPanel.qml:238", "shipped Nexus control (ToggleRow)"]] }, + { n: "setUseFuzzySchemes", p: "launcher.useFuzzy.schemes", g: "launcher", k: "bool", d: false, lo: null, hi: null, st: null, en: null, sl: null, go: true, c: [["shell/plugin/src/Caelestia/Config/launcherconfig.hpp:20", "CONFIG declaration: bool schemes = false"], ["shell/modules/nexus/pages/panels/LauncherPanel.qml:251", "shipped Nexus control (ToggleRow)"]] }, + { n: "setUseFuzzyVariants", p: "launcher.useFuzzy.variants", g: "launcher", k: "bool", d: false, lo: null, hi: null, st: null, en: null, sl: null, go: true, c: [["shell/plugin/src/Caelestia/Config/launcherconfig.hpp:21", "CONFIG declaration: bool variants = false"], ["shell/modules/nexus/pages/panels/LauncherPanel.qml:257", "shipped Nexus control (ToggleRow)"]] }, + { n: "setUseFuzzyWallpapers", p: "launcher.useFuzzy.wallpapers", g: "launcher", k: "bool", d: false, lo: null, hi: null, st: null, en: null, sl: null, go: true, c: [["shell/plugin/src/Caelestia/Config/launcherconfig.hpp:22", "CONFIG declaration: bool wallpapers = false"], ["shell/modules/nexus/pages/panels/LauncherPanel.qml:263", "shipped Nexus control (ToggleRow)"]] }, + { n: "setBlurWallpaper", p: "lock.blurWallpaper", g: "lockscreen", k: "bool", d: false, lo: null, hi: null, st: null, en: null, sl: null, go: true, c: [["shell/plugin/src/Caelestia/Config/lockconfig.hpp:22", "CONFIG declaration: bool blurWallpaper = false"], ["shell/modules/nexus/pages/wallandstyle/LockScreenPage.qml:184", "shipped Nexus control (ToggleRow)"]] }, + { n: "setEnableFprint", p: "lock.enableFprint", g: "lockscreen", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: true, c: [["shell/plugin/src/Caelestia/Config/lockconfig.hpp:12", "CONFIG declaration: bool enableFprint = true"], ["shell/modules/nexus/pages/wallandstyle/LockScreenPage.qml:201", "shipped Nexus control (ToggleRow)"]] }, + { n: "setHideNotifs", p: "lock.hideNotifs", g: "lockscreen", k: "bool", d: false, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/lockconfig.hpp:19", "CONFIG declaration: bool hideNotifs = false"], ["shell/modules/nexus/pages/wallandstyle/LockScreenPage.qml:280", "shipped Nexus control (ToggleRow)"]] }, + { n: "setLockOnStartup", p: "lock.lockOnStartup", g: "lockscreen", k: "bool", d: false, lo: null, hi: null, st: null, en: null, sl: null, go: true, c: [["shell/plugin/src/Caelestia/Config/lockconfig.hpp:20", "CONFIG declaration: bool lockOnStartup = false"], ["shell/modules/nexus/pages/wallandstyle/LockScreenPage.qml:269", "shipped Nexus control (ToggleRow)"]] }, + { n: "setMaxFprintTries", p: "lock.maxFprintTries", g: "lockscreen", k: "int", d: 3, lo: 1, hi: 5, st: 1, en: null, sl: null, go: true, c: [["shell/plugin/src/Caelestia/Config/lockconfig.hpp:13", "CONFIG declaration: int maxFprintTries = 3"], ["shell/modules/nexus/pages/wallandstyle/LockScreenPage.qml:213", "shipped Nexus control (SelectRow)"]] }, + { n: "setRecolourLogo", p: "lock.recolourLogo", g: "lockscreen", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/lockconfig.hpp:11", "CONFIG declaration: bool recolourLogo = true"], ["shell/modules/nexus/pages/wallandstyle/LockScreenPage.qml:291", "shipped Nexus control (ToggleRow)"]] }, + { n: "setRotateProfilePic", p: "lock.rotateProfilePic", g: "lockscreen", k: "bool", d: false, lo: null, hi: null, st: null, en: null, sl: null, go: true, c: [["shell/plugin/src/Caelestia/Config/lockconfig.hpp:18", "CONFIG declaration: bool rotateProfilePic = false"], ["shell/modules/nexus/pages/wallandstyle/LockScreenPage.qml:258", "shipped Nexus control (ToggleRow)"]] }, + { n: "setShowHibernate", p: "lock.showHibernate", g: "lockscreen", k: "bool", d: false, lo: null, hi: null, st: null, en: null, sl: null, go: true, c: [["shell/plugin/src/Caelestia/Config/lockconfig.hpp:24", "CONFIG declaration: bool showHibernate = false"], ["shell/modules/nexus/pages/wallandstyle/LockScreenPage.qml:320", "shipped Nexus control (ToggleRow)"]] }, + { n: "setShowLogout", p: "lock.showLogout", g: "lockscreen", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: true, c: [["shell/plugin/src/Caelestia/Config/lockconfig.hpp:26", "CONFIG declaration: bool showLogout = true"], ["shell/modules/nexus/pages/wallandstyle/LockScreenPage.qml:342", "shipped Nexus control (ToggleRow)"]] }, + { n: "setShowReboot", p: "lock.showReboot", g: "lockscreen", k: "bool", d: false, lo: null, hi: null, st: null, en: null, sl: null, go: true, c: [["shell/plugin/src/Caelestia/Config/lockconfig.hpp:27", "CONFIG declaration: bool showReboot = false"], ["shell/modules/nexus/pages/wallandstyle/LockScreenPage.qml:353", "shipped Nexus control (ToggleRow)"]] }, + { n: "setShowShutdown", p: "lock.showShutdown", g: "lockscreen", k: "bool", d: false, lo: null, hi: null, st: null, en: null, sl: null, go: true, c: [["shell/plugin/src/Caelestia/Config/lockconfig.hpp:28", "CONFIG declaration: bool showShutdown = false"], ["shell/modules/nexus/pages/wallandstyle/LockScreenPage.qml:364", "shipped Nexus control (ToggleRow)"]] }, + { n: "setShowSleep", p: "lock.showSleep", g: "lockscreen", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: true, c: [["shell/plugin/src/Caelestia/Config/lockconfig.hpp:23", "CONFIG declaration: bool showSleep = true"], ["shell/modules/nexus/pages/wallandstyle/LockScreenPage.qml:308", "shipped Nexus control (ToggleRow)"]] }, + { n: "setShowSwitchUser", p: "lock.showSwitchUser", g: "lockscreen", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: true, c: [["shell/plugin/src/Caelestia/Config/lockconfig.hpp:25", "CONFIG declaration: bool showSwitchUser = true"], ["shell/modules/nexus/pages/wallandstyle/LockScreenPage.qml:331", "shipped Nexus control (ToggleRow)"]] }, + { n: "setSyncWallpaper", p: "lock.syncWallpaper", g: "lockscreen", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: true, c: [["shell/plugin/src/Caelestia/Config/lockconfig.hpp:21", "CONFIG declaration: bool syncWallpaper = true"], ["shell/modules/nexus/pages/wallandstyle/LockScreenPage.qml:147", "shipped Nexus control (ToggleRow)"]] }, + { n: "setDesktopClockEnabled", p: "background.desktopClock.enabled", g: "wallpaper-scheme", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:29", "CONFIG declaration: bool enabled = true"], ["shell/modules/nexus/pages/wallandstyle/DesktopAddonsPage.qml:89", "shipped Nexus control (ToggleRow)"]] }, + { n: "setDesktopClockInvertColors", p: "background.desktopClock.invertColors", g: "wallpaper-scheme", k: "bool", d: false, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:32", "CONFIG declaration: bool invertColors = false"], ["shell/modules/nexus/pages/wallandstyle/DesktopAddonsPage.qml:213", "shipped Nexus control (ToggleRow)"]] }, + { n: "setDesktopClockPosition", p: "background.desktopClock.position", g: "wallpaper-scheme", k: "enum", d: "bottom-right", lo: null, hi: null, st: null, en: ["top-left", "top-center", "top-right", "center", "bottom-left", "bottom-center", "bottom-right"], sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:31", "CONFIG declaration: QString position = QStringLiteral(\"bottom-right\")"], ["shell/modules/nexus/pages/wallandstyle/DesktopAddonsPage.qml:197", "shipped Nexus control (SelectRow)"]] }, + { n: "setDesktopClockScale", p: "background.desktopClock.scale", g: "wallpaper-scheme", k: "float", d: 1.0, lo: 0.5, hi: 3, st: 0.1, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:30", "CONFIG declaration: qreal scale = 1.0"], ["shell/modules/nexus/pages/wallandstyle/DesktopAddonsPage.qml:186", "shipped Nexus control (StepperRow)"]] }, + { n: "setDesktopIconsEnabled", p: "background.desktopIconsEnabled", g: "wallpaper-scheme", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:103", "CONFIG declaration: bool desktopIconsEnabled = true"], ["shell/modules/nexus/pages/DesktopPage.qml:40", "shipped Nexus control (ToggleRow)"]] }, + { n: "setDesktopLyricsAlignment", p: "background.desktopLyrics.alignment", g: "wallpaper-scheme", k: "int", d: 1, lo: 0, hi: 2, st: 1, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:71", "CONFIG declaration: int alignment = 1"], ["shell/modules/nexus/pages/wallandstyle/DesktopAddonsPage.qml:294", "shipped Nexus control (SelectRow)"]] }, + { n: "setDesktopLyricsAutoHide", p: "background.desktopLyrics.autoHide", g: "wallpaper-scheme", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:68", "CONFIG declaration: bool autoHide = true"], ["shell/modules/nexus/pages/wallandstyle/DesktopAddonsPage.qml:131", "shipped Nexus control (ToggleRow)"]] }, + { n: "setDesktopLyricsEnabled", p: "background.desktopLyrics.enabled", g: "wallpaper-scheme", k: "bool", d: false, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:67", "CONFIG declaration: bool enabled = false"], ["shell/modules/nexus/pages/wallandstyle/DesktopAddonsPage.qml:119", "shipped Nexus control (ToggleRow)"]] }, + { n: "setDesktopLyricsInvertColors", p: "background.desktopLyrics.invertColors", g: "wallpaper-scheme", k: "bool", d: false, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:72", "CONFIG declaration: bool invertColors = false"], ["shell/modules/nexus/pages/wallandstyle/DesktopAddonsPage.qml:308", "shipped Nexus control (ToggleRow)"]] }, + { n: "setDesktopLyricsPosition", p: "background.desktopLyrics.position", g: "wallpaper-scheme", k: "enum", d: "bottom-center", lo: null, hi: null, st: null, en: ["top-left", "top-center", "top-right", "center", "bottom-left", "bottom-center", "bottom-right"], sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:70", "CONFIG declaration: QString position = QStringLiteral(\"bottom-center\")"], ["shell/modules/nexus/pages/wallandstyle/DesktopAddonsPage.qml:278", "shipped Nexus control (SelectRow)"]] }, + { n: "setDesktopLyricsScale", p: "background.desktopLyrics.scale", g: "wallpaper-scheme", k: "float", d: 1.0, lo: 0.5, hi: 3, st: 0.1, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:69", "CONFIG declaration: qreal scale = 1.0"], ["shell/modules/nexus/pages/wallandstyle/DesktopAddonsPage.qml:267", "shipped Nexus control (StepperRow)"]] }, + { n: "setDesktopShapesAutoHide", p: "background.desktopShapes.autoHide", g: "wallpaper-scheme", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:81", "CONFIG declaration: bool autoHide = true"], ["shell/modules/nexus/pages/wallandstyle/DesktopAddonsPage.qml:109", "shipped Nexus control (ToggleRow)"]] }, + { n: "setDesktopShapesEnabled", p: "background.desktopShapes.enabled", g: "wallpaper-scheme", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:80", "CONFIG declaration: bool enabled = true"], ["shell/modules/nexus/pages/wallandstyle/DesktopAddonsPage.qml:97", "shipped Nexus control (ToggleRow)"]] }, + { n: "setDesktopShapesPosition", p: "background.desktopShapes.position", g: "wallpaper-scheme", k: "enum", d: "bottom-center", lo: null, hi: null, st: null, en: ["top-left", "top-center", "top-right", "center", "bottom-left", "bottom-center", "bottom-right"], sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:83", "CONFIG declaration: QString position = QStringLiteral(\"bottom-center\")"], ["shell/modules/nexus/pages/wallandstyle/DesktopAddonsPage.qml:241", "shipped Nexus control (SelectRow)"]] }, + { n: "setDesktopShapesScale", p: "background.desktopShapes.scale", g: "wallpaper-scheme", k: "float", d: 1.0, lo: 0.5, hi: 3, st: 0.1, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:82", "CONFIG declaration: qreal scale = 1.0"], ["shell/modules/nexus/pages/wallandstyle/DesktopAddonsPage.qml:230", "shipped Nexus control (StepperRow)"]] }, + { n: "setMaterialYouIconsEnabled", p: "background.materialYouIconsEnabled", g: "wallpaper-scheme", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:104", "CONFIG declaration: bool materialYouIconsEnabled = true"], ["shell/modules/nexus/pages/DesktopPage.qml:57", "shipped Nexus control (ToggleRow)"]] }, + { n: "setMaterialYouIconsVibrant", p: "background.materialYouIconsVibrant", g: "wallpaper-scheme", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:105", "CONFIG declaration: bool materialYouIconsVibrant = true"], ["shell/modules/nexus/pages/DesktopPage.qml:74", "shipped Nexus control (ToggleRow)"]] }, + { n: "setSlideshowEnabled", p: "background.slideshowEnabled", g: "wallpaper-scheme", k: "bool", d: false, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:94", "CONFIG declaration: bool slideshowEnabled = false"], ["shell/modules/nexus/pages/wallandstyle/SlideshowAndOrderPage.qml:33", "shipped Nexus control (ToggleRow)"]] }, + { n: "setSlideshowInterval", p: "background.slideshowInterval", g: "wallpaper-scheme", k: "float", d: 0.16, lo: 0, hi: 1, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:95", "CONFIG declaration: qreal slideshowInterval = 0.16"], ["shell/modules/nexus/pages/wallandstyle/SlideshowAndOrderPage.qml:43", "shipped Nexus control (SliderRow)"]] }, + { n: "setSlideshowRandom", p: "background.slideshowRandom", g: "wallpaper-scheme", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:96", "CONFIG declaration: bool slideshowRandom = true"], ["shell/modules/nexus/pages/wallandstyle/SlideshowAndOrderPage.qml:54", "shipped Nexus control (ToggleRow)"]] }, + { n: "setVideoWallpaperMuteOnMedia", p: "background.videoWallpaperMuteOnMedia", g: "wallpaper-scheme", k: "bool", d: false, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:102", "CONFIG declaration: bool videoWallpaperMuteOnMedia = false"], ["shell/modules/nexus/pages/wallandstyle/VideoWallpapersPage.qml:61", "shipped Nexus control (ToggleRow)"]] }, + { n: "setVideoWallpaperPauseOnAllDisplays", p: "background.videoWallpaperPauseOnAllDisplays", g: "wallpaper-scheme", k: "bool", d: false, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:101", "CONFIG declaration: bool videoWallpaperPauseOnAllDisplays = false"], ["shell/modules/nexus/pages/wallandstyle/VideoWallpapersPage.qml:55", "shipped Nexus control (ToggleRow)"]] }, + { n: "setVideoWallpaperPauseOnFullscreen", p: "background.videoWallpaperPauseOnFullscreen", g: "wallpaper-scheme", k: "bool", d: false, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:99", "CONFIG declaration: bool videoWallpaperPauseOnFullscreen = false"], ["shell/modules/nexus/pages/wallandstyle/VideoWallpapersPage.qml:41", "shipped Nexus control (ToggleRow)"]] }, + { n: "setVideoWallpaperPauseOnTiled", p: "background.videoWallpaperPauseOnTiled", g: "wallpaper-scheme", k: "bool", d: false, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:100", "CONFIG declaration: bool videoWallpaperPauseOnTiled = false"], ["shell/modules/nexus/pages/wallandstyle/VideoWallpapersPage.qml:48", "shipped Nexus control (ToggleRow)"]] }, + { n: "setVideoWallpaperPaused", p: "background.videoWallpaperPaused", g: "wallpaper-scheme", k: "bool", d: false, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:97", "CONFIG declaration: bool videoWallpaperPaused = false"], ["shell/modules/nexus/pages/wallandstyle/VideoWallpapersPage.qml:28", "shipped Nexus control (ToggleRow)"]] }, + { n: "setVideoWallpaperSoundEnabled", p: "background.videoWallpaperSoundEnabled", g: "wallpaper-scheme", k: "bool", d: false, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:98", "CONFIG declaration: bool videoWallpaperSoundEnabled = false"], ["shell/modules/nexus/pages/wallandstyle/VideoWallpapersPage.qml:35", "shipped Nexus control (ToggleRow)"]] }, + { n: "setVisualiserAutoHide", p: "background.visualiser.autoHide", g: "wallpaper-scheme", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:41", "CONFIG declaration: bool autoHide = true"], ["shell/modules/nexus/pages/wallandstyle/DesktopAddonsPage.qml:155", "shipped Nexus control (ToggleRow)"]] }, + { n: "setVisualiserBlur", p: "background.visualiser.blur", g: "wallpaper-scheme", k: "bool", d: false, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:43", "CONFIG declaration: bool blur = false"], ["shell/modules/nexus/pages/wallandstyle/DesktopAddonsPage.qml:325", "shipped Nexus control (ToggleRow)"]] }, + { n: "setVisualiserEnabled", p: "background.visualiser.enabled", g: "wallpaper-scheme", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:40", "CONFIG declaration: bool enabled = true"], ["shell/modules/nexus/pages/wallandstyle/DesktopAddonsPage.qml:141", "shipped Nexus control (ToggleRow)"]] }, + { n: "setVisualiserHideOnAllMonitors", p: "background.visualiser.hideOnAllMonitors", g: "wallpaper-scheme", k: "bool", d: false, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:42", "CONFIG declaration: bool hideOnAllMonitors = false"], ["shell/modules/nexus/pages/wallandstyle/DesktopAddonsPage.qml:165", "shipped Nexus control (ToggleRow)"]] }, + { n: "setVisualiserRounding", p: "background.visualiser.rounding", g: "wallpaper-scheme", k: "float", d: 1.0, lo: 0, hi: 1, st: 0.05, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:44", "CONFIG declaration: qreal rounding = 1"], ["shell/modules/nexus/pages/wallandstyle/DesktopAddonsPage.qml:333", "shipped Nexus control (StepperRow)"]] }, + { n: "setVisualiserSpacing", p: "background.visualiser.spacing", g: "wallpaper-scheme", k: "float", d: 1.0, lo: 0.5, hi: 3, st: 0.1, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:45", "CONFIG declaration: qreal spacing = 1"], ["shell/modules/nexus/pages/wallandstyle/DesktopAddonsPage.qml:343", "shipped Nexus control (StepperRow)"]] }, + { n: "setWallpaperEnabled", p: "background.wallpaperEnabled", g: "wallpaper-scheme", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:90", "CONFIG declaration: bool wallpaperEnabled = true"], ["shell/modules/nexus/pages/DesktopPage.qml:24", "shipped Nexus control (ToggleRow)"]] }, + { n: "setWallpaperFillMode", p: "background.wallpaperFillMode", g: "wallpaper-scheme", k: "enum", d: 2, lo: null, hi: null, st: null, en: [0, 1, 2], sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:91", "CONFIG declaration: int wallpaperFillMode = 2"], ["shell/modules/nexus/pages/wallandstyle/WallpaperSettingsPage.qml:49", "shipped Nexus control (SelectRow)"], ["shell/modules/nexus/pages/wallandstyle/WallpaperSettingsPage.qml:26", "scalingValues: [Image.PreserveAspectCrop, Image.PreserveAspectFit, Image.Stretch] = [2, 1, 0]; the SelectRow writes these ints"]] }, + { n: "setWallpaperRecolor", p: "background.wallpaperRecolor", g: "wallpaper-scheme", k: "bool", d: false, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:92", "CONFIG declaration: bool wallpaperRecolor = false"], ["shell/modules/nexus/pages/wallandstyle/WallpaperSettingsPage.qml:68", "shipped Nexus control (ToggleRow)"]] }, + { n: "setWallpaperRecolorStrength", p: "background.wallpaperRecolorStrength", g: "wallpaper-scheme", k: "float", d: 0.5, lo: 0, hi: 1, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:93", "CONFIG declaration: qreal wallpaperRecolorStrength = 0.5"], ["shell/modules/nexus/pages/wallandstyle/WallpaperSettingsPage.qml:85", "shipped Nexus control (SliderRow)"]] }, + { n: "setBaseDuration", p: "overview.baseDuration", g: "overview", k: "int", d: 300, lo: 100, hi: 1000, st: 50, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/overviewconfig.hpp:22", "CONFIG declaration: int baseDuration = 300"], ["shell/modules/nexus/pages/panels/OverviewPanel.qml:225", "shipped Nexus control (StepperRow)"]] }, + { n: "setBlobScaleSpeed", p: "overview.blobScaleSpeed", g: "overview", k: "float", d: 1.0, lo: 0.1, hi: 5.0, st: 0.1, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/overviewconfig.hpp:23", "CONFIG declaration: qreal blobScaleSpeed = 1.0"], ["shell/modules/nexus/pages/panels/OverviewPanel.qml:234", "shipped Nexus control (StepperRow)"]] }, + { n: "setDisableWallpaperBlur", p: "overview.disableWallpaperBlur", g: "overview", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/overviewconfig.hpp:12", "CONFIG declaration: bool disableWallpaperBlur = true"], ["shell/modules/nexus/pages/panels/OverviewPanel.qml:191", "shipped Nexus control (ToggleRow)"]] }, + { n: "setEasingType", p: "overview.easingType", g: "overview", k: "enum", d: 2, lo: null, hi: null, st: null, en: [0, 2, 3, 6, 10, 14, 18, 22, 26, 30, 33, 34, 38], sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/overviewconfig.hpp:26", "CONFIG declaration: int easingType = 2"], ["shell/modules/nexus/pages/panels/OverviewPanel.qml:207", "shipped Nexus control (SelectRow)"]] }, + { n: "setEnableOverviewBlur", p: "overview.enableOverviewBlur", g: "overview", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/overviewconfig.hpp:13", "CONFIG declaration: bool enableOverviewBlur = true"], ["shell/modules/nexus/pages/panels/OverviewPanel.qml:197", "shipped Nexus control (ToggleRow)"]] }, + { n: "setGridFadeSpeed", p: "overview.gridFadeSpeed", g: "overview", k: "float", d: 1.0, lo: 0.1, hi: 5.0, st: 0.1, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/overviewconfig.hpp:25", "CONFIG declaration: qreal gridFadeSpeed = 1.0"], ["shell/modules/nexus/pages/panels/OverviewPanel.qml:252", "shipped Nexus control (StepperRow)"]] }, + { n: "setHoverBottomLeft", p: "overview.hoverBottomLeft", g: "overview", k: "bool", d: false, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/overviewconfig.hpp:19", "CONFIG declaration: bool hoverBottomLeft = false"], ["shell/modules/nexus/pages/panels/OverviewPanel.qml:159", "shipped Nexus control (ToggleRow)"]] }, + { n: "setHoverBottomRight", p: "overview.hoverBottomRight", g: "overview", k: "bool", d: false, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/overviewconfig.hpp:20", "CONFIG declaration: bool hoverBottomRight = false"], ["shell/modules/nexus/pages/panels/OverviewPanel.qml:164", "shipped Nexus control (ToggleRow)"]] }, + { n: "setHoverTopLeft", p: "overview.hoverTopLeft", g: "overview", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/overviewconfig.hpp:17", "CONFIG declaration: bool hoverTopLeft = true"], ["shell/modules/nexus/pages/panels/OverviewPanel.qml:148", "shipped Nexus control (ToggleRow)"]] }, + { n: "setHoverTopRight", p: "overview.hoverTopRight", g: "overview", k: "bool", d: false, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/overviewconfig.hpp:18", "CONFIG declaration: bool hoverTopRight = false"], ["shell/modules/nexus/pages/panels/OverviewPanel.qml:154", "shipped Nexus control (ToggleRow)"]] }, + { n: "setLayoutType", p: "overview.layoutType", g: "overview", k: "int", d: 1, lo: 0, hi: 1, st: 1, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/overviewconfig.hpp:27", "CONFIG declaration: int layoutType = 1"], ["shell/modules/nexus/pages/panels/OverviewPanel.qml:173", "shipped Nexus control (SelectRow)"]] }, + { n: "setOverviewDragThreshold", p: "overview.dragThreshold", g: "overview", k: "int", d: 30, lo: 10, hi: 200, st: 5, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/overviewconfig.hpp:15", "CONFIG declaration: int dragThreshold = 30"], ["shell/modules/nexus/pages/panels/OverviewPanel.qml:131", "shipped Nexus control (StepperRow)"]] }, + { n: "setOverviewEnabled", p: "overview.enabled", g: "overview", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/overviewconfig.hpp:11", "CONFIG declaration: bool enabled = true"], ["shell/modules/nexus/pages/panels/OverviewPanel.qml:108", "shipped Nexus control (ToggleRow)"]] }, + { n: "setOverviewHoverThickness", p: "overview.hoverThickness", g: "overview", k: "int", d: 20, lo: 1, hi: 100, st: 1, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/overviewconfig.hpp:16", "CONFIG declaration: int hoverThickness = 20"], ["shell/modules/nexus/pages/panels/OverviewPanel.qml:120", "shipped Nexus control (StepperRow)"]] }, + { n: "setOverviewShowOnHover", p: "overview.showOnHover", g: "overview", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/overviewconfig.hpp:14", "CONFIG declaration: bool showOnHover = true"], ["shell/modules/nexus/pages/panels/OverviewPanel.qml:114", "shipped Nexus control (ToggleRow)"]] }, + { n: "setWallpaperFadeSpeed", p: "overview.wallpaperFadeSpeed", g: "overview", k: "float", d: 1.0, lo: 0.1, hi: 5.0, st: 0.1, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/overviewconfig.hpp:24", "CONFIG declaration: qreal wallpaperFadeSpeed = 1.0"], ["shell/modules/nexus/pages/panels/OverviewPanel.qml:243", "shipped Nexus control (StepperRow)"]] }, + { n: "setEnableBrightness", p: "osd.enableBrightness", g: "osd", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/osdconfig.hpp:15", "CONFIG declaration: bool enableBrightness = true"], ["shell/modules/nexus/pages/utilities/OsdPage.qml:45", "shipped Nexus control (ToggleRow)"]] }, + { n: "setEnableMicrophone", p: "osd.enableMicrophone", g: "osd", k: "bool", d: false, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/osdconfig.hpp:16", "CONFIG declaration: bool enableMicrophone = false"], ["shell/modules/nexus/pages/utilities/OsdPage.qml:38", "shipped Nexus control (ToggleRow)"]] }, + { n: "setEnableVolume", p: "osd.enableVolume", g: "osd", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/osdconfig.hpp:17", "CONFIG declaration: bool enableVolume = true"], ["shell/modules/nexus/pages/utilities/OsdPage.qml:31", "shipped Nexus control (ToggleRow)"]] }, + { n: "setHideDelay", p: "osd.hideDelay", g: "osd", k: "int", d: 2000, lo: 1000, hi: 10000, st: 1000, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/osdconfig.hpp:12", "CONFIG declaration: int hideDelay = 2000"], ["shell/modules/nexus/pages/utilities/OsdPage.qml:83", "shipped Nexus control (StepperRow)"], ["shell/modules/nexus/pages/utilities/OsdPage.qml:88", "stepper displays seconds (value: x/1000; onMoved: Math.round(value*1000)); stored unit is ms — range converted x1000"]] }, + { n: "setOsdEnabled", p: "osd.enabled", g: "osd", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/osdconfig.hpp:11", "CONFIG declaration: bool enabled = true"], ["shell/modules/nexus/pages/utilities/OsdPage.qml:23", "shipped Nexus control (ToggleRow)"]] }, + { n: "setOsdHoverThickness", p: "osd.hoverThickness", g: "osd", k: "int", d: 10, lo: 1, hi: 100, st: 1, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/osdconfig.hpp:13", "CONFIG declaration: int hoverThickness = 10"], ["shell/modules/nexus/pages/utilities/OsdPage.qml:57", "shipped Nexus control (StepperRow)"]] }, + { n: "setOsdHoverWidth", p: "osd.hoverWidth", g: "osd", k: "int", d: 50, lo: 10, hi: 100, st: 5, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/osdconfig.hpp:14", "CONFIG declaration: int hoverWidth = 50"], ["shell/modules/nexus/pages/utilities/OsdPage.qml:68", "shipped Nexus control (StepperRow)"]] }, + { n: "setColorizeMediaGif", p: "dashboard.colorizeMediaGif", g: "dashboard", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/dashboardconfig.hpp:30", "CONFIG declaration: bool colorizeMediaGif = true"], ["shell/modules/nexus/pages/panels/DashboardPanel.qml:174", "shipped Nexus control (ToggleRow)"]] }, + { n: "setDashboardDragThreshold", p: "dashboard.dragThreshold", g: "dashboard", k: "int", d: 50, lo: 0, hi: 200, st: 5, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/dashboardconfig.hpp:36", "CONFIG declaration: int dragThreshold = 50"], ["shell/modules/nexus/pages/panels/DashboardPanel.qml:269", "shipped Nexus control (StepperRow)"]] }, + { n: "setDashboardEnabled", p: "dashboard.enabled", g: "dashboard", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/dashboardconfig.hpp:22", "CONFIG declaration: bool enabled = true"], ["shell/modules/nexus/pages/panels/DashboardPanel.qml:94", "shipped Nexus control (ToggleRow)"]] }, + { n: "setDashboardHoverThickness", p: "dashboard.hoverThickness", g: "dashboard", k: "int", d: 10, lo: 1, hi: 100, st: 1, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/dashboardconfig.hpp:37", "CONFIG declaration: int hoverThickness = 10"], ["shell/modules/nexus/pages/panels/DashboardPanel.qml:248", "shipped Nexus control (StepperRow)"]] }, + { n: "setDashboardHoverWidth", p: "dashboard.hoverWidth", g: "dashboard", k: "int", d: 50, lo: 10, hi: 100, st: 5, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/dashboardconfig.hpp:38", "CONFIG declaration: int hoverWidth = 50"], ["shell/modules/nexus/pages/panels/DashboardPanel.qml:259", "shipped Nexus control (StepperRow)"]] }, + { n: "setDashboardShowOnHover", p: "dashboard.showOnHover", g: "dashboard", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/dashboardconfig.hpp:23", "CONFIG declaration: bool showOnHover = true"], ["shell/modules/nexus/pages/panels/DashboardPanel.qml:101", "shipped Nexus control (ToggleRow)"]] }, + { n: "setMediaUpdateInterval", p: "dashboard.mediaUpdateInterval", g: "dashboard", k: "int", d: 500, lo: 100, hi: 2000, st: 50, en: null, sl: null, go: true, c: [["shell/plugin/src/Caelestia/Config/dashboardconfig.hpp:34", "CONFIG declaration: int mediaUpdateInterval = 500"], ["shell/modules/nexus/pages/ServicesPage.qml:89", "shipped Nexus control (StepperRow)"]] }, + { n: "setPerformanceShowBattery", p: "dashboard.performance.showBattery", g: "dashboard", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/dashboardconfig.hpp:11", "CONFIG declaration: bool showBattery = true"], ["shell/modules/nexus/pages/panels/DashboardPanel.qml:205", "shipped Nexus control (ToggleRow)"]] }, + { n: "setPerformanceShowCpu", p: "dashboard.performance.showCpu", g: "dashboard", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/dashboardconfig.hpp:13", "CONFIG declaration: bool showCpu = true"], ["shell/modules/nexus/pages/panels/DashboardPanel.qml:218", "shipped Nexus control (ToggleRow)"]] }, + { n: "setPerformanceShowGpu", p: "dashboard.performance.showGpu", g: "dashboard", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/dashboardconfig.hpp:12", "CONFIG declaration: bool showGpu = true"], ["shell/modules/nexus/pages/panels/DashboardPanel.qml:212", "shipped Nexus control (ToggleRow)"]] }, + { n: "setPerformanceShowMemory", p: "dashboard.performance.showMemory", g: "dashboard", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/dashboardconfig.hpp:14", "CONFIG declaration: bool showMemory = true"], ["shell/modules/nexus/pages/panels/DashboardPanel.qml:224", "shipped Nexus control (ToggleRow)"]] }, + { n: "setPerformanceShowNetwork", p: "dashboard.performance.showNetwork", g: "dashboard", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/dashboardconfig.hpp:16", "CONFIG declaration: bool showNetwork = true"], ["shell/modules/nexus/pages/panels/DashboardPanel.qml:236", "shipped Nexus control (ToggleRow)"]] }, + { n: "setPerformanceShowStorage", p: "dashboard.performance.showStorage", g: "dashboard", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/dashboardconfig.hpp:15", "CONFIG declaration: bool showStorage = true"], ["shell/modules/nexus/pages/panels/DashboardPanel.qml:230", "shipped Nexus control (ToggleRow)"]] }, + { n: "setResourceUpdateInterval", p: "dashboard.resourceUpdateInterval", g: "dashboard", k: "int", d: 1000, lo: 500, hi: 10000, st: 500, en: null, sl: null, go: true, c: [["shell/plugin/src/Caelestia/Config/dashboardconfig.hpp:35", "CONFIG declaration: int resourceUpdateInterval = 1000"], ["shell/modules/nexus/pages/ServicesPage.qml:100", "shipped Nexus control (StepperRow)"], ["shell/modules/nexus/pages/ServicesPage.qml:103", "stepper displays seconds (value: x/1000; onMoved: Math.round(v*1000)); stored unit is ms — range converted x1000"]] }, + { n: "setShowClockSeconds", p: "dashboard.showClockSeconds", g: "dashboard", k: "bool", d: false, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/dashboardconfig.hpp:32", "CONFIG declaration: bool showClockSeconds = false"], ["shell/modules/nexus/pages/panels/DashboardPanel.qml:128", "shipped Nexus control (ToggleRow)"]] }, + { n: "setShowDashboard", p: "dashboard.showDashboard", g: "dashboard", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/dashboardconfig.hpp:24", "CONFIG declaration: bool showDashboard = true"], ["shell/modules/nexus/pages/panels/DashboardPanel.qml:141", "shipped Nexus control (ToggleRow)"]] }, + { n: "setShowMedia", p: "dashboard.showMedia", g: "dashboard", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/dashboardconfig.hpp:25", "CONFIG declaration: bool showMedia = true"], ["shell/modules/nexus/pages/panels/DashboardPanel.qml:148", "shipped Nexus control (ToggleRow)"]] }, + { n: "setShowPerformance", p: "dashboard.showPerformance", g: "dashboard", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/dashboardconfig.hpp:26", "CONFIG declaration: bool showPerformance = true"], ["shell/modules/nexus/pages/panels/DashboardPanel.qml:154", "shipped Nexus control (ToggleRow)"]] }, + { n: "setShowTerminal", p: "dashboard.showTerminal", g: "dashboard", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/dashboardconfig.hpp:28", "CONFIG declaration: bool showTerminal = true"], ["shell/modules/nexus/pages/panels/DashboardPanel.qml:167", "shipped Nexus control (ToggleRow)"]] }, + { n: "setShowWeather", p: "dashboard.showWeather", g: "dashboard", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/dashboardconfig.hpp:27", "CONFIG declaration: bool showWeather = true"], ["shell/modules/nexus/pages/panels/DashboardPanel.qml:160", "shipped Nexus control (ToggleRow)"]] }, + { n: "setUseMediaShapes", p: "dashboard.useMediaShapes", g: "dashboard", k: "bool", d: false, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/dashboardconfig.hpp:31", "CONFIG declaration: bool useMediaShapes = false"], ["shell/modules/nexus/pages/panels/DashboardPanel.qml:182", "shipped Nexus control (ToggleRow)"]] }, + { n: "setGrabWidth", p: "sidebar.grabWidth", g: "sidebar", k: "int", d: 12, lo: 1, hi: 100, st: 1, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/sidebarconfig.hpp:13", "CONFIG declaration: int grabWidth = 12"], ["shell/modules/nexus/pages/panels/SidebarPanel.qml:48", "shipped Nexus control (StepperRow)"]] }, + { n: "setSidebarDragThreshold", p: "sidebar.dragThreshold", g: "sidebar", k: "int", d: 50, lo: 0, hi: 200, st: 5, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/sidebarconfig.hpp:12", "CONFIG declaration: int dragThreshold = 50"], ["shell/modules/nexus/pages/panels/SidebarPanel.qml:36", "shipped Nexus control (StepperRow)"]] }, + { n: "setSidebarEnabled", p: "sidebar.enabled", g: "sidebar", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/sidebarconfig.hpp:11", "CONFIG declaration: bool enabled = true"], ["shell/modules/nexus/pages/panels/SidebarPanel.qml:29", "shipped Nexus control (ToggleRow)"]] }, + { n: "setNetworkRescanInterval", p: "nexus.networkRescanInterval", g: "nexus", k: "int", d: 15000, lo: 5000, hi: 120000, st: 5000, en: null, sl: null, go: true, c: [["shell/plugin/src/Caelestia/Config/nexusconfig.hpp:12", "CONFIG declaration: int networkRescanInterval = 15000"], ["shell/modules/nexus/pages/ServicesPage.qml:110", "shipped Nexus control (StepperRow)"], ["shell/modules/nexus/pages/ServicesPage.qml:114", "stepper displays seconds (value: x/1000; onMoved: Math.round(v*1000)); stored unit is ms — range converted x1000"]] }, + { n: "setBorderThickness", p: "border.thickness", g: "border", k: "int", d: 10, lo: 0, hi: 50, st: 2, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/borderconfig.hpp:13", "CONFIG declaration: int thickness = 10"], ["shell/modules/nexus/pages/wallandstyle/AppearancePage.qml:108", "shipped Nexus control (StepperRow)"]] }, + { n: "setRounding", p: "border.rounding", g: "border", k: "int", d: 25, lo: 0, hi: 100, st: 1, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/borderconfig.hpp:14", "CONFIG declaration: int rounding = 25"], ["shell/modules/nexus/pages/wallandstyle/AppearancePage.qml:336", "shipped Nexus control (StepperRow)"]] }, + { n: "setSmoothing", p: "border.smoothing", g: "border", k: "int", d: 20, lo: 0, hi: 100, st: 1, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/borderconfig.hpp:15", "CONFIG declaration: int smoothing = 20"], ["shell/modules/nexus/pages/wallandstyle/AppearancePage.qml:347", "shipped Nexus control (StepperRow)"]] }, + { n: "setAllScreens", p: "tabSwitch.allScreens", g: "general", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/tabswitchconfig.hpp:15", "CONFIG declaration: bool allScreens = true"], ["shell/modules/nexus/pages/panels/TabSwitcherPanel.qml:164", "shipped Nexus control (ToggleRow)"]] }, + { n: "setCheckUpdates", p: "general.checkUpdates", g: "general", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/generalconfig.hpp:70", "CONFIG declaration: bool checkUpdates = true"], ["shell/modules/nexus/pages/panels/taskbar/BarUpdates.qml:44", "shipped Nexus control (ToggleRow)"]] }, + { n: "setCurrentDesktopOnly", p: "tabSwitch.currentDesktopOnly", g: "general", k: "bool", d: false, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/tabswitchconfig.hpp:12", "CONFIG declaration: bool currentDesktopOnly = false"], ["shell/modules/nexus/pages/panels/TabSwitcherPanel.qml:114", "shipped Nexus control (ToggleRow)"]] }, + { n: "setPreviewOnDesktop", p: "tabSwitch.previewOnDesktop", g: "general", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/tabswitchconfig.hpp:13", "CONFIG declaration: bool previewOnDesktop = true"], ["shell/modules/nexus/pages/panels/TabSwitcherPanel.qml:129", "shipped Nexus control (ToggleRow)"]] }, + { n: "setSessionDragThreshold", p: "session.dragThreshold", g: "general", k: "int", d: 30, lo: 10, hi: 200, st: 5, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/sessionconfig.hpp:36", "CONFIG declaration: int dragThreshold = 30"], ["shell/modules/nexus/pages/SessionPage.qml:53", "shipped Nexus control (StepperRow)"]] }, + { n: "setSessionEnabled", p: "session.enabled", g: "general", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/sessionconfig.hpp:35", "CONFIG declaration: bool enabled = true"], ["shell/modules/nexus/pages/SessionPage.qml:36", "shipped Nexus control (ToggleRow)"]] }, + { n: "setSessionVimKeybinds", p: "session.vimKeybinds", g: "general", k: "bool", d: false, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/sessionconfig.hpp:37", "CONFIG declaration: bool vimKeybinds = false"], ["shell/modules/nexus/pages/SessionPage.qml:45", "shipped Nexus control (ToggleRow)"]] }, + { n: "setShowMinimized", p: "tabSwitch.showMinimized", g: "general", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/tabswitchconfig.hpp:14", "CONFIG declaration: bool showMinimized = true"], ["shell/modules/nexus/pages/panels/TabSwitcherPanel.qml:149", "shipped Nexus control (ToggleRow)"]] }, + { n: "setArpcCaelestiaInfo", p: "services.arpcCaelestiaInfo", g: "services", k: "bool", d: false, lo: null, hi: null, st: null, en: null, sl: null, go: true, c: [["shell/plugin/src/Caelestia/Config/serviceconfig.hpp:82", "CONFIG declaration: bool arpcCaelestiaInfo = false"], ["shell/modules/nexus/pages/services/ArpcPage.qml:74", "shipped Nexus control (ToggleRow)"]] }, + { n: "setArpcEnabled", p: "services.arpcEnabled", g: "services", k: "bool", d: false, lo: null, hi: null, st: null, en: null, sl: null, go: true, c: [["shell/plugin/src/Caelestia/Config/serviceconfig.hpp:71", "CONFIG declaration: bool arpcEnabled = false"], ["shell/modules/nexus/pages/services/ArpcPage.qml:56", "shipped Nexus control (ToggleRow)"]] }, + { n: "setArpcIdleTimeout", p: "services.arpcIdleTimeout", g: "services", k: "int", d: 0, lo: 0, hi: 3600, st: 60, en: null, sl: null, go: true, c: [["shell/plugin/src/Caelestia/Config/serviceconfig.hpp:84", "CONFIG declaration: int arpcIdleTimeout = 0"], ["shell/modules/nexus/pages/services/ArpcPage.qml:83", "shipped Nexus control (StepperRow)"], ["shell/modules/nexus/pages/services/ArpcPage.qml:89", "stepper displays minutes (value: Math.round(x/60); onMoved: Math.round(v*60)); stored unit is seconds — range converted x60"]] }, + { n: "setArpcManualOverride", p: "services.arpcManualOverride", g: "services", k: "bool", d: false, lo: null, hi: null, st: null, en: null, sl: null, go: true, c: [["shell/plugin/src/Caelestia/Config/serviceconfig.hpp:83", "CONFIG declaration: bool arpcManualOverride = false"], ["shell/modules/nexus/pages/services/ArpcPage.qml:439", "shipped Nexus control (ToggleRow)"]] }, + { n: "setArpcSteamAutoDetect", p: "services.arpcSteamAutoDetect", g: "services", k: "bool", d: false, lo: null, hi: null, st: null, en: null, sl: null, go: true, c: [["shell/plugin/src/Caelestia/Config/serviceconfig.hpp:78", "CONFIG declaration: bool arpcSteamAutoDetect = false"], ["shell/modules/nexus/pages/services/ArpcPage.qml:65", "shipped Nexus control (ToggleRow)"]] }, + { n: "setAudioIncrement", p: "services.audioIncrement", g: "services", k: "float", d: 0.1, lo: 0.01, hi: 0.5, st: 0.01, en: null, sl: null, go: true, c: [["shell/plugin/src/Caelestia/Config/serviceconfig.hpp:51", "CONFIG declaration: qreal audioIncrement = 0.1"], ["shell/modules/nexus/pages/ServicesPage.qml:151", "shipped Nexus control (StepperRow)"], ["shell/modules/nexus/pages/ServicesPage.qml:155", "stepper displays percent (value: Math.round(x*100); onMoved: v/100); stored unit is a fraction — range converted /100"]] }, + { n: "setAutoSchemeEnabled", p: "services.autoSchemeEnabled", g: "services", k: "bool", d: false, lo: null, hi: null, st: null, en: null, sl: null, go: true, c: [["shell/plugin/src/Caelestia/Config/serviceconfig.hpp:59", "CONFIG declaration: bool autoSchemeEnabled = false"], ["shell/modules/nexus/pages/wallandstyle/AdvancedColorsPage.qml:89", "shipped Nexus control (ToggleRow)"]] }, + { n: "setAutoSchemeMode", p: "services.autoSchemeMode", g: "services", k: "enum", d: "solar", lo: null, hi: null, st: null, en: ["solar", "fixed"], sl: null, go: true, c: [["shell/plugin/src/Caelestia/Config/serviceconfig.hpp:60", "CONFIG declaration: QString autoSchemeMode = u\"solar\"_s"], ["shell/modules/nexus/pages/wallandstyle/AdvancedColorsPage.qml:98", "shipped Nexus control (SelectRow)"]] }, + { n: "setBrightnessIncrement", p: "services.brightnessIncrement", g: "services", k: "float", d: 0.1, lo: 0.01, hi: 0.5, st: 0.01, en: null, sl: null, go: true, c: [["shell/plugin/src/Caelestia/Config/serviceconfig.hpp:52", "CONFIG declaration: qreal brightnessIncrement = 0.1"], ["shell/modules/nexus/pages/ServicesPage.qml:162", "shipped Nexus control (StepperRow)"], ["shell/modules/nexus/pages/ServicesPage.qml:165", "stepper displays percent (value: Math.round(x*100); onMoved: v/100); stored unit is a fraction — range converted /100"]] }, + { n: "setClockFormat", p: "services.clockFormat", g: "services", k: "enum", d: "Auto", lo: null, hi: null, st: null, en: ["Auto", "TwelveHour", "TwentyFourHour"], sl: null, go: true, c: [["shell/plugin/src/Caelestia/Config/serviceconfig.hpp:37", "CONFIG declaration: caelestia::config::ClockFormat::Enum clockFormat = ClockFormat::Auto"], ["shell/modules/nexus/pages/LanguageAndRegion.qml:419", "shipped Nexus control (SelectRow)"]] }, + { n: "setDataUnits", p: "services.dataUnits", g: "services", k: "enum", d: "Binary", lo: null, hi: null, st: null, en: ["Binary", "Decimal"], sl: null, go: true, c: [["shell/plugin/src/Caelestia/Config/serviceconfig.hpp:31", "CONFIG declaration: caelestia::config::DataUnit::Enum dataUnits = DataUnit::Binary"], ["shell/modules/nexus/pages/LanguageAndRegion.qml:405", "shipped Nexus control (SelectRow)"]] }, + { n: "setGpuType", p: "services.gpuType", g: "services", k: "enum", d: "", lo: null, hi: null, st: null, en: ["", "NVIDIA", "GENERIC", "None"], sl: null, go: true, c: [["shell/plugin/src/Caelestia/Config/serviceconfig.hpp:49", "CONFIG declaration: QString gpuType = QString()"], ["shell/modules/nexus/pages/ServicesPage.qml:206", "shipped Nexus control (SelectRow)"], ["shell/modules/nexus/pages/ServicesPage.qml:47", "gpuValues: [\"\", \"NVIDIA\", \"GENERIC\", \"None\"] (fixed literal)"]] }, + { n: "setMaxVolume", p: "services.maxVolume", g: "services", k: "float", d: 1.0, lo: 0.5, hi: 2.0, st: 0.05, en: null, sl: null, go: true, c: [["shell/plugin/src/Caelestia/Config/serviceconfig.hpp:53", "CONFIG declaration: qreal maxVolume = 1.0"], ["shell/modules/nexus/pages/ServicesPage.qml:172", "shipped Nexus control (StepperRow)"], ["shell/modules/nexus/pages/ServicesPage.qml:176", "stepper displays percent (value: Math.round(x*100); onMoved: v/100); stored unit is a fraction — range converted /100"]] }, + { n: "setSensorUnits", p: "services.sensorUnits", g: "services", k: "enum", d: "Celsius", lo: null, hi: null, st: null, en: ["Auto", "Celsius", "Fahrenheit", "Kelvin"], sl: null, go: true, c: [["shell/plugin/src/Caelestia/Config/serviceconfig.hpp:30", "CONFIG declaration: caelestia::config::TemperatureUnit::Enum sensorUnits = TemperatureUnit::Celsius"], ["shell/modules/nexus/pages/LanguageAndRegion.qml:397", "shipped Nexus control (SelectRow)"]] }, + { n: "setSmartScheme", p: "services.smartScheme", g: "services", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: true, c: [["shell/plugin/src/Caelestia/Config/serviceconfig.hpp:54", "CONFIG declaration: bool smartScheme = true"], ["shell/modules/nexus/pages/wallandstyle/AdvancedColorsPage.qml:81", "shipped Nexus control (ToggleRow)"]] }, + { n: "setVisualiserBars", p: "services.visualiserBars", g: "services", k: "int", d: 60, lo: 10, hi: 120, st: 2, en: null, sl: null, go: true, c: [["shell/plugin/src/Caelestia/Config/serviceconfig.hpp:50", "CONFIG declaration: int visualiserBars = 60"], ["shell/modules/nexus/pages/ServicesPage.qml:196", "shipped Nexus control (StepperRow)"]] }, + { n: "setWeatherUnits", p: "services.weatherUnits", g: "services", k: "enum", d: "Auto", lo: null, hi: null, st: null, en: ["Auto", "Celsius", "Fahrenheit", "Kelvin"], sl: null, go: true, c: [["shell/plugin/src/Caelestia/Config/serviceconfig.hpp:29", "CONFIG declaration: caelestia::config::TemperatureUnit::Enum weatherUnits = TemperatureUnit::Auto"], ["shell/modules/nexus/pages/LanguageAndRegion.qml:388", "shipped Nexus control (SelectRow)"]] }, + { n: "setGameModeAutoEnable", p: "utilities.gameMode.autoEnable", g: "utilities", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: true, c: [["shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:69", "CONFIG declaration: bool autoEnable = true"], ["shell/modules/nexus/pages/services/GameModePage.qml:35", "shipped Nexus control (ToggleRow)"]] }, + { n: "setGameModeDisableDesktopLyrics", p: "utilities.gameMode.disableDesktopLyrics", g: "utilities", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: true, c: [["shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:66", "CONFIG declaration: bool disableDesktopLyrics = true"], ["shell/modules/nexus/pages/services/GameModePage.qml:109", "shipped Nexus control (ToggleRow)"]] }, + { n: "setGameModeDisableHyprlandAnimations", p: "utilities.gameMode.disableHyprlandAnimations", g: "utilities", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: true, c: [["shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:59", "CONFIG declaration: bool disableHyprlandAnimations = true"], ["shell/modules/nexus/pages/services/GameModePage.qml:60", "shipped Nexus control (ToggleRow)"]] }, + { n: "setGameModeDisableHyprlandBlur", p: "utilities.gameMode.disableHyprlandBlur", g: "utilities", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: true, c: [["shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:60", "CONFIG declaration: bool disableHyprlandBlur = true"], ["shell/modules/nexus/pages/services/GameModePage.qml:67", "shipped Nexus control (ToggleRow)"]] }, + { n: "setGameModeDisableHyprlandGaps", p: "utilities.gameMode.disableHyprlandGaps", g: "utilities", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: true, c: [["shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:61", "CONFIG declaration: bool disableHyprlandGaps = true"], ["shell/modules/nexus/pages/services/GameModePage.qml:73", "shipped Nexus control (ToggleRow)"]] }, + { n: "setGameModeDisableHyprlandShadows", p: "utilities.gameMode.disableHyprlandShadows", g: "utilities", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: true, c: [["shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:62", "CONFIG declaration: bool disableHyprlandShadows = true"], ["shell/modules/nexus/pages/services/GameModePage.qml:79", "shipped Nexus control (ToggleRow)"]] }, + { n: "setGameModeDisableShellTransparency", p: "utilities.gameMode.disableShellTransparency", g: "utilities", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: true, c: [["shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:63", "CONFIG declaration: bool disableShellTransparency = true"], ["shell/modules/nexus/pages/services/GameModePage.qml:98", "shipped Nexus control (ToggleRow)"]] }, + { n: "setGameModeDisableToastTransparency", p: "utilities.gameMode.disableToastTransparency", g: "utilities", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: true, c: [["shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:65", "CONFIG declaration: bool disableToastTransparency = true"], ["shell/modules/nexus/pages/services/GameModePage.qml:104", "shipped Nexus control (ToggleRow)"]] }, + { n: "setGameModeDisableVisualizer", p: "utilities.gameMode.disableVisualizer", g: "utilities", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: true, c: [["shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:67", "CONFIG declaration: bool disableVisualizer = true"], ["shell/modules/nexus/pages/services/GameModePage.qml:114", "shipped Nexus control (ToggleRow)"]] }, + { n: "setGameModeDisableWindowTransparency", p: "utilities.gameMode.disableWindowTransparency", g: "utilities", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: true, c: [["shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:64", "CONFIG declaration: bool disableWindowTransparency = true"], ["shell/modules/nexus/pages/services/GameModePage.qml:85", "shipped Nexus control (ToggleRow)"]] }, + { n: "setMaxToasts", p: "utilities.maxToasts", g: "utilities", k: "int", d: 4, lo: 1, hi: 10, st: 1, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:81", "CONFIG declaration: int maxToasts = 4"], ["shell/modules/nexus/pages/services/ToastPreferencesPage.qml:50", "shipped Nexus control (StepperRow)"]] }, + { n: "setShowGifRecorder", p: "utilities.showGifRecorder", g: "utilities", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:87", "CONFIG declaration: bool showGifRecorder = true"], ["shell/modules/nexus/pages/utilities/UtilitiesPanelPage.qml:38", "shipped Nexus control (ToggleRow)"]] }, + { n: "setShowKeepAwake", p: "utilities.showKeepAwake", g: "utilities", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:85", "CONFIG declaration: bool showKeepAwake = true"], ["shell/modules/nexus/pages/utilities/UtilitiesPanelPage.qml:23", "shipped Nexus control (ToggleRow)"]] }, + { n: "setShowQuickToggles", p: "utilities.showQuickToggles", g: "utilities", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:88", "CONFIG declaration: bool showQuickToggles = true"], ["shell/modules/nexus/pages/utilities/UtilitiesPanelPage.qml:45", "shipped Nexus control (ToggleRow)"]] }, + { n: "setShowScreenRecorder", p: "utilities.showScreenRecorder", g: "utilities", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:86", "CONFIG declaration: bool showScreenRecorder = true"], ["shell/modules/nexus/pages/utilities/UtilitiesPanelPage.qml:31", "shipped Nexus control (ToggleRow)"]] }, + { n: "setToastsChargingChanged", p: "utilities.toasts.chargingChanged", g: "utilities", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: true, c: [["shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:19", "CONFIG declaration: bool chargingChanged = true"], ["shell/modules/nexus/pages/services/ToastEventsPage.qml:26", "shipped Nexus control (ToggleRow)"]] }, + { n: "setToastsConfigLoaded", p: "utilities.toasts.configLoaded", g: "utilities", k: "bool", d: false, lo: null, hi: null, st: null, en: null, sl: null, go: true, c: [["shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:18", "CONFIG declaration: bool configLoaded = false"], ["shell/modules/nexus/pages/services/ToastEventsPage.qml:45", "shipped Nexus control (ToggleRow)"]] }, + { n: "setToastsFullscreen", p: "utilities.toasts.fullscreen", g: "utilities", k: "enum", d: "off", lo: null, hi: null, st: null, en: ["off", "important", "all"], sl: null, go: true, c: [["shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:17", "CONFIG declaration: QString fullscreen = u\"off\"_s"], ["shell/modules/nexus/pages/services/ToastPreferencesPage.qml:41", "shipped Nexus control (SelectRow)"]] }, + { n: "setToastsGameModeChanged", p: "utilities.toasts.gameModeChanged", g: "utilities", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: true, c: [["shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:20", "CONFIG declaration: bool gameModeChanged = true"], ["shell/modules/nexus/pages/services/ToastEventsPage.qml:32", "shipped Nexus control (ToggleRow)"]] }, + { n: "setToastsNightLightChanged", p: "utilities.toasts.nightLightChanged", g: "utilities", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: true, c: [["shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:31", "CONFIG declaration: bool nightLightChanged = true"], ["shell/modules/nexus/pages/services/ToastEventsPage.qml:38", "shipped Nexus control (ToggleRow)"]] }, + { n: "setToastsTransparency", p: "utilities.toasts.transparency", g: "utilities", k: "bool", d: false, lo: null, hi: null, st: null, en: null, sl: null, go: true, c: [["shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:32", "CONFIG declaration: bool transparency = false"], ["shell/modules/nexus/pages/services/ToastPreferencesPage.qml:60", "shipped Nexus control (ToggleRow)"]] }, + { n: "setToastsTransparencyBase", p: "utilities.toasts.transparencyBase", g: "utilities", k: "float", d: 0.85, lo: 0, hi: 1, st: null, en: null, sl: null, go: true, c: [["shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:33", "CONFIG declaration: qreal transparencyBase = 0.85"], ["shell/modules/nexus/pages/services/ToastPreferencesPage.qml:67", "shipped Nexus control (SliderRow)"]] }, + { n: "setUtilitiesDragThreshold", p: "utilities.dragThreshold", g: "utilities", k: "int", d: 50, lo: 0, hi: 200, st: 5, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:78", "CONFIG declaration: int dragThreshold = 50"], ["shell/modules/nexus/pages/panels/UtilitiesPanel.qml:68", "shipped Nexus control (StepperRow)"]] }, + { n: "setUtilitiesEnabled", p: "utilities.enabled", g: "utilities", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:76", "CONFIG declaration: bool enabled = true"], ["shell/modules/nexus/pages/panels/UtilitiesPanel.qml:29", "shipped Nexus control (ToggleRow)"]] }, + { n: "setUtilitiesHoverThickness", p: "utilities.hoverThickness", g: "utilities", k: "int", d: 10, lo: 1, hi: 100, st: 1, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:79", "CONFIG declaration: int hoverThickness = 10"], ["shell/modules/nexus/pages/panels/UtilitiesPanel.qml:44", "shipped Nexus control (StepperRow)"]] }, + { n: "setUtilitiesHoverWidth", p: "utilities.hoverWidth", g: "utilities", k: "int", d: 50, lo: 10, hi: 100, st: 5, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:80", "CONFIG declaration: int hoverWidth = 50"], ["shell/modules/nexus/pages/panels/UtilitiesPanel.qml:56", "shipped Nexus control (StepperRow)"]] }, + { n: "setUtilitiesShowOnHover", p: "utilities.showOnHover", g: "utilities", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: false, c: [["shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:77", "CONFIG declaration: bool showOnHover = true"], ["shell/modules/nexus/pages/panels/UtilitiesPanel.qml:36", "shipped Nexus control (ToggleRow)"]] }, + { n: "setSoundsCameraClick", p: "audio.sounds.cameraClick", g: "audio", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: true, c: [["shell/plugin/src/Caelestia/Config/audioconfig.hpp:12", "CONFIG declaration: bool cameraClick = true"], ["shell/modules/nexus/pages/audio/SoundEffectsPage.qml:46", "shipped Nexus control (ToggleRow)"]] }, + { n: "setSoundsChargingStarted", p: "audio.sounds.chargingStarted", g: "audio", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: true, c: [["shell/plugin/src/Caelestia/Config/audioconfig.hpp:13", "CONFIG declaration: bool chargingStarted = true"], ["shell/modules/nexus/pages/audio/SoundEffectsPage.qml:66", "shipped Nexus control (ToggleRow)"]] }, + { n: "setSoundsEffectTick", p: "audio.sounds.effectTick", g: "audio", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: true, c: [["shell/plugin/src/Caelestia/Config/audioconfig.hpp:14", "CONFIG declaration: bool effectTick = true"], ["shell/modules/nexus/pages/audio/SoundEffectsPage.qml:54", "shipped Nexus control (ToggleRow)"]] }, + { n: "setSoundsEnabled", p: "audio.sounds.enabled", g: "audio", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: true, c: [["shell/plugin/src/Caelestia/Config/audioconfig.hpp:11", "CONFIG declaration: bool enabled = true"], ["shell/modules/nexus/pages/audio/SoundEffectsPage.qml:24", "shipped Nexus control (ToggleRow)"]] }, + { n: "setSoundsLock", p: "audio.sounds.lock", g: "audio", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: true, c: [["shell/plugin/src/Caelestia/Config/audioconfig.hpp:15", "CONFIG declaration: bool lock = true"], ["shell/modules/nexus/pages/audio/SoundEffectsPage.qml:74", "shipped Nexus control (ToggleRow)"]] }, + { n: "setSoundsLowBattery", p: "audio.sounds.lowBattery", g: "audio", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: true, c: [["shell/plugin/src/Caelestia/Config/audioconfig.hpp:17", "CONFIG declaration: bool lowBattery = true"], ["shell/modules/nexus/pages/audio/SoundEffectsPage.qml:88", "shipped Nexus control (ToggleRow)"]] }, + { n: "setSoundsNotificationVolume", p: "audio.sounds.notificationVolume", g: "audio", k: "float", d: 1.0, lo: 0, hi: 1, st: null, en: null, sl: null, go: true, c: [["shell/plugin/src/Caelestia/Config/audioconfig.hpp:22", "CONFIG declaration: qreal notificationVolume = 1.0"], ["shell/modules/nexus/pages/services/ToastPreferencesPage.qml:80", "shipped Nexus control (SliderRow)"]] }, + { n: "setSoundsScreenRecord", p: "audio.sounds.screenRecord", g: "audio", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: true, c: [["shell/plugin/src/Caelestia/Config/audioconfig.hpp:18", "CONFIG declaration: bool screenRecord = true"], ["shell/modules/nexus/pages/audio/SoundEffectsPage.qml:95", "shipped Nexus control (ToggleRow)"]] }, + { n: "setSoundsSfxVolume", p: "audio.sounds.sfxVolume", g: "audio", k: "float", d: 1.0, lo: 0, hi: 1, st: null, en: null, sl: null, go: true, c: [["shell/plugin/src/Caelestia/Config/audioconfig.hpp:21", "CONFIG declaration: qreal sfxVolume = 1.0"], ["shell/modules/nexus/pages/audio/SoundEffectsPage.qml:31", "shipped Nexus control (SliderRow)"]] }, + { n: "setSoundsUnlock", p: "audio.sounds.unlock", g: "audio", k: "bool", d: true, lo: null, hi: null, st: null, en: null, sl: null, go: true, c: [["shell/plugin/src/Caelestia/Config/audioconfig.hpp:16", "CONFIG declaration: bool unlock = true"], ["shell/modules/nexus/pages/audio/SoundEffectsPage.qml:81", "shipped Nexus control (ToggleRow)"]] }, + ] + + // Named presets: bundles of validated tool calls only (see + // curations.PRESETS; build_registry validates every call). + readonly property var presetTable: [ + { name: "compact", label: "Compact", description: "Smaller dock icons and tighter spacing/padding/rounding — the same keys the Nexus steppers expose.", calls: [["setDockIconSize", 24], ["setSpacingScale", 0.8], ["setPaddingScale", 0.8], ["setRoundingScale", 0.8]] }, + { name: "minimal", label: "Minimal", description: "Issue #120's own example direction: smaller bar and dock, lower rounding, faster animations, badges and previews off.", calls: [["setBarScale", 0.7], ["setDockIconSize", 20], ["setRoundingScale", 0.5], ["setAnimationSpeed", 0.5], ["setSpacingScale", 0.7], ["setDockBadges", false], ["setLivePreviews", false]] }, + { name: "gaming", label: "Gaming", description: "Snappier shell, no blur/transparency compositing, no popup notifications. (Game Mode itself is a service toggle, not a shell.json scalar — this bundle is the config-side reduction only.)", calls: [["setBlurEnabled", false], ["setTransparencyEnabled", false], ["setAnimationSpeed", 0.25], ["setNotifsMaxPopups", 0]] }, + { name: "battery-saver", label: "Battery saver", description: "Reduce compositing and background work: blur, ambient glow and wallpaper recolour off, animations fast.", calls: [["setBlurEnabled", false], ["setAnimationSpeed", 0.25], ["setAmbientColor", false], ["setWallpaperRecolor", false]] }, + { name: "macos-like", label: "More like macOS", description: "Always-visible bottom dock with larger icons, rounder corners, roomier spacing and badges on — the keys the shipped controls already expose.", calls: [["setBarPosition", "bottom"], ["setBarPersistent", true], ["setDockIconSize", 48], ["setRoundingScale", 1.3], ["setSpacingScale", 1.1], ["setPaddingScale", 1.1], ["setAnimationSpeed", 1.0], ["setDockBadges", true]] }, + ] + + // Explainability rules: state predicate + answer template + citations. + // Rendered identically by the Python CLI (assistant/settings/explain.py). + readonly property var explainTable: [ + { path: "appearance.blur", when: "appearance.blur == true and appearance.transparency.enabled == true", answer: "Blur is enabled because transparency is currently active and appearance.blur is on — the blur regions gate on both ({cite}).", cites: ["shell/modules/drawers/blur/BlurOffsets.qml:17"] }, + { path: "appearance.blur", when: "appearance.blur == true and appearance.transparency.enabled == false", answer: "Blur is ON but has no effect, because transparency is currently disabled — the blur regions gate on transparency.enabled && blur together ({cite}).", cites: ["shell/modules/drawers/blur/BlurOffsets.qml:17"] }, + { path: "appearance.transparency.enabled", when: "appearance.transparency.enabled == true and utilities.gameMode.disableShellTransparency == true and _gamemode == true", answer: "Transparency is configured ON but is currently suppressed, because Game Mode is active with 'disable shell transparency' set — the colour service gates on that pair ({cite}).", cites: ["shell/services/Colours.qml:418"] }, + { path: "appearance.transparency.base", when: "appearance.transparency.base > 0 and _light == true", answer: "Surfaces look less transparent than the configured base opacity {appearance.transparency.base}, because light mode trims the base by 0.1 ({cite}).", cites: ["shell/services/Colours.qml:419"] }, + { path: "appearance.pitchBlack", when: "appearance.pitchBlack == true", answer: "Surfaces are fully opaque and pure black because Pitch Black (bezel mode) is active — it forces opacity 1 ({cite1}) and #000000 surfaces ({cite2}).", cites: ["shell/modules/drawers/ContentWindow.qml:383", "shell/modules/drawers/ContentWindow.qml:394"] }, + { path: "overview.enableOverviewBlur", when: "overview.enableOverviewBlur == true and appearance.blur == false", answer: "The overview blur setting is ON but has no effect, because the global appearance blur is off — the overview effect gates on both ({cite}).", cites: ["shell/modules/drawers/ContentWindow.qml:374"] }, + { path: "appearance.anim.durations.scale", when: "appearance.anim.durations.scale != 1", answer: "Animations feel {slower|faster} because the animation duration scale is currently set to {appearance.anim.durations.scale} — every duration token is multiplied by it, so lower means faster ({cite}).", cites: ["shell/plugin/src/Caelestia/Config/appearanceconfig.cpp:209"] }, + { path: "appearance.ambientColor", when: "appearance.ambientColor == true and _light == true", answer: "The ambient glow is configured ON but is currently hidden, because ambient glow only renders in dark mode — it gates on ambientColor && !light ({cite}).", cites: ["shell/components/effects/AmbientGlow.qml:34"] }, + { path: "bar.persistent", when: "bar.persistent == false", answer: "The bar hides because bar persistence is currently off — a non-persistent bar dodges or auto-hides instead of staying put ({cite}).", cites: ["shell/modules/bar/BarWrapper.qml:62"] }, + { path: "bar.dodgeWindows", when: "bar.dodgeWindows == true and bar.persistent == false", answer: "Window dodging has no effect, because dodge mode requires a persistent bar — the dodge gate is dodgeWindows && persistent ({cite}).", cites: ["shell/modules/bar/BarWrapper.qml:27"] }, + { path: "bar.scale", when: "bar.scale < 0.6", answer: "The bar is not as small as asked: the effective bar scale is floored at 0.6 ({cite}); the configured value is {bar.scale}.", cites: ["shell/modules/bar/BarWrapper.qml:24"] }, + ] + + Component.onCompleted: { + for (let i = 0; i < toolTable.length; i++) { + const t = toolTable[i]; + toolsByName[t.n] = t; + toolsByPath[t.p] = t; + } + const seen = []; + for (let i = 0; i < toolTable.length; i++) { + const g = toolTable[i].g; + if (seen.indexOf(g) === -1) + seen.push(g); + } + groups = seen; + } + + // ---- lookups ---------------------------------------------------------- + + function toolInfo(name) { + const t = toolsByName[name]; + if (!t) + return null; + return { + name: t.n, path: t.p, group: t.g, kind: t.k, default: t.d, + minimum: t.lo, maximum: t.hi, step: t.st, enum: t.en, + stringMaxLen: t.sl, globalOnly: t.go, citations: t.c || [] + }; + } + + function toolsInGroup(slug) { + const out = []; + for (let i = 0; i < toolTable.length; i++) + if (toolTable[i].g === slug) + out.push(toolTable[i].n); + return out; + } + + // Compact schema lines for the in-shell model (the 277-row table is too + // large for a system prompt; the model lists what it needs on demand). + function listTools(group) { + const lines = []; + for (let i = 0; i < toolTable.length; i++) { + const t = toolTable[i]; + if (group && t.g !== group) + continue; + let validation; + if (t.k === "enum") validation = (t.en || []).join("|"); + else if (t.k === "bool") validation = "on/off"; + else if (t.k === "string") validation = `string<=${t.sl || 64}`; + else validation = `${t.lo}-${t.hi}`; + lines.push(`${t.n} ${t.p} ${t.k} ${validation} default ${_fmtVal(t.d)}`); + } + if (group && lines.length === 0) + return { ok: false, reason: `unknown group ${group}; available: ${groups.join(", ")}` }; + return { ok: true, lines: lines, groups: groups }; + } + + // Read-only get for the model: live value + validation + grounding. + function get(path) { + const t = toolsByPath[path] !== undefined ? toolsByPath[path] + : toolsByName[path] !== undefined ? toolsByName[path] : null; + if (!t) + return { ok: false, reason: `unknown setting ${path}` }; + const value = readPath(t.p); + let validation; + if (t.k === "enum") validation = (t.en || []).join("|"); + else if (t.k === "bool") validation = "on/off"; + else if (t.k === "string") validation = `string<=${t.sl || 64}`; + else validation = `${t.lo}-${t.hi}`; + return { + ok: true, name: t.n, path: t.p, group: t.g, kind: t.k, + value: value === null ? t.d : value, validation: validation, + default: t.d, globalOnly: t.go, citations: (t.c || []).map(c => c[0]) + }; + } + + // ---- validation (mirrors planner.py's set branch) ---------------------- + + function validate(name, value) { + const t = toolsByName[name]; + if (!t) + return { ok: false, reason: `unknown tool ${name}` }; + if (t.k === "bool") { + if (typeof value !== "boolean") + return { ok: false, reason: "this setting is on/off only; it has no magnitude" }; + return { ok: true, value: value }; + } + if (t.k === "enum") { + const en = t.en || []; + for (let i = 0; i < en.length; i++) { + if (en[i] === value) + return { ok: true, value: en[i] }; + // Case-insensitive acceptance, canonicalized to the stored + // form (string enums only) — mirrors EnumCodec::decode's + // case-insensitive key match (codecs.cpp:249-257). + if (typeof en[i] === "string" && typeof value === "string" + && en[i].toLowerCase() === value.toLowerCase()) + return { ok: true, value: en[i] }; + } + return { ok: false, reason: `value '${value}' is not one of ${en.join("|")}` }; + } + if (t.k === "string") { + if (typeof value !== "string" || value.length === 0) + return { ok: false, reason: "a non-empty string is required" }; + if (value.length > (t.sl || 64)) + return { ok: false, reason: `string longer than ${t.sl || 64} characters` }; + return { ok: true, value: value }; + } + if (typeof value !== "number" || !isFinite(value)) + return { ok: false, reason: `value '${value}' is not a number` }; + if (t.k === "int" && Math.round(value) !== value) + return { ok: false, reason: "this setting is an integer" }; + if (t.lo !== null && value < t.lo) + return { ok: false, reason: `absolute value ${value} is outside the allowed range ${t.lo}-${t.hi}; it is not applied` }; + if (t.hi !== null && value > t.hi) + return { ok: false, reason: `absolute value ${value} is outside the allowed range ${t.lo}-${t.hi}; it is not applied` }; + return { ok: true, value: value }; + } + + // ---- live config read/write (the Nexus idiom, one writer here) -------- + + function readPath(path) { + const segs = path.split("."); + let obj = GlobalConfig; + for (let i = 0; i < segs.length - 1; i++) { + obj = obj[segs[i]]; + if (obj === undefined || obj === null) + return null; + } + const v = obj[segs[segs.length - 1]]; + return v === undefined ? null : v; + } + + function writePath(path, value) { + const segs = path.split("."); + let obj = GlobalConfig; + for (let i = 0; i < segs.length - 1; i++) { + obj = obj[segs[i]]; + if (obj === undefined || obj === null) + return false; + } + obj[segs[segs.length - 1]] = value; + return true; + } + + // ---- plan / confirm / apply -------------------------------------------- + // + // request(calls, label) implements issue #120's confirmation policy: + // a request resolving to ONE tool call applies immediately (undoable); + // a request resolving to MORE THAN ONE becomes a pending plan the chat + // UI must surface as a preview card — nothing is written until + // confirmPlan(). cancelPlan() drops it untouched. + + function buildPlan(calls, label) { + // calls: [{name, value}] (or {tool, value}); returns + // {ok, plan?, reason?}; the plan is all-or-nothing: any invalid + // entry rejects the whole plan before a single write happens. + const ops = []; + for (let i = 0; i < calls.length; i++) { + const c = calls[i]; + const name = c.name !== undefined ? c.name : c.tool; + const t = toolsByName[name]; + if (!t) + return { ok: false, reason: `unknown tool ${name}` }; + const v = validate(name, c.value); + if (!v.ok) + return { ok: false, reason: `${name}: ${v.reason}` }; + const old = readPath(t.p); + ops.push({ name: t.n, path: t.p, kind: t.k, old: old, new: v.value, + noOp: old === v.value }); + } + return { ok: true, plan: { label: label || "", ops: ops } }; + } + + function request(calls, label) { + const r = buildPlan(calls, label); + if (!r.ok) + return r; + const applicable = r.plan.ops.filter(op => !op.noOp); + if (applicable.length === 0) + return { ok: true, applied: false, message: "no changes needed; nothing written" }; + if (applicable.length === 1) { + const res = applyOps(applicable, r.plan.label); + return { ok: true, applied: true, changes: res.changes, message: res.message }; + } + pendingPlan = { plan: r.plan, applicable: applicable }; + return { ok: true, needsConfirm: true, plan: previewOf(r.plan) }; + } + + function previewOf(plan) { + // The confirm card's payload: one line per op, in the issue's own + // shape ("I found several changes that match your request: ..."). + const lines = []; + for (let i = 0; i < plan.ops.length; i++) { + const op = plan.ops[i]; + lines.push({ + name: op.name, path: op.path, + from: op.old === null ? "(unset)" : String(op.old), + to: String(op.new), noOp: op.noOp + }); + } + return { label: plan.label, ops: lines }; + } + + function confirmPlan() { + if (!pendingPlan) + return { ok: false, reason: "no pending plan to confirm" }; + const p = pendingPlan; + pendingPlan = null; + const res = applyOps(p.applicable, p.plan.label); + return { ok: true, applied: true, changes: res.changes, message: res.message }; + } + + function cancelPlan() { + if (!pendingPlan) + return { ok: false, reason: "no pending plan to cancel" }; + pendingPlan = null; + return { ok: true, applied: false, message: "plan cancelled; nothing was written" }; + } + + function applyOps(ops, label) { + // The only write path. Records the undo entry AFTER every write + // succeeded, so a failed write leaves no phantom history entry. + const recorded = []; + for (let i = 0; i < ops.length; i++) { + const op = ops[i]; + if (!writePath(op.path, op.new)) { + // Roll back what we already wrote this call (best effort; + // the failed write itself changed nothing). + for (let j = 0; j < recorded.length; j++) + writePath(recorded[j].path, recorded[j].old); + return { changes: 0, message: `write failed at ${op.path}; rolled back ${recorded.length} change(s); nothing else was written` }; + } + recorded.push(op); + } + pushHistory(label, ops.map(op => ({ path: op.path, old: op.old, new: op.new }))); + return { changes: ops.length, + message: `applied ${ops.length} change(s)${label ? ` (${label})` : ""}; undo is available` }; + } + + // ---- bounded undo history (>= 10, oldest evicted first) ----------------- + + function _persistHistory() { + const trimmed = history.slice(0, maxHistory); // FIFO: oldest evicted + if (trimmed.length !== history.length) + history = trimmed; + historyFile.setText(JSON.stringify(history)); + } + + function pushHistory(label, ops) { + const entry = { + id: Date.now() + Math.floor(Math.random() * 1000), + at: new Date().toISOString(), + label: label || "", + ops: ops + }; + history.unshift(entry); + _persistHistory(); + } + + function historyEntries() { + return history.map(e => ({ id: e.id, at: e.at, label: e.label, ops: e.ops.length })); + } + + function undo(steps) { + const n = Math.max(1, steps || 1); + let undone = 0; + for (let i = 0; i < n && history.length > 0; i++) { + const entry = history.shift(); + // Reverse order: undo the newest entry's ops back-to-front so + // interdependent keys restore in the opposite order they were set. + for (let j = entry.ops.length - 1; j >= 0; j--) + writePath(entry.ops[j].path, entry.ops[j].old); + undone++; + } + if (undone === 0) + return { ok: false, reason: "nothing to undo (history is empty)" }; + _persistHistory(); + return { ok: true, undone: undone, + message: `undid ${undone} apply entr${undone === 1 ? "y" : "ies"}` }; + } + + function undoById(id) { + const idx = history.findIndex(e => e.id === id); + if (idx === -1) + return { ok: false, reason: `no history entry with id ${id}` }; + const entry = history[idx]; + for (let j = entry.ops.length - 1; j >= 0; j--) + writePath(entry.ops[j].path, entry.ops[j].old); + history.splice(idx, 1); + _persistHistory(); + return { ok: true, undone: 1, + message: `reverted '${entry.label || entry.ops[0].path}' (${entry.ops.length} change(s), applied ${entry.at})` }; + } + + // ---- explainability (read-only; grounded in the same registry) ---------- + // + // explain(path) answers in issue #120's own style. Causal rules from + // tools.json's explainTable run first (each grounded in a real QML/C++ + // citation); with no rule firing, the answer is the live value readback + // with validation + default + citation, e.g. "The bar scale is + // currently set to 1.2 (range 0.6-1.6, default 1; barconfig.hpp:233)." + + function _liveState(paths) { + const state = {}; + for (let i = 0; i < paths.length; i++) + state[paths[i]] = readPath(paths[i]); + // Live session flags the offline CLI cannot know (documented): + state._gamemode = GameMode.enabled; + state._light = Colours.light; + return state; + } + + function _pathsIn(expr) { + const out = []; + const re = /([A-Za-z_][\w.]*)/g; + let m; + while ((m = re.exec(expr)) !== null) { + if (m[1] !== "true" && m[1] !== "false" && out.indexOf(m[1]) === -1) + out.push(m[1]); + } + return out; + } + + function _evalWhen(rule, state) { + // Restricted predicate grammar: `path == value`, `!=`, `>`, `<` + // joined by ` and ` (see curations.EXPLAIN_RULES). Unknown state + // keys make the rule NOT fire (offline honesty), never guess. + const clauses = String(rule.when).split(" and "); + for (let i = 0; i < clauses.length; i++) { + const m = clauses[i].match(/^\s*([\w.]+)\s*(==|!=|>|<)\s*(.+?)\s*$/); + if (!m) + return false; + const have = state[m[1]]; + if (have === undefined || have === null) + return false; + let want = m[3]; + let wantV; + if (want === "true") wantV = true; + else if (want === "false") wantV = false; + else if (/^-?\d+(\.\d+)?$/.test(want)) wantV = Number(want); + else wantV = want.replace(/^["']|["']$/g, ""); + let r; + if (m[2] === "==") r = _valuesEqual(have, wantV); + else if (m[2] === "!=") r = !_valuesEqual(have, wantV); + else if (m[2] === ">") r = have > wantV; + else r = have < wantV; + if (!r) + return false; + } + return true; + } + + function _valuesEqual(have, wantV) { + if (have === wantV) + return true; + if (typeof have === "number" && typeof wantV === "number" + && Math.abs(have - wantV) < 1e-9) + return true; + if (typeof have === "boolean" && typeof wantV === "string") + return String(have) === wantV; + return false; + } + + function _fmtVal(v) { + if (v === true) return "on"; + if (v === false) return "off"; + if (typeof v === "number") { + const r = Math.round(v * 100) / 100; + return String(r); + } + return String(v); + } + + function _renderAnswer(template, state, cites) { + let out = String(template); + // {a|b} alternation: resolve against the first numeric value + // placeholder in the template (> its "neutral" 1 -> first option). + const valPh = out.match(/\{[A-Za-z_][\w.]*\}/); + let firstNum = null; + if (valPh) { + const key = valPh[0].slice(1, -1); + if (typeof state[key] === "number") + firstNum = state[key]; + } + out = out.replace(/\{([^{}|]+)\|([^{}]+)\}/g, (match, a, b) => + (firstNum !== null && firstNum > 1) ? a : b); + // {citeN} / {cite} + out = out.replace(/\{cite(\d*)\}/g, (match, d) => { + const idx = d ? (parseInt(d, 10) - 1) : 0; + return cites[idx] !== undefined ? cites[idx] : (cites[0] || ""); + }); + // {dotted.path} value placeholders + out = out.replace(/\{([A-Za-z_][\w.]*)\}/g, (match, key) => + state[key] !== undefined ? _fmtVal(state[key]) : match); + return out; + } + + function explain(path) { + const t = toolsByPath[path] !== undefined ? toolsByPath[path] + : toolsByName[path] !== undefined ? toolsByName[path] : null; + if (!t) + return { ok: false, reason: `unknown setting ${path}` }; + const needed = [t.p]; + for (let i = 0; i < explainTable.length; i++) { + const rule = explainTable[i]; + if (rule.path !== t.p) + continue; + const paths = _pathsIn(rule.when); + for (let j = 0; j < paths.length; j++) + if (needed.indexOf(paths[j]) === -1) + needed.push(paths[j]); + } + const state = _liveState(needed); + for (let i = 0; i < explainTable.length; i++) { + const rule = explainTable[i]; + if (rule.path !== t.p) + continue; + if (_evalWhen(rule, state)) { + const answer = _renderAnswer(rule.answer, state, rule.cites); + return { ok: true, answer: answer, cites: rule.cites, rule: true }; + } + } + const value = readPath(t.p); + const cite = (t.c && t.c.length) ? t.c[0][0] : ""; + let validation; + if (t.k === "enum") validation = `one of ${(t.en || []).join("|")}`; + else if (t.k === "bool") validation = "on/off"; + else if (t.k === "string") validation = `string <= ${t.sl || 64} chars`; + else validation = `range ${t.lo}-${t.hi}`; + const shown = value === null ? t.d : value; + return { + ok: true, + answer: `The ${t.p} is currently set to ${_fmtVal(shown)} ` + + `(${validation}, default ${_fmtVal(t.d)}${cite ? `; ${cite}` : ""}).`, + cites: t.c || [], rule: false + }; + } + + // ---- presets (bundles of validated tool calls only) ---------------------- + + function presetList() { + return presetTable.map(p => ({ + name: p.name, label: p.label, description: p.description, + calls: p.calls.length + })); + } + + function requestPreset(name) { + const p = presetTable.find(x => x.name === name); + if (!p) + return { ok: false, reason: `unknown preset ${name}` }; + const calls = p.calls.map(c => ({ name: c[0], value: c[1] })); + // Presets are multi-op by construction -> always the confirm flow. + return request(calls, `preset: ${p.label}`); + } + + FileView { + id: historyFile + + printErrors: false + path: root.historyPath + onLoaded: { + try { + const data = JSON.parse(text()); + if (Array.isArray(data)) + root.history = data.slice(0, root.maxHistory); + } catch (e) { + root.history = []; + } + } + } +} diff --git a/plugins/caelestia-assistant/assistant/adapters/caelestia/tools.json b/plugins/caelestia-assistant/assistant/adapters/caelestia/tools.json new file mode 100644 index 0000000..e702214 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/adapters/caelestia/tools.json @@ -0,0 +1,8388 @@ +{ + "meta": { + "generator": "assistant.capabilities.settings.build_registry", + "repo_commit": "70ee7da115fde9012e28e393c73d274f55bd2dd7", + "notes": "Validation ranges/enums adopted exactly from the shipped Nexus controls (ui_ranges_data.py) and the C++ enum declarations; upstream declares no numeric bounds in the settings schema (type-only hook). not_exposed records every scalar leaf without a tool, with its reason.", + "tool_count": 272, + "group_counts": { + "bar": 58, + "dock": 5, + "appearance": 5, + "effects": 9, + "animations": 1, + "notifications": 13, + "launcher": 18, + "lockscreen": 14, + "wallpaper-scheme": 36, + "overview": 16, + "osd": 7, + "dashboard": 21, + "sidebar": 3, + "nexus": 1, + "border": 3, + "general": 8, + "services": 17, + "utilities": 27, + "audio": 10 + }, + "not_exposed_count": 339, + "excluded_by_rule": { + "ai-provider-selfconfig": 30, + "ai-credentials": 5, + "ai-endpoints": 7, + "ai-internal-state": 2, + "ai-executables": 2, + "no-shipped-control": 264, + "complex-control": 2, + "dynamic-enum": 4, + "master-switch": 1, + "kwinrc-companion-writes": 4, + "free-string": 1, + "filesystem-paths": 7, + "string-stepper": 2, + "session-commands": 4, + "session-icons": 4 + } + }, + "tools": [ + { + "name": "setBarDragThreshold", + "path": "bar.dragThreshold", + "group": "bar", + "kind": "int", + "default": 20, + "minimum": 0, + "maximum": 200, + "step": 5, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/barconfig.hpp:224", + "CONFIG declaration: int dragThreshold = 20" + ], + [ + "shell/modules/nexus/pages/panels/TaskbarPanel.qml:107", + "shipped Nexus control (StepperRow)" + ] + ] + }, + { + "name": "setBarPersistent", + "path": "bar.persistent", + "group": "bar", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [ + "bar|taskbar", + "persistent|always visible|auto.?hide" + ], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/barconfig.hpp:220", + "CONFIG declaration: bool persistent = true" + ], + [ + "shell/modules/nexus/pages/panels/TaskbarPanel.qml:67", + "shipped Nexus control (ToggleRow)" + ], + [ + "shell/modules/bar/BarWrapper.qml:27", + "persistent reader" + ] + ] + }, + { + "name": "setBarPosition", + "path": "bar.position", + "group": "bar", + "kind": "enum", + "default": "bottom", + "minimum": null, + "maximum": null, + "step": null, + "enum": [ + "top", + "bottom", + "left", + "right" + ], + "string_max_len": null, + "global_only": false, + "nouns": [ + "bar|taskbar|panel" + ], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/barconfig.hpp:225", + "CONFIG declaration: QString position = u\"bottom\"_s" + ], + [ + "shell/modules/nexus/pages/panels/TaskbarPanel.qml:91", + "shipped Nexus control (SelectRow)" + ], + [ + "shell/modules/bar/BarWrapper.qml:23", + "position-driven anchoring" + ] + ] + }, + { + "name": "setBarScale", + "path": "bar.scale", + "group": "bar", + "kind": "float", + "default": 1.0, + "minimum": 0.6, + "maximum": 1.6, + "step": 0.1, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [ + "bar|taskbar|panel" + ], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/barconfig.hpp:211", + "CONFIG declaration: qreal scale = 1.0" + ], + [ + "shell/modules/nexus/pages/panels/TaskbarPanel.qml:157", + "shipped Nexus control (StepperRow)" + ], + [ + "shell/modules/bar/BarWrapper.qml:24", + "contentWidth = innerWidth * barScale; floor 0.6" + ] + ] + }, + { + "name": "setBarShowOnHover", + "path": "bar.showOnHover", + "group": "bar", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/barconfig.hpp:223", + "CONFIG declaration: bool showOnHover = true" + ], + [ + "shell/modules/nexus/pages/panels/TaskbarPanel.qml:100", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setClockBackground", + "path": "bar.clock.background", + "group": "bar", + "kind": "bool", + "default": false, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/barconfig.hpp:139", + "CONFIG declaration: bool background = false" + ], + [ + "shell/modules/nexus/pages/panels/taskbar/BarClock.qml:19", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setClockShowDate", + "path": "bar.clock.showDate", + "group": "bar", + "kind": "bool", + "default": false, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/barconfig.hpp:140", + "CONFIG declaration: bool showDate = false" + ], + [ + "shell/modules/nexus/pages/panels/taskbar/BarClock.qml:26", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setClockShowIcon", + "path": "bar.clock.showIcon", + "group": "bar", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/barconfig.hpp:141", + "CONFIG declaration: bool showIcon = true" + ], + [ + "shell/modules/nexus/pages/panels/taskbar/BarClock.qml:32", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setClockShowSeconds", + "path": "bar.clock.showSeconds", + "group": "bar", + "kind": "bool", + "default": false, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/barconfig.hpp:143", + "CONFIG declaration: bool showSeconds = false" + ], + [ + "shell/modules/nexus/pages/panels/taskbar/BarClock.qml:38", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setDodgeFocusedOnly", + "path": "bar.dodgeFocusedOnly", + "group": "bar", + "kind": "bool", + "default": false, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/barconfig.hpp:222", + "CONFIG declaration: bool dodgeFocusedOnly = false" + ], + [ + "shell/modules/nexus/pages/panels/TaskbarPanel.qml:83", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setDodgeWindows", + "path": "bar.dodgeWindows", + "group": "bar", + "kind": "bool", + "default": false, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/barconfig.hpp:221", + "CONFIG declaration: bool dodgeWindows = false" + ], + [ + "shell/modules/nexus/pages/panels/TaskbarPanel.qml:75", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setFontScaleOffset", + "path": "bar.fontScaleOffset", + "group": "bar", + "kind": "float", + "default": 0.0, + "minimum": -1.0, + "maximum": 1.0, + "step": 0.05, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/barconfig.hpp:216", + "CONFIG declaration: qreal fontScaleOffset = 0.0" + ], + [ + "shell/modules/nexus/pages/panels/TaskbarPanel.qml:192", + "shipped Nexus control (StepperRow)" + ] + ] + }, + { + "name": "setGithubBackground", + "path": "bar.github.background", + "group": "bar", + "kind": "bool", + "default": false, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/barconfig.hpp:161", + "CONFIG declaration: bool background = false" + ], + [ + "shell/modules/nexus/pages/panels/taskbar/BarGithub.qml:99", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setGreeterAfternoonStart", + "path": "bar.greeter.afternoonStart", + "group": "bar", + "kind": "int", + "default": 12, + "minimum": 0, + "maximum": 23, + "step": 1, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/barconfig.hpp:83", + "CONFIG declaration: int afternoonStart = 12" + ], + [ + "shell/modules/nexus/pages/panels/taskbar/BarGreeter.qml:228", + "shipped Nexus control (StepperRow)" + ] + ] + }, + { + "name": "setGreeterCompact", + "path": "bar.greeter.compact", + "group": "bar", + "kind": "bool", + "default": false, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/barconfig.hpp:71", + "CONFIG declaration: bool compact = false" + ], + [ + "shell/modules/nexus/pages/panels/taskbar/BarGreeter.qml:97", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setGreeterEveningStart", + "path": "bar.greeter.eveningStart", + "group": "bar", + "kind": "int", + "default": 17, + "minimum": 0, + "maximum": 23, + "step": 1, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/barconfig.hpp:84", + "CONFIG declaration: int eveningStart = 17" + ], + [ + "shell/modules/nexus/pages/panels/taskbar/BarGreeter.qml:273", + "shipped Nexus control (StepperRow)" + ] + ] + }, + { + "name": "setGreeterInverted", + "path": "bar.greeter.inverted", + "group": "bar", + "kind": "bool", + "default": false, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/barconfig.hpp:72", + "CONFIG declaration: bool inverted = false" + ], + [ + "shell/modules/nexus/pages/panels/taskbar/BarGreeter.qml:107", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setGreeterMode", + "path": "bar.greeter.mode", + "group": "bar", + "kind": "enum", + "default": "timeOfDay", + "minimum": null, + "maximum": null, + "step": null, + "enum": [ + "timeOfDay", + "slideshow" + ], + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/barconfig.hpp:75", + "CONFIG declaration: QString mode = u\"timeOfDay\"_s" + ], + [ + "shell/modules/nexus/pages/panels/taskbar/BarGreeter.qml:141", + "shipped Nexus control (SelectRow)" + ] + ] + }, + { + "name": "setGreeterMorningStart", + "path": "bar.greeter.morningStart", + "group": "bar", + "kind": "int", + "default": 5, + "minimum": 0, + "maximum": 23, + "step": 1, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/barconfig.hpp:82", + "CONFIG declaration: int morningStart = 5" + ], + [ + "shell/modules/nexus/pages/panels/taskbar/BarGreeter.qml:183", + "shipped Nexus control (StepperRow)" + ] + ] + }, + { + "name": "setGreeterNightStart", + "path": "bar.greeter.nightStart", + "group": "bar", + "kind": "int", + "default": 20, + "minimum": 0, + "maximum": 23, + "step": 1, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/barconfig.hpp:85", + "CONFIG declaration: int nightStart = 20" + ], + [ + "shell/modules/nexus/pages/panels/taskbar/BarGreeter.qml:318", + "shipped Nexus control (StepperRow)" + ] + ] + }, + { + "name": "setGreeterShowOnHover", + "path": "bar.greeter.showOnHover", + "group": "bar", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/barconfig.hpp:73", + "CONFIG declaration: bool showOnHover = true" + ], + [ + "shell/modules/nexus/pages/panels/taskbar/BarGreeter.qml:116", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setGreeterSlideshowInterval", + "path": "bar.greeter.slideshowInterval", + "group": "bar", + "kind": "float", + "default": 60.0, + "minimum": 5, + "maximum": 3600, + "step": 5, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/barconfig.hpp:96", + "CONFIG declaration: qreal slideshowInterval = 60.0" + ], + [ + "shell/modules/nexus/pages/panels/taskbar/BarGreeter.qml:352", + "shipped Nexus control (StepperRow)" + ] + ] + }, + { + "name": "setGreeterSlideshowRandom", + "path": "bar.greeter.slideshowRandom", + "group": "bar", + "kind": "bool", + "default": false, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/barconfig.hpp:97", + "CONFIG declaration: bool slideshowRandom = false" + ], + [ + "shell/modules/nexus/pages/panels/taskbar/BarGreeter.qml:367", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setLivePreviews", + "path": "bar.livePreviews", + "group": "bar", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [ + "live previews|window previews|thumbnails|previews" + ], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/barconfig.hpp:217", + "CONFIG declaration: bool livePreviews = true" + ], + [ + "shell/modules/nexus/pages/panels/TaskbarPanel.qml:178", + "shipped Nexus control (ToggleRow)" + ], + [ + "shell/components/images/WindowPreview.qml:42", + "live reader" + ] + ] + }, + { + "name": "setPopoutsGreeter", + "path": "bar.popouts.greeter", + "group": "bar", + "kind": "bool", + "default": false, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/barconfig.hpp:27", + "CONFIG declaration: bool greeter = false" + ], + [ + "shell/modules/nexus/pages/panels/taskbar/BarGreeter.qml:126", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setPopoutsStatusIcons", + "path": "bar.popouts.statusIcons", + "group": "bar", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/barconfig.hpp:29", + "CONFIG declaration: bool statusIcons = true" + ], + [ + "shell/modules/nexus/pages/panels/taskbar/BarStatusIcons.qml:101", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setPopoutsTray", + "path": "bar.popouts.tray", + "group": "bar", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/barconfig.hpp:28", + "CONFIG declaration: bool tray = true" + ], + [ + "shell/modules/nexus/pages/panels/taskbar/BarTray.qml:39", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setPreviewScale", + "path": "bar.previewScale", + "group": "bar", + "kind": "float", + "default": 1.0, + "minimum": 0.5, + "maximum": 1.6, + "step": 0.05, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/barconfig.hpp:212", + "CONFIG declaration: qreal previewScale = 1.0" + ], + [ + "shell/modules/nexus/pages/panels/TaskbarPanel.qml:168", + "shipped Nexus control (StepperRow)" + ] + ] + }, + { + "name": "setPreviewScaleWithBar", + "path": "bar.previewScaleWithBar", + "group": "bar", + "kind": "bool", + "default": false, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/barconfig.hpp:213", + "CONFIG declaration: bool previewScaleWithBar = false" + ], + [ + "shell/modules/nexus/pages/panels/TaskbarPanel.qml:185", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setPreviewScalesAudio", + "path": "bar.previewScales.audio", + "group": "bar", + "kind": "float", + "default": 0.0, + "minimum": -1.0, + "maximum": 1.0, + "step": 0.05, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/barconfig.hpp:174", + "CONFIG declaration: qreal audio = 0.0" + ], + [ + "shell/modules/nexus/pages/panels/taskbar/BarPreviewScales.qml:100", + "shipped Nexus control (DoubleStepperRow)" + ] + ] + }, + { + "name": "setPreviewScalesBattery", + "path": "bar.previewScales.battery", + "group": "bar", + "kind": "float", + "default": 0.0, + "minimum": -1.0, + "maximum": 1.0, + "step": 0.05, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/barconfig.hpp:175", + "CONFIG declaration: qreal battery = 0.0" + ], + [ + "shell/modules/nexus/pages/panels/taskbar/BarPreviewScales.qml:113", + "shipped Nexus control (DoubleStepperRow)" + ] + ] + }, + { + "name": "setPreviewScalesBluetooth", + "path": "bar.previewScales.bluetooth", + "group": "bar", + "kind": "float", + "default": 0.0, + "minimum": -1.0, + "maximum": 1.0, + "step": 0.05, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/barconfig.hpp:176", + "CONFIG declaration: qreal bluetooth = 0.0" + ], + [ + "shell/modules/nexus/pages/panels/taskbar/BarPreviewScales.qml:126", + "shipped Nexus control (DoubleStepperRow)" + ] + ] + }, + { + "name": "setPreviewScalesDock", + "path": "bar.previewScales.dock", + "group": "bar", + "kind": "float", + "default": 0.0, + "minimum": -1.0, + "maximum": 1.0, + "step": 0.05, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/barconfig.hpp:178", + "CONFIG declaration: qreal dock = 0.0" + ], + [ + "shell/modules/nexus/pages/panels/taskbar/BarPreviewScales.qml:139", + "shipped Nexus control (DoubleStepperRow)" + ] + ] + }, + { + "name": "setPreviewScalesGithub", + "path": "bar.previewScales.github", + "group": "bar", + "kind": "float", + "default": 0.0, + "minimum": -1.0, + "maximum": 1.0, + "step": 0.05, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/barconfig.hpp:179", + "CONFIG declaration: qreal github = 0.0" + ], + [ + "shell/modules/nexus/pages/panels/taskbar/BarPreviewScales.qml:152", + "shipped Nexus control (DoubleStepperRow)" + ] + ] + }, + { + "name": "setPreviewScalesGreeter", + "path": "bar.previewScales.greeter", + "group": "bar", + "kind": "float", + "default": 0.0, + "minimum": -1.0, + "maximum": 1.0, + "step": 0.05, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/barconfig.hpp:173", + "CONFIG declaration: qreal greeter = 0.0" + ], + [ + "shell/modules/nexus/pages/panels/taskbar/BarPreviewScales.qml:81", + "shipped Nexus control (DoubleStepperRow)" + ] + ] + }, + { + "name": "setPreviewScalesLockStatus", + "path": "bar.previewScales.lockStatus", + "group": "bar", + "kind": "float", + "default": 0.0, + "minimum": -1.0, + "maximum": 1.0, + "step": 0.05, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/barconfig.hpp:181", + "CONFIG declaration: qreal lockStatus = 0.0" + ], + [ + "shell/modules/nexus/pages/panels/taskbar/BarPreviewScales.qml:165", + "shipped Nexus control (DoubleStepperRow)" + ] + ] + }, + { + "name": "setPreviewScalesNetwork", + "path": "bar.previewScales.network", + "group": "bar", + "kind": "float", + "default": 0.0, + "minimum": -1.0, + "maximum": 1.0, + "step": 0.05, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/barconfig.hpp:182", + "CONFIG declaration: qreal network = 0.0" + ], + [ + "shell/modules/nexus/pages/panels/taskbar/BarPreviewScales.qml:178", + "shipped Nexus control (DoubleStepperRow)" + ] + ] + }, + { + "name": "setPreviewScalesNotifications", + "path": "bar.previewScales.notifications", + "group": "bar", + "kind": "float", + "default": 0.0, + "minimum": -1.0, + "maximum": 1.0, + "step": 0.05, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/barconfig.hpp:183", + "CONFIG declaration: qreal notifications = 0.0" + ], + [ + "shell/modules/nexus/pages/panels/taskbar/BarPreviewScales.qml:191", + "shipped Nexus control (DoubleStepperRow)" + ] + ] + }, + { + "name": "setPreviewScalesPeripheralBattery", + "path": "bar.previewScales.peripheralBattery", + "group": "bar", + "kind": "float", + "default": 0.0, + "minimum": -1.0, + "maximum": 1.0, + "step": 0.05, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/barconfig.hpp:184", + "CONFIG declaration: qreal peripheralBattery = 0.0" + ], + [ + "shell/modules/nexus/pages/panels/taskbar/BarPreviewScales.qml:204", + "shipped Nexus control (DoubleStepperRow)" + ] + ] + }, + { + "name": "setPreviewScalesTrayMenu", + "path": "bar.previewScales.trayMenu", + "group": "bar", + "kind": "float", + "default": 0.0, + "minimum": -1.0, + "maximum": 1.0, + "step": 0.05, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/barconfig.hpp:185", + "CONFIG declaration: qreal trayMenu = 0.0" + ], + [ + "shell/modules/nexus/pages/panels/taskbar/BarPreviewScales.qml:217", + "shipped Nexus control (DoubleStepperRow)" + ] + ] + }, + { + "name": "setPreviewScalesWirelessPassword", + "path": "bar.previewScales.wirelessPassword", + "group": "bar", + "kind": "float", + "default": 0.0, + "minimum": -1.0, + "maximum": 1.0, + "step": 0.05, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/barconfig.hpp:186", + "CONFIG declaration: qreal wirelessPassword = 0.0" + ], + [ + "shell/modules/nexus/pages/panels/taskbar/BarPreviewScales.qml:230", + "shipped Nexus control (DoubleStepperRow)" + ] + ] + }, + { + "name": "setScrollActionsBrightness", + "path": "bar.scrollActions.brightness", + "group": "bar", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/barconfig.hpp:21", + "CONFIG declaration: bool brightness = true" + ], + [ + "shell/modules/nexus/pages/panels/TaskbarPanel.qml:249", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setScrollActionsVolume", + "path": "bar.scrollActions.volume", + "group": "bar", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/barconfig.hpp:20", + "CONFIG declaration: bool volume = true" + ], + [ + "shell/modules/nexus/pages/panels/TaskbarPanel.qml:242", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setScrollActionsWorkspaces", + "path": "bar.scrollActions.workspaces", + "group": "bar", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/barconfig.hpp:19", + "CONFIG declaration: bool workspaces = true" + ], + [ + "shell/modules/nexus/pages/panels/TaskbarPanel.qml:234", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setStatusShowWifi", + "path": "bar.status.showWifi", + "group": "bar", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/barconfig.hpp:126", + "CONFIG declaration: bool showWifi = true" + ], + [ + "shell/modules/nexus/pages/panels/taskbar/BarStatusIcons.qml:88", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setTrayBackground", + "path": "bar.tray.background", + "group": "bar", + "kind": "bool", + "default": false, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/barconfig.hpp:112", + "CONFIG declaration: bool background = false" + ], + [ + "shell/modules/nexus/pages/panels/taskbar/BarTray.qml:20", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setTrayCompact", + "path": "bar.tray.compact", + "group": "bar", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/barconfig.hpp:114", + "CONFIG declaration: bool compact = true" + ], + [ + "shell/modules/nexus/pages/panels/taskbar/BarTray.qml:33", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setTrayRecolour", + "path": "bar.tray.recolour", + "group": "bar", + "kind": "bool", + "default": false, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/barconfig.hpp:113", + "CONFIG declaration: bool recolour = false" + ], + [ + "shell/modules/nexus/pages/panels/taskbar/BarTray.qml:27", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setWorkspacesActiveIndicator", + "path": "bar.workspaces.activeIndicator", + "group": "bar", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/barconfig.hpp:37", + "CONFIG declaration: bool activeIndicator = true" + ], + [ + "shell/modules/nexus/pages/panels/taskbar/BarWorkspaces.qml:77", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setWorkspacesActiveTrail", + "path": "bar.workspaces.activeTrail", + "group": "bar", + "kind": "bool", + "default": false, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/barconfig.hpp:43", + "CONFIG declaration: bool activeTrail = false" + ], + [ + "shell/modules/nexus/pages/panels/taskbar/BarWorkspaces.qml:83", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setWorkspacesDisplayType", + "path": "bar.workspaces.displayType", + "group": "bar", + "kind": "enum", + "default": "Shapes", + "minimum": null, + "maximum": null, + "step": null, + "enum": [ + "Shapes", + "Text" + ], + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/barconfig.hpp:49", + "CONFIG declaration: caelestia::config::BarWorkspaceDisplay::Enum displayType = BarWorkspaceDisplay::Shapes" + ], + [ + "shell/modules/nexus/pages/panels/taskbar/BarWorkspaces.qml:95", + "shipped Nexus control (SelectRow)" + ] + ] + }, + { + "name": "setWorkspacesMaxWindowIcons", + "path": "bar.workspaces.maxWindowIcons", + "group": "bar", + "kind": "int", + "default": 5, + "minimum": 0, + "maximum": 20, + "step": 1, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/barconfig.hpp:42", + "CONFIG declaration: int maxWindowIcons = 5" + ], + [ + "shell/modules/nexus/pages/panels/taskbar/BarWorkspaces.qml:126", + "shipped Nexus control (StepperRow)" + ] + ] + }, + { + "name": "setWorkspacesOccupiedBg", + "path": "bar.workspaces.occupiedBg", + "group": "bar", + "kind": "bool", + "default": false, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/barconfig.hpp:38", + "CONFIG declaration: bool occupiedBg = false" + ], + [ + "shell/modules/nexus/pages/panels/taskbar/BarWorkspaces.qml:89", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setWorkspacesPerMonitor", + "path": "bar.workspaces.perMonitor", + "group": "bar", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/barconfig.hpp:45", + "CONFIG declaration: bool perMonitor = true" + ], + [ + "shell/modules/nexus/pages/panels/taskbar/BarWorkspaces.qml:137", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setWorkspacesShowUnoccupied", + "path": "bar.workspaces.showUnoccupied", + "group": "bar", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/barconfig.hpp:39", + "CONFIG declaration: bool showUnoccupied = true" + ], + [ + "shell/modules/nexus/pages/panels/taskbar/BarWorkspaces.qml:112", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setWorkspacesShowWindows", + "path": "bar.workspaces.showWindows", + "group": "bar", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/barconfig.hpp:40", + "CONFIG declaration: bool showWindows = true" + ], + [ + "shell/modules/nexus/pages/panels/taskbar/BarWorkspaces.qml:104", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setWorkspacesShowWindowsOnSpecialWorkspaces", + "path": "bar.workspaces.showWindowsOnSpecialWorkspaces", + "group": "bar", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/barconfig.hpp:41", + "CONFIG declaration: bool showWindowsOnSpecialWorkspaces = true" + ], + [ + "shell/modules/nexus/pages/panels/taskbar/BarWorkspaces.qml:120", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setWorkspacesShown", + "path": "bar.workspaces.shown", + "group": "bar", + "kind": "int", + "default": 5, + "minimum": 1, + "maximum": 20, + "step": 1, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/barconfig.hpp:36", + "CONFIG declaration: int shown = 5" + ], + [ + "shell/modules/nexus/pages/panels/taskbar/BarWorkspaces.qml:53", + "shipped Nexus control (StepperRow)" + ] + ] + }, + { + "name": "setDockBadges", + "path": "bar.dock.showBadges", + "group": "dock", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [ + "app badges|badges|badge" + ], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/barconfig.hpp:151", + "CONFIG declaration: bool showBadges = true" + ], + [ + "shell/modules/nexus/pages/panels/taskbar/BarDock.qml:75", + "shipped Nexus control (ToggleRow)" + ], + [ + "shell/modules/bar/components/Dock.qml:630", + "badge over LauncherEntry.forApp, ?? true" + ] + ] + }, + { + "name": "setDockCurrentDesktopOnly", + "path": "bar.dock.currentDesktopOnly", + "group": "dock", + "kind": "bool", + "default": false, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/barconfig.hpp:153", + "CONFIG declaration: bool currentDesktopOnly = false" + ], + [ + "shell/modules/nexus/pages/panels/taskbar/BarDock.qml:83", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setDockIconSize", + "path": "bar.dock.iconSize", + "group": "dock", + "kind": "int", + "default": 32, + "minimum": 16, + "maximum": 96, + "step": 4, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [ + "dock icons|taskbar dock|dock" + ], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/barconfig.hpp:152", + "CONFIG declaration: int iconSize = 32" + ], + [ + "shell/modules/nexus/pages/panels/taskbar/BarDock.qml:54", + "shipped Nexus control (StepperRow)" + ], + [ + "shell/modules/bar/components/Dock.qml:38", + "QML floor 16" + ] + ] + }, + { + "name": "setDockPreviewOnDesktop", + "path": "bar.dock.previewOnDesktop", + "group": "dock", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/barconfig.hpp:154", + "CONFIG declaration: bool previewOnDesktop = true" + ], + [ + "shell/modules/nexus/pages/panels/taskbar/BarDock.qml:91", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setDockRecolourIcons", + "path": "bar.dock.recolourIcons", + "group": "dock", + "kind": "bool", + "default": false, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/barconfig.hpp:150", + "CONFIG declaration: bool recolourIcons = false" + ], + [ + "shell/modules/nexus/pages/panels/taskbar/BarDock.qml:67", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setDeformScale", + "path": "appearance.deformScale", + "group": "appearance", + "kind": "float", + "default": 1.0, + "minimum": 0, + "maximum": 1.5, + "step": 0.05, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/appearanceconfig.hpp:314", + "CONFIG declaration: qreal deformScale = 1" + ], + [ + "shell/modules/nexus/pages/wallandstyle/AppearancePage.qml:357", + "shipped Nexus control (StepperRow)" + ] + ] + }, + { + "name": "setFontScale", + "path": "appearance.font.scale", + "group": "appearance", + "kind": "float", + "default": 1.0, + "minimum": 0.5, + "maximum": 2.0, + "step": 0.1, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [ + "font size|text size|fonts|font|text" + ], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/appearanceconfig.hpp:249", + "CONFIG declaration: qreal scale = 1" + ], + [ + "shell/modules/nexus/pages/wallandstyle/AppearancePage.qml:285", + "shipped Nexus control (StepperRow)" + ] + ] + }, + { + "name": "setPaddingScale", + "path": "appearance.padding.scale", + "group": "appearance", + "kind": "float", + "default": 1.0, + "minimum": 0.5, + "maximum": 2.0, + "step": 0.1, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [ + "padding|insets" + ], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/appearanceconfig.hpp:90", + "CONFIG declaration: qreal scale = 1" + ], + [ + "shell/modules/nexus/pages/wallandstyle/AppearancePage.qml:306", + "shipped Nexus control (StepperRow)" + ] + ] + }, + { + "name": "setRoundingScale", + "path": "appearance.rounding.scale", + "group": "appearance", + "kind": "float", + "default": 1.0, + "minimum": 0.5, + "maximum": 2.0, + "step": 0.1, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [ + "corner rounding|corner radius|rounding|corners" + ], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/appearanceconfig.hpp:22", + "CONFIG declaration: qreal scale = 1" + ], + [ + "shell/modules/nexus/pages/wallandstyle/AppearancePage.qml:118", + "shipped Nexus control (StepperRow)" + ] + ] + }, + { + "name": "setSpacingScale", + "path": "appearance.spacing.scale", + "group": "appearance", + "kind": "float", + "default": 1.0, + "minimum": 0.5, + "maximum": 2.0, + "step": 0.1, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [ + "gaps|spacing|gap" + ], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/appearanceconfig.hpp:57", + "CONFIG declaration: qreal scale = 1" + ], + [ + "shell/modules/nexus/pages/wallandstyle/AppearancePage.qml:296", + "shipped Nexus control (StepperRow)" + ] + ] + }, + { + "name": "setAmbientColor", + "path": "appearance.ambientColor", + "group": "effects", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": true, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/appearanceconfig.hpp:326", + "CONFIG declaration: bool ambientColor = true" + ], + [ + "shell/modules/nexus/pages/wallandstyle/AppearancePage.qml:158", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setAmbientOpacity", + "path": "appearance.ambientOpacity", + "group": "effects", + "kind": "float", + "default": 0.45, + "minimum": 0, + "maximum": 1, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": true, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/appearanceconfig.hpp:327", + "CONFIG declaration: qreal ambientOpacity = 0.45" + ], + [ + "shell/modules/nexus/pages/wallandstyle/AppearancePage.qml:167", + "shipped Nexus control (SliderRow)" + ] + ] + }, + { + "name": "setBlurEnabled", + "path": "appearance.blur", + "group": "effects", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": true, + "nouns": [ + "background blur|frosted glass|blur" + ], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/appearanceconfig.hpp:324", + "CONFIG declaration: bool blur = true" + ], + [ + "shell/modules/nexus/pages/wallandstyle/AppearancePage.qml:222", + "shipped Nexus control (ToggleRow)" + ], + [ + "shell/modules/drawers/blur/BlurOffsets.qml:17", + "isActive = transparency.enabled && blur" + ] + ] + }, + { + "name": "setBlurMask", + "path": "appearance.blurMask", + "group": "effects", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": true, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/appearanceconfig.hpp:325", + "CONFIG declaration: bool blurMask = true" + ], + [ + "shell/modules/nexus/pages/wallandstyle/AppearancePage.qml:246", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setIslands", + "path": "appearance.islands", + "group": "effects", + "kind": "bool", + "default": false, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": true, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/appearanceconfig.hpp:323", + "CONFIG declaration: bool islands = false" + ], + [ + "shell/modules/nexus/pages/wallandstyle/AppearancePage.qml:100", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setPitchBlack", + "path": "appearance.pitchBlack", + "group": "effects", + "kind": "bool", + "default": false, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": true, + "nouns": [ + "pitch black|bezel mode|bezel" + ], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/appearanceconfig.hpp:322", + "CONFIG declaration: bool pitchBlack = false" + ], + [ + "shell/modules/nexus/pages/wallandstyle/AppearancePage.qml:92", + "shipped Nexus control (ToggleRow)" + ], + [ + "shell/modules/drawers/ContentWindow.qml:394", + "#000000 surface when pitchBlack" + ] + ] + }, + { + "name": "setTransparencyBase", + "path": "appearance.transparency.base", + "group": "effects", + "kind": "float", + "default": 0.85, + "minimum": 0.0, + "maximum": 1.0, + "step": 0.05, + "enum": null, + "string_max_len": null, + "global_only": true, + "nouns": [ + "base opacity|transparency|opacity" + ], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/appearanceconfig.hpp:307", + "CONFIG declaration: qreal base = 0.85" + ], + [ + "shell/modules/nexus/pages/wallandstyle/AppearancePage.qml:141", + "shipped Nexus control (SliderRow)" + ], + [ + "shell/modules/drawers/ContentWindow.qml:383", + "surface opacity reader" + ] + ] + }, + { + "name": "setTransparencyEnabled", + "path": "appearance.transparency.enabled", + "group": "effects", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": true, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/appearanceconfig.hpp:306", + "CONFIG declaration: bool enabled = true" + ], + [ + "shell/modules/nexus/pages/wallandstyle/AppearancePage.qml:128", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setTransparencyLayers", + "path": "appearance.transparency.layers", + "group": "effects", + "kind": "float", + "default": 0.4, + "minimum": 0, + "maximum": 1, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": true, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/appearanceconfig.hpp:308", + "CONFIG declaration: qreal layers = 0.4" + ], + [ + "shell/modules/nexus/pages/wallandstyle/AppearancePage.qml:149", + "shipped Nexus control (SliderRow)" + ] + ] + }, + { + "name": "setAnimationSpeed", + "path": "appearance.anim.durations.scale", + "group": "animations", + "kind": "float", + "default": 1.0, + "minimum": 0.25, + "maximum": 4.0, + "step": 0.25, + "enum": null, + "string_max_len": null, + "global_only": true, + "nouns": [ + "animation speed|animations?|transitions|motion|effects speed" + ], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/appearanceconfig.hpp:263", + "CONFIG declaration: qreal scale = 1" + ], + [ + "shell/modules/nexus/pages/wallandstyle/AppearancePage.qml:316", + "shipped Nexus control (StepperRow)" + ], + [ + "shell/plugin/src/Caelestia/Config/appearanceconfig.cpp:207", + "durations multiplied by scale" + ] + ] + }, + { + "name": "setActionOnClick", + "path": "notifs.actionOnClick", + "group": "notifications", + "kind": "bool", + "default": false, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": true, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/notifsconfig.hpp:20", + "CONFIG declaration: bool actionOnClick = false" + ], + [ + "shell/modules/nexus/pages/services/NotificationPreferencesPage.qml:162", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setClearThreshold", + "path": "notifs.clearThreshold", + "group": "notifications", + "kind": "float", + "default": 0.3, + "minimum": 0, + "maximum": 1, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/notifsconfig.hpp:18", + "CONFIG declaration: qreal clearThreshold = 0.3" + ], + [ + "shell/modules/nexus/pages/services/NotificationPreferencesPage.qml:190", + "shipped Nexus control (SliderRow)" + ] + ] + }, + { + "name": "setDefaultExpireTimeout", + "path": "notifs.defaultExpireTimeout", + "group": "notifications", + "kind": "int", + "default": 5000, + "minimum": 1000, + "maximum": 60000, + "step": 1000, + "enum": null, + "string_max_len": null, + "global_only": true, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/notifsconfig.hpp:16", + "CONFIG declaration: int defaultExpireTimeout = 5000" + ], + [ + "shell/modules/nexus/pages/services/NotificationPreferencesPage.qml:117", + "shipped Nexus control (StepperRow)" + ], + [ + "shell/modules/nexus/pages/services/NotificationPreferencesPage.qml:120", + "stepper displays seconds (value: x/1000; onMoved: Math.round(v*1000)); stored unit is ms — range converted x1000" + ] + ] + }, + { + "name": "setExpandThreshold", + "path": "notifs.expandThreshold", + "group": "notifications", + "kind": "int", + "default": 20, + "minimum": 5, + "maximum": 100, + "step": 5, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/notifsconfig.hpp:19", + "CONFIG declaration: int expandThreshold = 20" + ], + [ + "shell/modules/nexus/pages/services/NotificationPreferencesPage.qml:170", + "shipped Nexus control (StepperRow)" + ] + ] + }, + { + "name": "setExpire", + "path": "notifs.expire", + "group": "notifications", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": true, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/notifsconfig.hpp:13", + "CONFIG declaration: bool expire = true" + ], + [ + "shell/modules/nexus/pages/services/NotificationPreferencesPage.qml:103", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setFullscreen", + "path": "notifs.fullscreen", + "group": "notifications", + "kind": "enum", + "default": "off", + "minimum": null, + "maximum": null, + "step": null, + "enum": [ + "off", + "on" + ], + "string_max_len": null, + "global_only": true, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/notifsconfig.hpp:14", + "CONFIG declaration: QString fullscreen = QStringLiteral(\"off\")" + ], + [ + "shell/modules/nexus/pages/services/NotificationPreferencesPage.qml:78", + "shipped Nexus control (SelectRow)" + ] + ] + }, + { + "name": "setFullscreenExpireTimeout", + "path": "notifs.fullscreenExpireTimeout", + "group": "notifications", + "kind": "int", + "default": 2000, + "minimum": 1000, + "maximum": 30000, + "step": 1000, + "enum": null, + "string_max_len": null, + "global_only": true, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/notifsconfig.hpp:17", + "CONFIG declaration: int fullscreenExpireTimeout = 2000" + ], + [ + "shell/modules/nexus/pages/services/NotificationPreferencesPage.qml:180", + "shipped Nexus control (StepperRow)" + ], + [ + "shell/modules/nexus/pages/services/NotificationPreferencesPage.qml:183", + "stepper displays seconds (value: x/1000; onMoved: Math.round(value*1000)); stored unit is ms — range converted x1000" + ] + ] + }, + { + "name": "setGroupPreviewNum", + "path": "notifs.groupPreviewNum", + "group": "notifications", + "kind": "int", + "default": 3, + "minimum": 1, + "maximum": 10, + "step": 1, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/notifsconfig.hpp:21", + "CONFIG declaration: int groupPreviewNum = 3" + ], + [ + "shell/modules/nexus/pages/services/NotificationPreferencesPage.qml:127", + "shipped Nexus control (StepperRow)" + ] + ] + }, + { + "name": "setMonitor", + "path": "notifs.monitor", + "group": "notifications", + "kind": "enum", + "default": "all", + "minimum": null, + "maximum": null, + "step": null, + "enum": [ + "all", + "focused" + ], + "string_max_len": null, + "global_only": true, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/notifsconfig.hpp:15", + "CONFIG declaration: QString monitor = QStringLiteral(\"all\")" + ], + [ + "shell/modules/nexus/pages/services/NotificationPreferencesPage.qml:87", + "shipped Nexus control (SelectRow)" + ] + ] + }, + { + "name": "setNotifsMaxNotifs", + "path": "notifs.maxNotifs", + "group": "notifications", + "kind": "int", + "default": 50, + "minimum": 20, + "maximum": 2000, + "step": 50, + "enum": null, + "string_max_len": null, + "global_only": true, + "nouns": [ + "stored notifications|max stored notifications" + ], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/notifsconfig.hpp:25", + "CONFIG declaration: int maxNotifs = 50" + ], + [ + "shell/modules/nexus/pages/services/NotificationPreferencesPage.qml:147", + "shipped Nexus control (StepperRow)" + ] + ] + }, + { + "name": "setNotifsMaxPopups", + "path": "notifs.maxPopups", + "group": "notifications", + "kind": "int", + "default": 8, + "minimum": 0, + "maximum": 30, + "step": 1, + "enum": null, + "string_max_len": null, + "global_only": true, + "nouns": [ + "notification popups|popup notifications" + ], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/notifsconfig.hpp:24", + "CONFIG declaration: int maxPopups = 8" + ], + [ + "shell/modules/nexus/pages/services/NotificationPreferencesPage.qml:137", + "shipped Nexus control (StepperRow)" + ] + ] + }, + { + "name": "setOpenExpanded", + "path": "notifs.openExpanded", + "group": "notifications", + "kind": "bool", + "default": false, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/notifsconfig.hpp:22", + "CONFIG declaration: bool openExpanded = false" + ], + [ + "shell/modules/nexus/pages/services/NotificationPreferencesPage.qml:110", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setPosition", + "path": "notifs.position", + "group": "notifications", + "kind": "enum", + "default": "auto", + "minimum": null, + "maximum": null, + "step": null, + "enum": [ + "auto", + "top-left", + "top-center", + "top-right", + "bottom-left", + "bottom-center", + "bottom-right" + ], + "string_max_len": null, + "global_only": true, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/notifsconfig.hpp:23", + "CONFIG declaration: QString position = QStringLiteral(\"auto\")" + ], + [ + "shell/modules/nexus/pages/services/NotificationPreferencesPage.qml:95", + "shipped Nexus control (SelectRow)" + ] + ] + }, + { + "name": "setClipboardMaxEntries", + "path": "launcher.clipboardMaxEntries", + "group": "launcher", + "kind": "int", + "default": 20, + "minimum": 1, + "maximum": 100, + "step": 1, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/launcherconfig.hpp:46", + "CONFIG declaration: int clipboardMaxEntries = 20" + ], + [ + "shell/modules/nexus/pages/panels/LauncherPanel.qml:193", + "shipped Nexus control (StepperRow)" + ] + ] + }, + { + "name": "setConfirmClearClipboard", + "path": "launcher.confirmClearClipboard", + "group": "launcher", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": true, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/launcherconfig.hpp:56", + "CONFIG declaration: bool confirmClearClipboard = true" + ], + [ + "shell/modules/nexus/pages/panels/LauncherPanel.qml:204", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setEnableDangerousActions", + "path": "launcher.enableDangerousActions", + "group": "launcher", + "kind": "bool", + "default": false, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": true, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/launcherconfig.hpp:49", + "CONFIG declaration: bool enableDangerousActions = false" + ], + [ + "shell/modules/nexus/pages/panels/LauncherPanel.qml:225", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setLauncherDragThreshold", + "path": "launcher.dragThreshold", + "group": "launcher", + "kind": "int", + "default": 50, + "minimum": 0, + "maximum": 200, + "step": 5, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/launcherconfig.hpp:50", + "CONFIG declaration: int dragThreshold = 50" + ], + [ + "shell/modules/nexus/pages/panels/LauncherPanel.qml:177", + "shipped Nexus control (StepperRow)" + ] + ] + }, + { + "name": "setLauncherEnabled", + "path": "launcher.enabled", + "group": "launcher", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/launcherconfig.hpp:42", + "CONFIG declaration: bool enabled = true" + ], + [ + "shell/modules/nexus/pages/panels/LauncherPanel.qml:30", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setLauncherHoverThickness", + "path": "launcher.hoverThickness", + "group": "launcher", + "kind": "int", + "default": 10, + "minimum": 1, + "maximum": 100, + "step": 1, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/launcherconfig.hpp:53", + "CONFIG declaration: int hoverThickness = 10" + ], + [ + "shell/modules/nexus/pages/panels/LauncherPanel.qml:157", + "shipped Nexus control (StepperRow)" + ] + ] + }, + { + "name": "setLauncherHoverWidth", + "path": "launcher.hoverWidth", + "group": "launcher", + "kind": "int", + "default": 50, + "minimum": 10, + "maximum": 100, + "step": 5, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/launcherconfig.hpp:54", + "CONFIG declaration: int hoverWidth = 50" + ], + [ + "shell/modules/nexus/pages/panels/LauncherPanel.qml:167", + "shipped Nexus control (StepperRow)" + ] + ] + }, + { + "name": "setLauncherMaxShown", + "path": "launcher.maxShown", + "group": "launcher", + "kind": "int", + "default": 7, + "minimum": 1, + "maximum": 20, + "step": 1, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [ + "launcher results|search results|launcher" + ], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/launcherconfig.hpp:44", + "CONFIG declaration: int maxShown = 7" + ], + [ + "shell/modules/nexus/pages/panels/LauncherPanel.qml:139", + "shipped Nexus control (StepperRow)" + ] + ] + }, + { + "name": "setLauncherShowOnHover", + "path": "launcher.showOnHover", + "group": "launcher", + "kind": "bool", + "default": false, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/launcherconfig.hpp:43", + "CONFIG declaration: bool showOnHover = false" + ], + [ + "shell/modules/nexus/pages/panels/LauncherPanel.qml:111", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setLauncherVimKeybinds", + "path": "launcher.vimKeybinds", + "group": "launcher", + "kind": "bool", + "default": false, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": true, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/launcherconfig.hpp:55", + "CONFIG declaration: bool vimKeybinds = false" + ], + [ + "shell/modules/nexus/pages/panels/LauncherPanel.qml:217", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setMaxWallpapers", + "path": "launcher.maxWallpapers", + "group": "launcher", + "kind": "int", + "default": 9, + "minimum": 1, + "maximum": 30, + "step": 1, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/launcherconfig.hpp:45", + "CONFIG declaration: int maxWallpapers = 9" + ], + [ + "shell/modules/nexus/pages/panels/LauncherPanel.qml:148", + "shipped Nexus control (StepperRow)" + ] + ] + }, + { + "name": "setShowBrowseOnEmpty", + "path": "launcher.showBrowseOnEmpty", + "group": "launcher", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/launcherconfig.hpp:52", + "CONFIG declaration: bool showBrowseOnEmpty = true" + ], + [ + "shell/modules/nexus/pages/panels/LauncherPanel.qml:124", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setShowPowerMenu", + "path": "launcher.showPowerMenu", + "group": "launcher", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/launcherconfig.hpp:51", + "CONFIG declaration: bool showPowerMenu = true" + ], + [ + "shell/modules/nexus/pages/panels/LauncherPanel.qml:132", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setUseFuzzyActions", + "path": "launcher.useFuzzy.actions", + "group": "launcher", + "kind": "bool", + "default": false, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": true, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/launcherconfig.hpp:19", + "CONFIG declaration: bool actions = false" + ], + [ + "shell/modules/nexus/pages/panels/LauncherPanel.qml:245", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setUseFuzzyApps", + "path": "launcher.useFuzzy.apps", + "group": "launcher", + "kind": "bool", + "default": false, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": true, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/launcherconfig.hpp:18", + "CONFIG declaration: bool apps = false" + ], + [ + "shell/modules/nexus/pages/panels/LauncherPanel.qml:238", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setUseFuzzySchemes", + "path": "launcher.useFuzzy.schemes", + "group": "launcher", + "kind": "bool", + "default": false, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": true, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/launcherconfig.hpp:20", + "CONFIG declaration: bool schemes = false" + ], + [ + "shell/modules/nexus/pages/panels/LauncherPanel.qml:251", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setUseFuzzyVariants", + "path": "launcher.useFuzzy.variants", + "group": "launcher", + "kind": "bool", + "default": false, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": true, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/launcherconfig.hpp:21", + "CONFIG declaration: bool variants = false" + ], + [ + "shell/modules/nexus/pages/panels/LauncherPanel.qml:257", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setUseFuzzyWallpapers", + "path": "launcher.useFuzzy.wallpapers", + "group": "launcher", + "kind": "bool", + "default": false, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": true, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/launcherconfig.hpp:22", + "CONFIG declaration: bool wallpapers = false" + ], + [ + "shell/modules/nexus/pages/panels/LauncherPanel.qml:263", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setBlurWallpaper", + "path": "lock.blurWallpaper", + "group": "lockscreen", + "kind": "bool", + "default": false, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": true, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/lockconfig.hpp:22", + "CONFIG declaration: bool blurWallpaper = false" + ], + [ + "shell/modules/nexus/pages/wallandstyle/LockScreenPage.qml:184", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setEnableFprint", + "path": "lock.enableFprint", + "group": "lockscreen", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": true, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/lockconfig.hpp:12", + "CONFIG declaration: bool enableFprint = true" + ], + [ + "shell/modules/nexus/pages/wallandstyle/LockScreenPage.qml:201", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setHideNotifs", + "path": "lock.hideNotifs", + "group": "lockscreen", + "kind": "bool", + "default": false, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/lockconfig.hpp:19", + "CONFIG declaration: bool hideNotifs = false" + ], + [ + "shell/modules/nexus/pages/wallandstyle/LockScreenPage.qml:280", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setLockOnStartup", + "path": "lock.lockOnStartup", + "group": "lockscreen", + "kind": "bool", + "default": false, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": true, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/lockconfig.hpp:20", + "CONFIG declaration: bool lockOnStartup = false" + ], + [ + "shell/modules/nexus/pages/wallandstyle/LockScreenPage.qml:269", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setMaxFprintTries", + "path": "lock.maxFprintTries", + "group": "lockscreen", + "kind": "int", + "default": 3, + "minimum": 1, + "maximum": 5, + "step": 1, + "enum": null, + "string_max_len": null, + "global_only": true, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/lockconfig.hpp:13", + "CONFIG declaration: int maxFprintTries = 3" + ], + [ + "shell/modules/nexus/pages/wallandstyle/LockScreenPage.qml:213", + "shipped Nexus control (SelectRow)" + ] + ] + }, + { + "name": "setRecolourLogo", + "path": "lock.recolourLogo", + "group": "lockscreen", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/lockconfig.hpp:11", + "CONFIG declaration: bool recolourLogo = true" + ], + [ + "shell/modules/nexus/pages/wallandstyle/LockScreenPage.qml:291", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setRotateProfilePic", + "path": "lock.rotateProfilePic", + "group": "lockscreen", + "kind": "bool", + "default": false, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": true, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/lockconfig.hpp:18", + "CONFIG declaration: bool rotateProfilePic = false" + ], + [ + "shell/modules/nexus/pages/wallandstyle/LockScreenPage.qml:258", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setShowHibernate", + "path": "lock.showHibernate", + "group": "lockscreen", + "kind": "bool", + "default": false, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": true, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/lockconfig.hpp:24", + "CONFIG declaration: bool showHibernate = false" + ], + [ + "shell/modules/nexus/pages/wallandstyle/LockScreenPage.qml:320", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setShowLogout", + "path": "lock.showLogout", + "group": "lockscreen", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": true, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/lockconfig.hpp:26", + "CONFIG declaration: bool showLogout = true" + ], + [ + "shell/modules/nexus/pages/wallandstyle/LockScreenPage.qml:342", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setShowReboot", + "path": "lock.showReboot", + "group": "lockscreen", + "kind": "bool", + "default": false, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": true, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/lockconfig.hpp:27", + "CONFIG declaration: bool showReboot = false" + ], + [ + "shell/modules/nexus/pages/wallandstyle/LockScreenPage.qml:353", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setShowShutdown", + "path": "lock.showShutdown", + "group": "lockscreen", + "kind": "bool", + "default": false, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": true, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/lockconfig.hpp:28", + "CONFIG declaration: bool showShutdown = false" + ], + [ + "shell/modules/nexus/pages/wallandstyle/LockScreenPage.qml:364", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setShowSleep", + "path": "lock.showSleep", + "group": "lockscreen", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": true, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/lockconfig.hpp:23", + "CONFIG declaration: bool showSleep = true" + ], + [ + "shell/modules/nexus/pages/wallandstyle/LockScreenPage.qml:308", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setShowSwitchUser", + "path": "lock.showSwitchUser", + "group": "lockscreen", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": true, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/lockconfig.hpp:25", + "CONFIG declaration: bool showSwitchUser = true" + ], + [ + "shell/modules/nexus/pages/wallandstyle/LockScreenPage.qml:331", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setSyncWallpaper", + "path": "lock.syncWallpaper", + "group": "lockscreen", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": true, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/lockconfig.hpp:21", + "CONFIG declaration: bool syncWallpaper = true" + ], + [ + "shell/modules/nexus/pages/wallandstyle/LockScreenPage.qml:147", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setDesktopClockEnabled", + "path": "background.desktopClock.enabled", + "group": "wallpaper-scheme", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:29", + "CONFIG declaration: bool enabled = true" + ], + [ + "shell/modules/nexus/pages/wallandstyle/DesktopAddonsPage.qml:89", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setDesktopClockInvertColors", + "path": "background.desktopClock.invertColors", + "group": "wallpaper-scheme", + "kind": "bool", + "default": false, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:32", + "CONFIG declaration: bool invertColors = false" + ], + [ + "shell/modules/nexus/pages/wallandstyle/DesktopAddonsPage.qml:213", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setDesktopClockPosition", + "path": "background.desktopClock.position", + "group": "wallpaper-scheme", + "kind": "enum", + "default": "bottom-right", + "minimum": null, + "maximum": null, + "step": null, + "enum": [ + "top-left", + "top-center", + "top-right", + "center", + "bottom-left", + "bottom-center", + "bottom-right" + ], + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:31", + "CONFIG declaration: QString position = QStringLiteral(\"bottom-right\")" + ], + [ + "shell/modules/nexus/pages/wallandstyle/DesktopAddonsPage.qml:197", + "shipped Nexus control (SelectRow)" + ] + ] + }, + { + "name": "setDesktopClockScale", + "path": "background.desktopClock.scale", + "group": "wallpaper-scheme", + "kind": "float", + "default": 1.0, + "minimum": 0.5, + "maximum": 3, + "step": 0.1, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:30", + "CONFIG declaration: qreal scale = 1.0" + ], + [ + "shell/modules/nexus/pages/wallandstyle/DesktopAddonsPage.qml:186", + "shipped Nexus control (StepperRow)" + ] + ] + }, + { + "name": "setDesktopIconsEnabled", + "path": "background.desktopIconsEnabled", + "group": "wallpaper-scheme", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:103", + "CONFIG declaration: bool desktopIconsEnabled = true" + ], + [ + "shell/modules/nexus/pages/DesktopPage.qml:40", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setDesktopLyricsAlignment", + "path": "background.desktopLyrics.alignment", + "group": "wallpaper-scheme", + "kind": "int", + "default": 1, + "minimum": 0, + "maximum": 2, + "step": 1, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:71", + "CONFIG declaration: int alignment = 1" + ], + [ + "shell/modules/nexus/pages/wallandstyle/DesktopAddonsPage.qml:294", + "shipped Nexus control (SelectRow)" + ] + ] + }, + { + "name": "setDesktopLyricsAutoHide", + "path": "background.desktopLyrics.autoHide", + "group": "wallpaper-scheme", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:68", + "CONFIG declaration: bool autoHide = true" + ], + [ + "shell/modules/nexus/pages/wallandstyle/DesktopAddonsPage.qml:131", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setDesktopLyricsEnabled", + "path": "background.desktopLyrics.enabled", + "group": "wallpaper-scheme", + "kind": "bool", + "default": false, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:67", + "CONFIG declaration: bool enabled = false" + ], + [ + "shell/modules/nexus/pages/wallandstyle/DesktopAddonsPage.qml:119", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setDesktopLyricsInvertColors", + "path": "background.desktopLyrics.invertColors", + "group": "wallpaper-scheme", + "kind": "bool", + "default": false, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:72", + "CONFIG declaration: bool invertColors = false" + ], + [ + "shell/modules/nexus/pages/wallandstyle/DesktopAddonsPage.qml:308", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setDesktopLyricsPosition", + "path": "background.desktopLyrics.position", + "group": "wallpaper-scheme", + "kind": "enum", + "default": "bottom-center", + "minimum": null, + "maximum": null, + "step": null, + "enum": [ + "top-left", + "top-center", + "top-right", + "center", + "bottom-left", + "bottom-center", + "bottom-right" + ], + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:70", + "CONFIG declaration: QString position = QStringLiteral(\"bottom-center\")" + ], + [ + "shell/modules/nexus/pages/wallandstyle/DesktopAddonsPage.qml:278", + "shipped Nexus control (SelectRow)" + ] + ] + }, + { + "name": "setDesktopLyricsScale", + "path": "background.desktopLyrics.scale", + "group": "wallpaper-scheme", + "kind": "float", + "default": 1.0, + "minimum": 0.5, + "maximum": 3, + "step": 0.1, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:69", + "CONFIG declaration: qreal scale = 1.0" + ], + [ + "shell/modules/nexus/pages/wallandstyle/DesktopAddonsPage.qml:267", + "shipped Nexus control (StepperRow)" + ] + ] + }, + { + "name": "setDesktopShapesAutoHide", + "path": "background.desktopShapes.autoHide", + "group": "wallpaper-scheme", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:81", + "CONFIG declaration: bool autoHide = true" + ], + [ + "shell/modules/nexus/pages/wallandstyle/DesktopAddonsPage.qml:109", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setDesktopShapesEnabled", + "path": "background.desktopShapes.enabled", + "group": "wallpaper-scheme", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:80", + "CONFIG declaration: bool enabled = true" + ], + [ + "shell/modules/nexus/pages/wallandstyle/DesktopAddonsPage.qml:97", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setDesktopShapesPosition", + "path": "background.desktopShapes.position", + "group": "wallpaper-scheme", + "kind": "enum", + "default": "bottom-center", + "minimum": null, + "maximum": null, + "step": null, + "enum": [ + "top-left", + "top-center", + "top-right", + "center", + "bottom-left", + "bottom-center", + "bottom-right" + ], + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:83", + "CONFIG declaration: QString position = QStringLiteral(\"bottom-center\")" + ], + [ + "shell/modules/nexus/pages/wallandstyle/DesktopAddonsPage.qml:241", + "shipped Nexus control (SelectRow)" + ] + ] + }, + { + "name": "setDesktopShapesScale", + "path": "background.desktopShapes.scale", + "group": "wallpaper-scheme", + "kind": "float", + "default": 1.0, + "minimum": 0.5, + "maximum": 3, + "step": 0.1, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:82", + "CONFIG declaration: qreal scale = 1.0" + ], + [ + "shell/modules/nexus/pages/wallandstyle/DesktopAddonsPage.qml:230", + "shipped Nexus control (StepperRow)" + ] + ] + }, + { + "name": "setMaterialYouIconsEnabled", + "path": "background.materialYouIconsEnabled", + "group": "wallpaper-scheme", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:104", + "CONFIG declaration: bool materialYouIconsEnabled = true" + ], + [ + "shell/modules/nexus/pages/DesktopPage.qml:57", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setMaterialYouIconsVibrant", + "path": "background.materialYouIconsVibrant", + "group": "wallpaper-scheme", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:105", + "CONFIG declaration: bool materialYouIconsVibrant = true" + ], + [ + "shell/modules/nexus/pages/DesktopPage.qml:74", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setSlideshowEnabled", + "path": "background.slideshowEnabled", + "group": "wallpaper-scheme", + "kind": "bool", + "default": false, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:94", + "CONFIG declaration: bool slideshowEnabled = false" + ], + [ + "shell/modules/nexus/pages/wallandstyle/SlideshowAndOrderPage.qml:33", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setSlideshowInterval", + "path": "background.slideshowInterval", + "group": "wallpaper-scheme", + "kind": "float", + "default": 0.16, + "minimum": 0, + "maximum": 1, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:95", + "CONFIG declaration: qreal slideshowInterval = 0.16" + ], + [ + "shell/modules/nexus/pages/wallandstyle/SlideshowAndOrderPage.qml:43", + "shipped Nexus control (SliderRow)" + ] + ] + }, + { + "name": "setSlideshowRandom", + "path": "background.slideshowRandom", + "group": "wallpaper-scheme", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:96", + "CONFIG declaration: bool slideshowRandom = true" + ], + [ + "shell/modules/nexus/pages/wallandstyle/SlideshowAndOrderPage.qml:54", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setVideoWallpaperMuteOnMedia", + "path": "background.videoWallpaperMuteOnMedia", + "group": "wallpaper-scheme", + "kind": "bool", + "default": false, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:102", + "CONFIG declaration: bool videoWallpaperMuteOnMedia = false" + ], + [ + "shell/modules/nexus/pages/wallandstyle/VideoWallpapersPage.qml:61", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setVideoWallpaperPauseOnAllDisplays", + "path": "background.videoWallpaperPauseOnAllDisplays", + "group": "wallpaper-scheme", + "kind": "bool", + "default": false, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:101", + "CONFIG declaration: bool videoWallpaperPauseOnAllDisplays = false" + ], + [ + "shell/modules/nexus/pages/wallandstyle/VideoWallpapersPage.qml:55", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setVideoWallpaperPauseOnFullscreen", + "path": "background.videoWallpaperPauseOnFullscreen", + "group": "wallpaper-scheme", + "kind": "bool", + "default": false, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:99", + "CONFIG declaration: bool videoWallpaperPauseOnFullscreen = false" + ], + [ + "shell/modules/nexus/pages/wallandstyle/VideoWallpapersPage.qml:41", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setVideoWallpaperPauseOnTiled", + "path": "background.videoWallpaperPauseOnTiled", + "group": "wallpaper-scheme", + "kind": "bool", + "default": false, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:100", + "CONFIG declaration: bool videoWallpaperPauseOnTiled = false" + ], + [ + "shell/modules/nexus/pages/wallandstyle/VideoWallpapersPage.qml:48", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setVideoWallpaperPaused", + "path": "background.videoWallpaperPaused", + "group": "wallpaper-scheme", + "kind": "bool", + "default": false, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:97", + "CONFIG declaration: bool videoWallpaperPaused = false" + ], + [ + "shell/modules/nexus/pages/wallandstyle/VideoWallpapersPage.qml:28", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setVideoWallpaperSoundEnabled", + "path": "background.videoWallpaperSoundEnabled", + "group": "wallpaper-scheme", + "kind": "bool", + "default": false, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:98", + "CONFIG declaration: bool videoWallpaperSoundEnabled = false" + ], + [ + "shell/modules/nexus/pages/wallandstyle/VideoWallpapersPage.qml:35", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setVisualiserAutoHide", + "path": "background.visualiser.autoHide", + "group": "wallpaper-scheme", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:41", + "CONFIG declaration: bool autoHide = true" + ], + [ + "shell/modules/nexus/pages/wallandstyle/DesktopAddonsPage.qml:155", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setVisualiserBlur", + "path": "background.visualiser.blur", + "group": "wallpaper-scheme", + "kind": "bool", + "default": false, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:43", + "CONFIG declaration: bool blur = false" + ], + [ + "shell/modules/nexus/pages/wallandstyle/DesktopAddonsPage.qml:325", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setVisualiserEnabled", + "path": "background.visualiser.enabled", + "group": "wallpaper-scheme", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:40", + "CONFIG declaration: bool enabled = true" + ], + [ + "shell/modules/nexus/pages/wallandstyle/DesktopAddonsPage.qml:141", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setVisualiserHideOnAllMonitors", + "path": "background.visualiser.hideOnAllMonitors", + "group": "wallpaper-scheme", + "kind": "bool", + "default": false, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:42", + "CONFIG declaration: bool hideOnAllMonitors = false" + ], + [ + "shell/modules/nexus/pages/wallandstyle/DesktopAddonsPage.qml:165", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setVisualiserRounding", + "path": "background.visualiser.rounding", + "group": "wallpaper-scheme", + "kind": "float", + "default": 1.0, + "minimum": 0, + "maximum": 1, + "step": 0.05, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:44", + "CONFIG declaration: qreal rounding = 1" + ], + [ + "shell/modules/nexus/pages/wallandstyle/DesktopAddonsPage.qml:333", + "shipped Nexus control (StepperRow)" + ] + ] + }, + { + "name": "setVisualiserSpacing", + "path": "background.visualiser.spacing", + "group": "wallpaper-scheme", + "kind": "float", + "default": 1.0, + "minimum": 0.5, + "maximum": 3, + "step": 0.1, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:45", + "CONFIG declaration: qreal spacing = 1" + ], + [ + "shell/modules/nexus/pages/wallandstyle/DesktopAddonsPage.qml:343", + "shipped Nexus control (StepperRow)" + ] + ] + }, + { + "name": "setWallpaperEnabled", + "path": "background.wallpaperEnabled", + "group": "wallpaper-scheme", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:90", + "CONFIG declaration: bool wallpaperEnabled = true" + ], + [ + "shell/modules/nexus/pages/DesktopPage.qml:24", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setWallpaperFillMode", + "path": "background.wallpaperFillMode", + "group": "wallpaper-scheme", + "kind": "enum", + "default": 2, + "minimum": null, + "maximum": null, + "step": null, + "enum": [ + 0, + 1, + 2 + ], + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:91", + "CONFIG declaration: int wallpaperFillMode = 2" + ], + [ + "shell/modules/nexus/pages/wallandstyle/WallpaperSettingsPage.qml:49", + "shipped Nexus control (SelectRow)" + ], + [ + "shell/modules/nexus/pages/wallandstyle/WallpaperSettingsPage.qml:26", + "scalingValues: [Image.PreserveAspectCrop, Image.PreserveAspectFit, Image.Stretch] = [2, 1, 0]; the SelectRow writes these ints" + ] + ] + }, + { + "name": "setWallpaperRecolor", + "path": "background.wallpaperRecolor", + "group": "wallpaper-scheme", + "kind": "bool", + "default": false, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:92", + "CONFIG declaration: bool wallpaperRecolor = false" + ], + [ + "shell/modules/nexus/pages/wallandstyle/WallpaperSettingsPage.qml:68", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setWallpaperRecolorStrength", + "path": "background.wallpaperRecolorStrength", + "group": "wallpaper-scheme", + "kind": "float", + "default": 0.5, + "minimum": 0, + "maximum": 1, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:93", + "CONFIG declaration: qreal wallpaperRecolorStrength = 0.5" + ], + [ + "shell/modules/nexus/pages/wallandstyle/WallpaperSettingsPage.qml:85", + "shipped Nexus control (SliderRow)" + ] + ] + }, + { + "name": "setBaseDuration", + "path": "overview.baseDuration", + "group": "overview", + "kind": "int", + "default": 300, + "minimum": 100, + "maximum": 1000, + "step": 50, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/overviewconfig.hpp:22", + "CONFIG declaration: int baseDuration = 300" + ], + [ + "shell/modules/nexus/pages/panels/OverviewPanel.qml:225", + "shipped Nexus control (StepperRow)" + ] + ] + }, + { + "name": "setBlobScaleSpeed", + "path": "overview.blobScaleSpeed", + "group": "overview", + "kind": "float", + "default": 1.0, + "minimum": 0.1, + "maximum": 5.0, + "step": 0.1, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/overviewconfig.hpp:23", + "CONFIG declaration: qreal blobScaleSpeed = 1.0" + ], + [ + "shell/modules/nexus/pages/panels/OverviewPanel.qml:234", + "shipped Nexus control (StepperRow)" + ] + ] + }, + { + "name": "setDisableWallpaperBlur", + "path": "overview.disableWallpaperBlur", + "group": "overview", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/overviewconfig.hpp:12", + "CONFIG declaration: bool disableWallpaperBlur = true" + ], + [ + "shell/modules/nexus/pages/panels/OverviewPanel.qml:191", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setEasingType", + "path": "overview.easingType", + "group": "overview", + "kind": "enum", + "default": 2, + "minimum": null, + "maximum": null, + "step": null, + "enum": [ + 0, + 2, + 3, + 6, + 10, + 14, + 18, + 22, + 26, + 30, + 33, + 34, + 38 + ], + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/overviewconfig.hpp:26", + "CONFIG declaration: int easingType = 2" + ], + [ + "shell/modules/nexus/pages/panels/OverviewPanel.qml:207", + "shipped Nexus control (SelectRow)" + ] + ] + }, + { + "name": "setEnableOverviewBlur", + "path": "overview.enableOverviewBlur", + "group": "overview", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/overviewconfig.hpp:13", + "CONFIG declaration: bool enableOverviewBlur = true" + ], + [ + "shell/modules/nexus/pages/panels/OverviewPanel.qml:197", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setGridFadeSpeed", + "path": "overview.gridFadeSpeed", + "group": "overview", + "kind": "float", + "default": 1.0, + "minimum": 0.1, + "maximum": 5.0, + "step": 0.1, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/overviewconfig.hpp:25", + "CONFIG declaration: qreal gridFadeSpeed = 1.0" + ], + [ + "shell/modules/nexus/pages/panels/OverviewPanel.qml:252", + "shipped Nexus control (StepperRow)" + ] + ] + }, + { + "name": "setHoverBottomLeft", + "path": "overview.hoverBottomLeft", + "group": "overview", + "kind": "bool", + "default": false, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/overviewconfig.hpp:19", + "CONFIG declaration: bool hoverBottomLeft = false" + ], + [ + "shell/modules/nexus/pages/panels/OverviewPanel.qml:159", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setHoverBottomRight", + "path": "overview.hoverBottomRight", + "group": "overview", + "kind": "bool", + "default": false, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/overviewconfig.hpp:20", + "CONFIG declaration: bool hoverBottomRight = false" + ], + [ + "shell/modules/nexus/pages/panels/OverviewPanel.qml:164", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setHoverTopLeft", + "path": "overview.hoverTopLeft", + "group": "overview", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/overviewconfig.hpp:17", + "CONFIG declaration: bool hoverTopLeft = true" + ], + [ + "shell/modules/nexus/pages/panels/OverviewPanel.qml:148", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setHoverTopRight", + "path": "overview.hoverTopRight", + "group": "overview", + "kind": "bool", + "default": false, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/overviewconfig.hpp:18", + "CONFIG declaration: bool hoverTopRight = false" + ], + [ + "shell/modules/nexus/pages/panels/OverviewPanel.qml:154", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setLayoutType", + "path": "overview.layoutType", + "group": "overview", + "kind": "int", + "default": 1, + "minimum": 0, + "maximum": 1, + "step": 1, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/overviewconfig.hpp:27", + "CONFIG declaration: int layoutType = 1" + ], + [ + "shell/modules/nexus/pages/panels/OverviewPanel.qml:173", + "shipped Nexus control (SelectRow)" + ] + ] + }, + { + "name": "setOverviewDragThreshold", + "path": "overview.dragThreshold", + "group": "overview", + "kind": "int", + "default": 30, + "minimum": 10, + "maximum": 200, + "step": 5, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/overviewconfig.hpp:15", + "CONFIG declaration: int dragThreshold = 30" + ], + [ + "shell/modules/nexus/pages/panels/OverviewPanel.qml:131", + "shipped Nexus control (StepperRow)" + ] + ] + }, + { + "name": "setOverviewEnabled", + "path": "overview.enabled", + "group": "overview", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/overviewconfig.hpp:11", + "CONFIG declaration: bool enabled = true" + ], + [ + "shell/modules/nexus/pages/panels/OverviewPanel.qml:108", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setOverviewHoverThickness", + "path": "overview.hoverThickness", + "group": "overview", + "kind": "int", + "default": 20, + "minimum": 1, + "maximum": 100, + "step": 1, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/overviewconfig.hpp:16", + "CONFIG declaration: int hoverThickness = 20" + ], + [ + "shell/modules/nexus/pages/panels/OverviewPanel.qml:120", + "shipped Nexus control (StepperRow)" + ] + ] + }, + { + "name": "setOverviewShowOnHover", + "path": "overview.showOnHover", + "group": "overview", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/overviewconfig.hpp:14", + "CONFIG declaration: bool showOnHover = true" + ], + [ + "shell/modules/nexus/pages/panels/OverviewPanel.qml:114", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setWallpaperFadeSpeed", + "path": "overview.wallpaperFadeSpeed", + "group": "overview", + "kind": "float", + "default": 1.0, + "minimum": 0.1, + "maximum": 5.0, + "step": 0.1, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/overviewconfig.hpp:24", + "CONFIG declaration: qreal wallpaperFadeSpeed = 1.0" + ], + [ + "shell/modules/nexus/pages/panels/OverviewPanel.qml:243", + "shipped Nexus control (StepperRow)" + ] + ] + }, + { + "name": "setEnableBrightness", + "path": "osd.enableBrightness", + "group": "osd", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/osdconfig.hpp:15", + "CONFIG declaration: bool enableBrightness = true" + ], + [ + "shell/modules/nexus/pages/utilities/OsdPage.qml:45", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setEnableMicrophone", + "path": "osd.enableMicrophone", + "group": "osd", + "kind": "bool", + "default": false, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/osdconfig.hpp:16", + "CONFIG declaration: bool enableMicrophone = false" + ], + [ + "shell/modules/nexus/pages/utilities/OsdPage.qml:38", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setEnableVolume", + "path": "osd.enableVolume", + "group": "osd", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/osdconfig.hpp:17", + "CONFIG declaration: bool enableVolume = true" + ], + [ + "shell/modules/nexus/pages/utilities/OsdPage.qml:31", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setHideDelay", + "path": "osd.hideDelay", + "group": "osd", + "kind": "int", + "default": 2000, + "minimum": 1000, + "maximum": 10000, + "step": 1000, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/osdconfig.hpp:12", + "CONFIG declaration: int hideDelay = 2000" + ], + [ + "shell/modules/nexus/pages/utilities/OsdPage.qml:83", + "shipped Nexus control (StepperRow)" + ], + [ + "shell/modules/nexus/pages/utilities/OsdPage.qml:88", + "stepper displays seconds (value: x/1000; onMoved: Math.round(value*1000)); stored unit is ms — range converted x1000" + ] + ] + }, + { + "name": "setOsdEnabled", + "path": "osd.enabled", + "group": "osd", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/osdconfig.hpp:11", + "CONFIG declaration: bool enabled = true" + ], + [ + "shell/modules/nexus/pages/utilities/OsdPage.qml:23", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setOsdHoverThickness", + "path": "osd.hoverThickness", + "group": "osd", + "kind": "int", + "default": 10, + "minimum": 1, + "maximum": 100, + "step": 1, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/osdconfig.hpp:13", + "CONFIG declaration: int hoverThickness = 10" + ], + [ + "shell/modules/nexus/pages/utilities/OsdPage.qml:57", + "shipped Nexus control (StepperRow)" + ] + ] + }, + { + "name": "setOsdHoverWidth", + "path": "osd.hoverWidth", + "group": "osd", + "kind": "int", + "default": 50, + "minimum": 10, + "maximum": 100, + "step": 5, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/osdconfig.hpp:14", + "CONFIG declaration: int hoverWidth = 50" + ], + [ + "shell/modules/nexus/pages/utilities/OsdPage.qml:68", + "shipped Nexus control (StepperRow)" + ] + ] + }, + { + "name": "setColorizeMediaGif", + "path": "dashboard.colorizeMediaGif", + "group": "dashboard", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/dashboardconfig.hpp:30", + "CONFIG declaration: bool colorizeMediaGif = true" + ], + [ + "shell/modules/nexus/pages/panels/DashboardPanel.qml:174", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setDashboardDragThreshold", + "path": "dashboard.dragThreshold", + "group": "dashboard", + "kind": "int", + "default": 50, + "minimum": 0, + "maximum": 200, + "step": 5, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/dashboardconfig.hpp:36", + "CONFIG declaration: int dragThreshold = 50" + ], + [ + "shell/modules/nexus/pages/panels/DashboardPanel.qml:269", + "shipped Nexus control (StepperRow)" + ] + ] + }, + { + "name": "setDashboardEnabled", + "path": "dashboard.enabled", + "group": "dashboard", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/dashboardconfig.hpp:22", + "CONFIG declaration: bool enabled = true" + ], + [ + "shell/modules/nexus/pages/panels/DashboardPanel.qml:94", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setDashboardHoverThickness", + "path": "dashboard.hoverThickness", + "group": "dashboard", + "kind": "int", + "default": 10, + "minimum": 1, + "maximum": 100, + "step": 1, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/dashboardconfig.hpp:37", + "CONFIG declaration: int hoverThickness = 10" + ], + [ + "shell/modules/nexus/pages/panels/DashboardPanel.qml:248", + "shipped Nexus control (StepperRow)" + ] + ] + }, + { + "name": "setDashboardHoverWidth", + "path": "dashboard.hoverWidth", + "group": "dashboard", + "kind": "int", + "default": 50, + "minimum": 10, + "maximum": 100, + "step": 5, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/dashboardconfig.hpp:38", + "CONFIG declaration: int hoverWidth = 50" + ], + [ + "shell/modules/nexus/pages/panels/DashboardPanel.qml:259", + "shipped Nexus control (StepperRow)" + ] + ] + }, + { + "name": "setDashboardShowOnHover", + "path": "dashboard.showOnHover", + "group": "dashboard", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/dashboardconfig.hpp:23", + "CONFIG declaration: bool showOnHover = true" + ], + [ + "shell/modules/nexus/pages/panels/DashboardPanel.qml:101", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setMediaUpdateInterval", + "path": "dashboard.mediaUpdateInterval", + "group": "dashboard", + "kind": "int", + "default": 500, + "minimum": 100, + "maximum": 2000, + "step": 50, + "enum": null, + "string_max_len": null, + "global_only": true, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/dashboardconfig.hpp:34", + "CONFIG declaration: int mediaUpdateInterval = 500" + ], + [ + "shell/modules/nexus/pages/ServicesPage.qml:89", + "shipped Nexus control (StepperRow)" + ] + ] + }, + { + "name": "setPerformanceShowBattery", + "path": "dashboard.performance.showBattery", + "group": "dashboard", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/dashboardconfig.hpp:11", + "CONFIG declaration: bool showBattery = true" + ], + [ + "shell/modules/nexus/pages/panels/DashboardPanel.qml:205", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setPerformanceShowCpu", + "path": "dashboard.performance.showCpu", + "group": "dashboard", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/dashboardconfig.hpp:13", + "CONFIG declaration: bool showCpu = true" + ], + [ + "shell/modules/nexus/pages/panels/DashboardPanel.qml:218", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setPerformanceShowGpu", + "path": "dashboard.performance.showGpu", + "group": "dashboard", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/dashboardconfig.hpp:12", + "CONFIG declaration: bool showGpu = true" + ], + [ + "shell/modules/nexus/pages/panels/DashboardPanel.qml:212", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setPerformanceShowMemory", + "path": "dashboard.performance.showMemory", + "group": "dashboard", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/dashboardconfig.hpp:14", + "CONFIG declaration: bool showMemory = true" + ], + [ + "shell/modules/nexus/pages/panels/DashboardPanel.qml:224", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setPerformanceShowNetwork", + "path": "dashboard.performance.showNetwork", + "group": "dashboard", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/dashboardconfig.hpp:16", + "CONFIG declaration: bool showNetwork = true" + ], + [ + "shell/modules/nexus/pages/panels/DashboardPanel.qml:236", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setPerformanceShowStorage", + "path": "dashboard.performance.showStorage", + "group": "dashboard", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/dashboardconfig.hpp:15", + "CONFIG declaration: bool showStorage = true" + ], + [ + "shell/modules/nexus/pages/panels/DashboardPanel.qml:230", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setResourceUpdateInterval", + "path": "dashboard.resourceUpdateInterval", + "group": "dashboard", + "kind": "int", + "default": 1000, + "minimum": 500, + "maximum": 10000, + "step": 500, + "enum": null, + "string_max_len": null, + "global_only": true, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/dashboardconfig.hpp:35", + "CONFIG declaration: int resourceUpdateInterval = 1000" + ], + [ + "shell/modules/nexus/pages/ServicesPage.qml:100", + "shipped Nexus control (StepperRow)" + ], + [ + "shell/modules/nexus/pages/ServicesPage.qml:103", + "stepper displays seconds (value: x/1000; onMoved: Math.round(v*1000)); stored unit is ms — range converted x1000" + ] + ] + }, + { + "name": "setShowClockSeconds", + "path": "dashboard.showClockSeconds", + "group": "dashboard", + "kind": "bool", + "default": false, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/dashboardconfig.hpp:32", + "CONFIG declaration: bool showClockSeconds = false" + ], + [ + "shell/modules/nexus/pages/panels/DashboardPanel.qml:128", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setShowDashboard", + "path": "dashboard.showDashboard", + "group": "dashboard", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/dashboardconfig.hpp:24", + "CONFIG declaration: bool showDashboard = true" + ], + [ + "shell/modules/nexus/pages/panels/DashboardPanel.qml:141", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setShowMedia", + "path": "dashboard.showMedia", + "group": "dashboard", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/dashboardconfig.hpp:25", + "CONFIG declaration: bool showMedia = true" + ], + [ + "shell/modules/nexus/pages/panels/DashboardPanel.qml:148", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setShowPerformance", + "path": "dashboard.showPerformance", + "group": "dashboard", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/dashboardconfig.hpp:26", + "CONFIG declaration: bool showPerformance = true" + ], + [ + "shell/modules/nexus/pages/panels/DashboardPanel.qml:154", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setShowTerminal", + "path": "dashboard.showTerminal", + "group": "dashboard", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/dashboardconfig.hpp:28", + "CONFIG declaration: bool showTerminal = true" + ], + [ + "shell/modules/nexus/pages/panels/DashboardPanel.qml:167", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setShowWeather", + "path": "dashboard.showWeather", + "group": "dashboard", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/dashboardconfig.hpp:27", + "CONFIG declaration: bool showWeather = true" + ], + [ + "shell/modules/nexus/pages/panels/DashboardPanel.qml:160", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setUseMediaShapes", + "path": "dashboard.useMediaShapes", + "group": "dashboard", + "kind": "bool", + "default": false, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/dashboardconfig.hpp:31", + "CONFIG declaration: bool useMediaShapes = false" + ], + [ + "shell/modules/nexus/pages/panels/DashboardPanel.qml:182", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setGrabWidth", + "path": "sidebar.grabWidth", + "group": "sidebar", + "kind": "int", + "default": 12, + "minimum": 1, + "maximum": 100, + "step": 1, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/sidebarconfig.hpp:13", + "CONFIG declaration: int grabWidth = 12" + ], + [ + "shell/modules/nexus/pages/panels/SidebarPanel.qml:48", + "shipped Nexus control (StepperRow)" + ] + ] + }, + { + "name": "setSidebarDragThreshold", + "path": "sidebar.dragThreshold", + "group": "sidebar", + "kind": "int", + "default": 50, + "minimum": 0, + "maximum": 200, + "step": 5, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/sidebarconfig.hpp:12", + "CONFIG declaration: int dragThreshold = 50" + ], + [ + "shell/modules/nexus/pages/panels/SidebarPanel.qml:36", + "shipped Nexus control (StepperRow)" + ] + ] + }, + { + "name": "setSidebarEnabled", + "path": "sidebar.enabled", + "group": "sidebar", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/sidebarconfig.hpp:11", + "CONFIG declaration: bool enabled = true" + ], + [ + "shell/modules/nexus/pages/panels/SidebarPanel.qml:29", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setNetworkRescanInterval", + "path": "nexus.networkRescanInterval", + "group": "nexus", + "kind": "int", + "default": 15000, + "minimum": 5000, + "maximum": 120000, + "step": 5000, + "enum": null, + "string_max_len": null, + "global_only": true, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/nexusconfig.hpp:12", + "CONFIG declaration: int networkRescanInterval = 15000" + ], + [ + "shell/modules/nexus/pages/ServicesPage.qml:110", + "shipped Nexus control (StepperRow)" + ], + [ + "shell/modules/nexus/pages/ServicesPage.qml:114", + "stepper displays seconds (value: x/1000; onMoved: Math.round(v*1000)); stored unit is ms — range converted x1000" + ] + ] + }, + { + "name": "setBorderThickness", + "path": "border.thickness", + "group": "border", + "kind": "int", + "default": 10, + "minimum": 0, + "maximum": 50, + "step": 2, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [ + "shell border|border|outline" + ], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/borderconfig.hpp:13", + "CONFIG declaration: int thickness = 10" + ], + [ + "shell/modules/nexus/pages/wallandstyle/AppearancePage.qml:108", + "shipped Nexus control (StepperRow)" + ] + ] + }, + { + "name": "setRounding", + "path": "border.rounding", + "group": "border", + "kind": "int", + "default": 25, + "minimum": 0, + "maximum": 100, + "step": 1, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/borderconfig.hpp:14", + "CONFIG declaration: int rounding = 25" + ], + [ + "shell/modules/nexus/pages/wallandstyle/AppearancePage.qml:336", + "shipped Nexus control (StepperRow)" + ] + ] + }, + { + "name": "setSmoothing", + "path": "border.smoothing", + "group": "border", + "kind": "int", + "default": 20, + "minimum": 0, + "maximum": 100, + "step": 1, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/borderconfig.hpp:15", + "CONFIG declaration: int smoothing = 20" + ], + [ + "shell/modules/nexus/pages/wallandstyle/AppearancePage.qml:347", + "shipped Nexus control (StepperRow)" + ] + ] + }, + { + "name": "setAllScreens", + "path": "tabSwitch.allScreens", + "group": "general", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/tabswitchconfig.hpp:15", + "CONFIG declaration: bool allScreens = true" + ], + [ + "shell/modules/nexus/pages/panels/TabSwitcherPanel.qml:164", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setCheckUpdates", + "path": "general.checkUpdates", + "group": "general", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/generalconfig.hpp:70", + "CONFIG declaration: bool checkUpdates = true" + ], + [ + "shell/modules/nexus/pages/panels/taskbar/BarUpdates.qml:44", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setCurrentDesktopOnly", + "path": "tabSwitch.currentDesktopOnly", + "group": "general", + "kind": "bool", + "default": false, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/tabswitchconfig.hpp:12", + "CONFIG declaration: bool currentDesktopOnly = false" + ], + [ + "shell/modules/nexus/pages/panels/TabSwitcherPanel.qml:114", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setPreviewOnDesktop", + "path": "tabSwitch.previewOnDesktop", + "group": "general", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/tabswitchconfig.hpp:13", + "CONFIG declaration: bool previewOnDesktop = true" + ], + [ + "shell/modules/nexus/pages/panels/TabSwitcherPanel.qml:129", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setSessionDragThreshold", + "path": "session.dragThreshold", + "group": "general", + "kind": "int", + "default": 30, + "minimum": 10, + "maximum": 200, + "step": 5, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/sessionconfig.hpp:36", + "CONFIG declaration: int dragThreshold = 30" + ], + [ + "shell/modules/nexus/pages/SessionPage.qml:53", + "shipped Nexus control (StepperRow)" + ] + ] + }, + { + "name": "setSessionEnabled", + "path": "session.enabled", + "group": "general", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/sessionconfig.hpp:35", + "CONFIG declaration: bool enabled = true" + ], + [ + "shell/modules/nexus/pages/SessionPage.qml:36", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setSessionVimKeybinds", + "path": "session.vimKeybinds", + "group": "general", + "kind": "bool", + "default": false, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/sessionconfig.hpp:37", + "CONFIG declaration: bool vimKeybinds = false" + ], + [ + "shell/modules/nexus/pages/SessionPage.qml:45", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setShowMinimized", + "path": "tabSwitch.showMinimized", + "group": "general", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/tabswitchconfig.hpp:14", + "CONFIG declaration: bool showMinimized = true" + ], + [ + "shell/modules/nexus/pages/panels/TabSwitcherPanel.qml:149", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setArpcCaelestiaInfo", + "path": "services.arpcCaelestiaInfo", + "group": "services", + "kind": "bool", + "default": false, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": true, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/serviceconfig.hpp:82", + "CONFIG declaration: bool arpcCaelestiaInfo = false" + ], + [ + "shell/modules/nexus/pages/services/ArpcPage.qml:74", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setArpcEnabled", + "path": "services.arpcEnabled", + "group": "services", + "kind": "bool", + "default": false, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": true, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/serviceconfig.hpp:71", + "CONFIG declaration: bool arpcEnabled = false" + ], + [ + "shell/modules/nexus/pages/services/ArpcPage.qml:56", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setArpcIdleTimeout", + "path": "services.arpcIdleTimeout", + "group": "services", + "kind": "int", + "default": 0, + "minimum": 0, + "maximum": 3600, + "step": 60, + "enum": null, + "string_max_len": null, + "global_only": true, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/serviceconfig.hpp:84", + "CONFIG declaration: int arpcIdleTimeout = 0" + ], + [ + "shell/modules/nexus/pages/services/ArpcPage.qml:83", + "shipped Nexus control (StepperRow)" + ], + [ + "shell/modules/nexus/pages/services/ArpcPage.qml:89", + "stepper displays minutes (value: Math.round(x/60); onMoved: Math.round(v*60)); stored unit is seconds — range converted x60" + ] + ] + }, + { + "name": "setArpcManualOverride", + "path": "services.arpcManualOverride", + "group": "services", + "kind": "bool", + "default": false, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": true, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/serviceconfig.hpp:83", + "CONFIG declaration: bool arpcManualOverride = false" + ], + [ + "shell/modules/nexus/pages/services/ArpcPage.qml:439", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setArpcSteamAutoDetect", + "path": "services.arpcSteamAutoDetect", + "group": "services", + "kind": "bool", + "default": false, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": true, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/serviceconfig.hpp:78", + "CONFIG declaration: bool arpcSteamAutoDetect = false" + ], + [ + "shell/modules/nexus/pages/services/ArpcPage.qml:65", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setAudioIncrement", + "path": "services.audioIncrement", + "group": "services", + "kind": "float", + "default": 0.1, + "minimum": 0.01, + "maximum": 0.5, + "step": 0.01, + "enum": null, + "string_max_len": null, + "global_only": true, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/serviceconfig.hpp:51", + "CONFIG declaration: qreal audioIncrement = 0.1" + ], + [ + "shell/modules/nexus/pages/ServicesPage.qml:151", + "shipped Nexus control (StepperRow)" + ], + [ + "shell/modules/nexus/pages/ServicesPage.qml:155", + "stepper displays percent (value: Math.round(x*100); onMoved: v/100); stored unit is a fraction — range converted /100" + ] + ] + }, + { + "name": "setAutoSchemeEnabled", + "path": "services.autoSchemeEnabled", + "group": "services", + "kind": "bool", + "default": false, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": true, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/serviceconfig.hpp:59", + "CONFIG declaration: bool autoSchemeEnabled = false" + ], + [ + "shell/modules/nexus/pages/wallandstyle/AdvancedColorsPage.qml:89", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setAutoSchemeMode", + "path": "services.autoSchemeMode", + "group": "services", + "kind": "enum", + "default": "solar", + "minimum": null, + "maximum": null, + "step": null, + "enum": [ + "solar", + "fixed" + ], + "string_max_len": null, + "global_only": true, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/serviceconfig.hpp:60", + "CONFIG declaration: QString autoSchemeMode = u\"solar\"_s" + ], + [ + "shell/modules/nexus/pages/wallandstyle/AdvancedColorsPage.qml:98", + "shipped Nexus control (SelectRow)" + ] + ] + }, + { + "name": "setBrightnessIncrement", + "path": "services.brightnessIncrement", + "group": "services", + "kind": "float", + "default": 0.1, + "minimum": 0.01, + "maximum": 0.5, + "step": 0.01, + "enum": null, + "string_max_len": null, + "global_only": true, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/serviceconfig.hpp:52", + "CONFIG declaration: qreal brightnessIncrement = 0.1" + ], + [ + "shell/modules/nexus/pages/ServicesPage.qml:162", + "shipped Nexus control (StepperRow)" + ], + [ + "shell/modules/nexus/pages/ServicesPage.qml:165", + "stepper displays percent (value: Math.round(x*100); onMoved: v/100); stored unit is a fraction — range converted /100" + ] + ] + }, + { + "name": "setClockFormat", + "path": "services.clockFormat", + "group": "services", + "kind": "enum", + "default": "Auto", + "minimum": null, + "maximum": null, + "step": null, + "enum": [ + "Auto", + "TwelveHour", + "TwentyFourHour" + ], + "string_max_len": null, + "global_only": true, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/serviceconfig.hpp:37", + "CONFIG declaration: caelestia::config::ClockFormat::Enum clockFormat = ClockFormat::Auto" + ], + [ + "shell/modules/nexus/pages/LanguageAndRegion.qml:419", + "shipped Nexus control (SelectRow)" + ] + ] + }, + { + "name": "setDataUnits", + "path": "services.dataUnits", + "group": "services", + "kind": "enum", + "default": "Binary", + "minimum": null, + "maximum": null, + "step": null, + "enum": [ + "Binary", + "Decimal" + ], + "string_max_len": null, + "global_only": true, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/serviceconfig.hpp:31", + "CONFIG declaration: caelestia::config::DataUnit::Enum dataUnits = DataUnit::Binary" + ], + [ + "shell/modules/nexus/pages/LanguageAndRegion.qml:405", + "shipped Nexus control (SelectRow)" + ] + ] + }, + { + "name": "setGpuType", + "path": "services.gpuType", + "group": "services", + "kind": "enum", + "default": "", + "minimum": null, + "maximum": null, + "step": null, + "enum": [ + "", + "NVIDIA", + "GENERIC", + "None" + ], + "string_max_len": null, + "global_only": true, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/serviceconfig.hpp:49", + "CONFIG declaration: QString gpuType = QString()" + ], + [ + "shell/modules/nexus/pages/ServicesPage.qml:206", + "shipped Nexus control (SelectRow)" + ], + [ + "shell/modules/nexus/pages/ServicesPage.qml:47", + "gpuValues: [\"\", \"NVIDIA\", \"GENERIC\", \"None\"] (fixed literal)" + ] + ] + }, + { + "name": "setMaxVolume", + "path": "services.maxVolume", + "group": "services", + "kind": "float", + "default": 1.0, + "minimum": 0.5, + "maximum": 2.0, + "step": 0.05, + "enum": null, + "string_max_len": null, + "global_only": true, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/serviceconfig.hpp:53", + "CONFIG declaration: qreal maxVolume = 1.0" + ], + [ + "shell/modules/nexus/pages/ServicesPage.qml:172", + "shipped Nexus control (StepperRow)" + ], + [ + "shell/modules/nexus/pages/ServicesPage.qml:176", + "stepper displays percent (value: Math.round(x*100); onMoved: v/100); stored unit is a fraction — range converted /100" + ] + ] + }, + { + "name": "setSensorUnits", + "path": "services.sensorUnits", + "group": "services", + "kind": "enum", + "default": "Celsius", + "minimum": null, + "maximum": null, + "step": null, + "enum": [ + "Auto", + "Celsius", + "Fahrenheit", + "Kelvin" + ], + "string_max_len": null, + "global_only": true, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/serviceconfig.hpp:30", + "CONFIG declaration: caelestia::config::TemperatureUnit::Enum sensorUnits = TemperatureUnit::Celsius" + ], + [ + "shell/modules/nexus/pages/LanguageAndRegion.qml:397", + "shipped Nexus control (SelectRow)" + ] + ] + }, + { + "name": "setSmartScheme", + "path": "services.smartScheme", + "group": "services", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": true, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/serviceconfig.hpp:54", + "CONFIG declaration: bool smartScheme = true" + ], + [ + "shell/modules/nexus/pages/wallandstyle/AdvancedColorsPage.qml:81", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setVisualiserBars", + "path": "services.visualiserBars", + "group": "services", + "kind": "int", + "default": 60, + "minimum": 10, + "maximum": 120, + "step": 2, + "enum": null, + "string_max_len": null, + "global_only": true, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/serviceconfig.hpp:50", + "CONFIG declaration: int visualiserBars = 60" + ], + [ + "shell/modules/nexus/pages/ServicesPage.qml:196", + "shipped Nexus control (StepperRow)" + ] + ] + }, + { + "name": "setWeatherUnits", + "path": "services.weatherUnits", + "group": "services", + "kind": "enum", + "default": "Auto", + "minimum": null, + "maximum": null, + "step": null, + "enum": [ + "Auto", + "Celsius", + "Fahrenheit", + "Kelvin" + ], + "string_max_len": null, + "global_only": true, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/serviceconfig.hpp:29", + "CONFIG declaration: caelestia::config::TemperatureUnit::Enum weatherUnits = TemperatureUnit::Auto" + ], + [ + "shell/modules/nexus/pages/LanguageAndRegion.qml:388", + "shipped Nexus control (SelectRow)" + ] + ] + }, + { + "name": "setGameModeAutoEnable", + "path": "utilities.gameMode.autoEnable", + "group": "utilities", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": true, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:69", + "CONFIG declaration: bool autoEnable = true" + ], + [ + "shell/modules/nexus/pages/services/GameModePage.qml:35", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setGameModeDisableDesktopLyrics", + "path": "utilities.gameMode.disableDesktopLyrics", + "group": "utilities", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": true, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:66", + "CONFIG declaration: bool disableDesktopLyrics = true" + ], + [ + "shell/modules/nexus/pages/services/GameModePage.qml:109", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setGameModeDisableHyprlandAnimations", + "path": "utilities.gameMode.disableHyprlandAnimations", + "group": "utilities", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": true, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:59", + "CONFIG declaration: bool disableHyprlandAnimations = true" + ], + [ + "shell/modules/nexus/pages/services/GameModePage.qml:60", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setGameModeDisableHyprlandBlur", + "path": "utilities.gameMode.disableHyprlandBlur", + "group": "utilities", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": true, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:60", + "CONFIG declaration: bool disableHyprlandBlur = true" + ], + [ + "shell/modules/nexus/pages/services/GameModePage.qml:67", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setGameModeDisableHyprlandGaps", + "path": "utilities.gameMode.disableHyprlandGaps", + "group": "utilities", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": true, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:61", + "CONFIG declaration: bool disableHyprlandGaps = true" + ], + [ + "shell/modules/nexus/pages/services/GameModePage.qml:73", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setGameModeDisableHyprlandShadows", + "path": "utilities.gameMode.disableHyprlandShadows", + "group": "utilities", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": true, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:62", + "CONFIG declaration: bool disableHyprlandShadows = true" + ], + [ + "shell/modules/nexus/pages/services/GameModePage.qml:79", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setGameModeDisableShellTransparency", + "path": "utilities.gameMode.disableShellTransparency", + "group": "utilities", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": true, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:63", + "CONFIG declaration: bool disableShellTransparency = true" + ], + [ + "shell/modules/nexus/pages/services/GameModePage.qml:98", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setGameModeDisableToastTransparency", + "path": "utilities.gameMode.disableToastTransparency", + "group": "utilities", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": true, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:65", + "CONFIG declaration: bool disableToastTransparency = true" + ], + [ + "shell/modules/nexus/pages/services/GameModePage.qml:104", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setGameModeDisableVisualizer", + "path": "utilities.gameMode.disableVisualizer", + "group": "utilities", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": true, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:67", + "CONFIG declaration: bool disableVisualizer = true" + ], + [ + "shell/modules/nexus/pages/services/GameModePage.qml:114", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setGameModeDisableWindowTransparency", + "path": "utilities.gameMode.disableWindowTransparency", + "group": "utilities", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": true, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:64", + "CONFIG declaration: bool disableWindowTransparency = true" + ], + [ + "shell/modules/nexus/pages/services/GameModePage.qml:85", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setMaxToasts", + "path": "utilities.maxToasts", + "group": "utilities", + "kind": "int", + "default": 4, + "minimum": 1, + "maximum": 10, + "step": 1, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:81", + "CONFIG declaration: int maxToasts = 4" + ], + [ + "shell/modules/nexus/pages/services/ToastPreferencesPage.qml:50", + "shipped Nexus control (StepperRow)" + ] + ] + }, + { + "name": "setShowGifRecorder", + "path": "utilities.showGifRecorder", + "group": "utilities", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:87", + "CONFIG declaration: bool showGifRecorder = true" + ], + [ + "shell/modules/nexus/pages/utilities/UtilitiesPanelPage.qml:38", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setShowKeepAwake", + "path": "utilities.showKeepAwake", + "group": "utilities", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:85", + "CONFIG declaration: bool showKeepAwake = true" + ], + [ + "shell/modules/nexus/pages/utilities/UtilitiesPanelPage.qml:23", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setShowQuickToggles", + "path": "utilities.showQuickToggles", + "group": "utilities", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:88", + "CONFIG declaration: bool showQuickToggles = true" + ], + [ + "shell/modules/nexus/pages/utilities/UtilitiesPanelPage.qml:45", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setShowScreenRecorder", + "path": "utilities.showScreenRecorder", + "group": "utilities", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:86", + "CONFIG declaration: bool showScreenRecorder = true" + ], + [ + "shell/modules/nexus/pages/utilities/UtilitiesPanelPage.qml:31", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setToastsChargingChanged", + "path": "utilities.toasts.chargingChanged", + "group": "utilities", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": true, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:19", + "CONFIG declaration: bool chargingChanged = true" + ], + [ + "shell/modules/nexus/pages/services/ToastEventsPage.qml:26", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setToastsConfigLoaded", + "path": "utilities.toasts.configLoaded", + "group": "utilities", + "kind": "bool", + "default": false, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": true, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:18", + "CONFIG declaration: bool configLoaded = false" + ], + [ + "shell/modules/nexus/pages/services/ToastEventsPage.qml:45", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setToastsFullscreen", + "path": "utilities.toasts.fullscreen", + "group": "utilities", + "kind": "enum", + "default": "off", + "minimum": null, + "maximum": null, + "step": null, + "enum": [ + "off", + "important", + "all" + ], + "string_max_len": null, + "global_only": true, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:17", + "CONFIG declaration: QString fullscreen = u\"off\"_s" + ], + [ + "shell/modules/nexus/pages/services/ToastPreferencesPage.qml:41", + "shipped Nexus control (SelectRow)" + ] + ] + }, + { + "name": "setToastsGameModeChanged", + "path": "utilities.toasts.gameModeChanged", + "group": "utilities", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": true, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:20", + "CONFIG declaration: bool gameModeChanged = true" + ], + [ + "shell/modules/nexus/pages/services/ToastEventsPage.qml:32", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setToastsNightLightChanged", + "path": "utilities.toasts.nightLightChanged", + "group": "utilities", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": true, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:31", + "CONFIG declaration: bool nightLightChanged = true" + ], + [ + "shell/modules/nexus/pages/services/ToastEventsPage.qml:38", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setToastsTransparency", + "path": "utilities.toasts.transparency", + "group": "utilities", + "kind": "bool", + "default": false, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": true, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:32", + "CONFIG declaration: bool transparency = false" + ], + [ + "shell/modules/nexus/pages/services/ToastPreferencesPage.qml:60", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setToastsTransparencyBase", + "path": "utilities.toasts.transparencyBase", + "group": "utilities", + "kind": "float", + "default": 0.85, + "minimum": 0, + "maximum": 1, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": true, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:33", + "CONFIG declaration: qreal transparencyBase = 0.85" + ], + [ + "shell/modules/nexus/pages/services/ToastPreferencesPage.qml:67", + "shipped Nexus control (SliderRow)" + ] + ] + }, + { + "name": "setUtilitiesDragThreshold", + "path": "utilities.dragThreshold", + "group": "utilities", + "kind": "int", + "default": 50, + "minimum": 0, + "maximum": 200, + "step": 5, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:78", + "CONFIG declaration: int dragThreshold = 50" + ], + [ + "shell/modules/nexus/pages/panels/UtilitiesPanel.qml:68", + "shipped Nexus control (StepperRow)" + ] + ] + }, + { + "name": "setUtilitiesEnabled", + "path": "utilities.enabled", + "group": "utilities", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:76", + "CONFIG declaration: bool enabled = true" + ], + [ + "shell/modules/nexus/pages/panels/UtilitiesPanel.qml:29", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setUtilitiesHoverThickness", + "path": "utilities.hoverThickness", + "group": "utilities", + "kind": "int", + "default": 10, + "minimum": 1, + "maximum": 100, + "step": 1, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:79", + "CONFIG declaration: int hoverThickness = 10" + ], + [ + "shell/modules/nexus/pages/panels/UtilitiesPanel.qml:44", + "shipped Nexus control (StepperRow)" + ] + ] + }, + { + "name": "setUtilitiesHoverWidth", + "path": "utilities.hoverWidth", + "group": "utilities", + "kind": "int", + "default": 50, + "minimum": 10, + "maximum": 100, + "step": 5, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:80", + "CONFIG declaration: int hoverWidth = 50" + ], + [ + "shell/modules/nexus/pages/panels/UtilitiesPanel.qml:56", + "shipped Nexus control (StepperRow)" + ] + ] + }, + { + "name": "setUtilitiesShowOnHover", + "path": "utilities.showOnHover", + "group": "utilities", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:77", + "CONFIG declaration: bool showOnHover = true" + ], + [ + "shell/modules/nexus/pages/panels/UtilitiesPanel.qml:36", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setSoundsCameraClick", + "path": "audio.sounds.cameraClick", + "group": "audio", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": true, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/audioconfig.hpp:12", + "CONFIG declaration: bool cameraClick = true" + ], + [ + "shell/modules/nexus/pages/audio/SoundEffectsPage.qml:46", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setSoundsChargingStarted", + "path": "audio.sounds.chargingStarted", + "group": "audio", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": true, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/audioconfig.hpp:13", + "CONFIG declaration: bool chargingStarted = true" + ], + [ + "shell/modules/nexus/pages/audio/SoundEffectsPage.qml:66", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setSoundsEffectTick", + "path": "audio.sounds.effectTick", + "group": "audio", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": true, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/audioconfig.hpp:14", + "CONFIG declaration: bool effectTick = true" + ], + [ + "shell/modules/nexus/pages/audio/SoundEffectsPage.qml:54", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setSoundsEnabled", + "path": "audio.sounds.enabled", + "group": "audio", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": true, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/audioconfig.hpp:11", + "CONFIG declaration: bool enabled = true" + ], + [ + "shell/modules/nexus/pages/audio/SoundEffectsPage.qml:24", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setSoundsLock", + "path": "audio.sounds.lock", + "group": "audio", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": true, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/audioconfig.hpp:15", + "CONFIG declaration: bool lock = true" + ], + [ + "shell/modules/nexus/pages/audio/SoundEffectsPage.qml:74", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setSoundsLowBattery", + "path": "audio.sounds.lowBattery", + "group": "audio", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": true, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/audioconfig.hpp:17", + "CONFIG declaration: bool lowBattery = true" + ], + [ + "shell/modules/nexus/pages/audio/SoundEffectsPage.qml:88", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setSoundsNotificationVolume", + "path": "audio.sounds.notificationVolume", + "group": "audio", + "kind": "float", + "default": 1.0, + "minimum": 0, + "maximum": 1, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": true, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/audioconfig.hpp:22", + "CONFIG declaration: qreal notificationVolume = 1.0" + ], + [ + "shell/modules/nexus/pages/services/ToastPreferencesPage.qml:80", + "shipped Nexus control (SliderRow)" + ] + ] + }, + { + "name": "setSoundsScreenRecord", + "path": "audio.sounds.screenRecord", + "group": "audio", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": true, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/audioconfig.hpp:18", + "CONFIG declaration: bool screenRecord = true" + ], + [ + "shell/modules/nexus/pages/audio/SoundEffectsPage.qml:95", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setSoundsSfxVolume", + "path": "audio.sounds.sfxVolume", + "group": "audio", + "kind": "float", + "default": 1.0, + "minimum": 0, + "maximum": 1, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": true, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/audioconfig.hpp:21", + "CONFIG declaration: qreal sfxVolume = 1.0" + ], + [ + "shell/modules/nexus/pages/audio/SoundEffectsPage.qml:31", + "shipped Nexus control (SliderRow)" + ] + ] + }, + { + "name": "setSoundsUnlock", + "path": "audio.sounds.unlock", + "group": "audio", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": true, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/audioconfig.hpp:16", + "CONFIG declaration: bool unlock = true" + ], + [ + "shell/modules/nexus/pages/audio/SoundEffectsPage.qml:81", + "shipped Nexus control (ToggleRow)" + ] + ] + } + ], + "not_exposed": [ + { + "path": "ai.activeClaudeAccount", + "reason": "[ai-provider-selfconfig] AI-provider self-configuration (models/providers/accounts): the assistant must not reconfigure its own plumbing; the Nexus AiSettingsPage owns these" + }, + { + "path": "ai.activeOllamaModel", + "reason": "[ai-provider-selfconfig] AI-provider self-configuration (models/providers/accounts): the assistant must not reconfigure its own plumbing; the Nexus AiSettingsPage owns these" + }, + { + "path": "ai.activeProvider", + "reason": "[ai-provider-selfconfig] AI-provider self-configuration (models/providers/accounts): the assistant must not reconfigure its own plumbing; the Nexus AiSettingsPage owns these" + }, + { + "path": "ai.anthropicApiKey", + "reason": "[ai-credentials] plaintext credential — never exposed as a tool" + }, + { + "path": "ai.anthropicUrl", + "reason": "[ai-endpoints] network endpoint the shell sends data to — outside the settings tool surface" + }, + { + "path": "ai.claudeAccountsJson", + "reason": "[ai-internal-state] internally-managed state blob" + }, + { + "path": "ai.claudeCodeBin", + "reason": "[ai-executables] binary/path the shell executes — never a settings tool" + }, + { + "path": "ai.claudeCodeEffort", + "reason": "[ai-provider-selfconfig] AI-provider self-configuration (models/providers/accounts): the assistant must not reconfigure its own plumbing; the Nexus AiSettingsPage owns these" + }, + { + "path": "ai.claudeCodeSkipPermissions", + "reason": "[ai-provider-selfconfig] AI-provider self-configuration (models/providers/accounts): the assistant must not reconfigure its own plumbing; the Nexus AiSettingsPage owns these" + }, + { + "path": "ai.defaultClaudeCodeModel", + "reason": "[ai-provider-selfconfig] AI-provider self-configuration (models/providers/accounts): the assistant must not reconfigure its own plumbing; the Nexus AiSettingsPage owns these" + }, + { + "path": "ai.defaultClaudeModel", + "reason": "[ai-provider-selfconfig] AI-provider self-configuration (models/providers/accounts): the assistant must not reconfigure its own plumbing; the Nexus AiSettingsPage owns these" + }, + { + "path": "ai.defaultGeminiModel", + "reason": "[ai-provider-selfconfig] AI-provider self-configuration (models/providers/accounts): the assistant must not reconfigure its own plumbing; the Nexus AiSettingsPage owns these" + }, + { + "path": "ai.defaultOllamaModel", + "reason": "[ai-provider-selfconfig] AI-provider self-configuration (models/providers/accounts): the assistant must not reconfigure its own plumbing; the Nexus AiSettingsPage owns these" + }, + { + "path": "ai.defaultOpenaiModel", + "reason": "[ai-provider-selfconfig] AI-provider self-configuration (models/providers/accounts): the assistant must not reconfigure its own plumbing; the Nexus AiSettingsPage owns these" + }, + { + "path": "ai.defaultOpencodeGoModel", + "reason": "[ai-provider-selfconfig] AI-provider self-configuration (models/providers/accounts): the assistant must not reconfigure its own plumbing; the Nexus AiSettingsPage owns these" + }, + { + "path": "ai.defaultOpencodeModel", + "reason": "[ai-provider-selfconfig] AI-provider self-configuration (models/providers/accounts): the assistant must not reconfigure its own plumbing; the Nexus AiSettingsPage owns these" + }, + { + "path": "ai.defaultOpenrouterModel", + "reason": "[ai-provider-selfconfig] AI-provider self-configuration (models/providers/accounts): the assistant must not reconfigure its own plumbing; the Nexus AiSettingsPage owns these" + }, + { + "path": "ai.defaultProvider", + "reason": "[ai-provider-selfconfig] AI-provider self-configuration (models/providers/accounts): the assistant must not reconfigure its own plumbing; the Nexus AiSettingsPage owns these" + }, + { + "path": "ai.enableAiAssistant", + "reason": "[ai-provider-selfconfig] AI-provider self-configuration (models/providers/accounts): the assistant must not reconfigure its own plumbing; the Nexus AiSettingsPage owns these" + }, + { + "path": "ai.enableCelestialMode", + "reason": "[ai-provider-selfconfig] AI-provider self-configuration (models/providers/accounts): the assistant must not reconfigure its own plumbing; the Nexus AiSettingsPage owns these" + }, + { + "path": "ai.enableClaude", + "reason": "[ai-provider-selfconfig] AI-provider self-configuration (models/providers/accounts): the assistant must not reconfigure its own plumbing; the Nexus AiSettingsPage owns these" + }, + { + "path": "ai.enableClaudeCode", + "reason": "[ai-provider-selfconfig] AI-provider self-configuration (models/providers/accounts): the assistant must not reconfigure its own plumbing; the Nexus AiSettingsPage owns these" + }, + { + "path": "ai.enableGemini", + "reason": "[ai-provider-selfconfig] AI-provider self-configuration (models/providers/accounts): the assistant must not reconfigure its own plumbing; the Nexus AiSettingsPage owns these" + }, + { + "path": "ai.enableOllama", + "reason": "[ai-provider-selfconfig] AI-provider self-configuration (models/providers/accounts): the assistant must not reconfigure its own plumbing; the Nexus AiSettingsPage owns these" + }, + { + "path": "ai.enableOpenai", + "reason": "[ai-provider-selfconfig] AI-provider self-configuration (models/providers/accounts): the assistant must not reconfigure its own plumbing; the Nexus AiSettingsPage owns these" + }, + { + "path": "ai.enableOpencode", + "reason": "[ai-provider-selfconfig] AI-provider self-configuration (models/providers/accounts): the assistant must not reconfigure its own plumbing; the Nexus AiSettingsPage owns these" + }, + { + "path": "ai.enableOpencodeGo", + "reason": "[ai-provider-selfconfig] AI-provider self-configuration (models/providers/accounts): the assistant must not reconfigure its own plumbing; the Nexus AiSettingsPage owns these" + }, + { + "path": "ai.enableOpenrouter", + "reason": "[ai-provider-selfconfig] AI-provider self-configuration (models/providers/accounts): the assistant must not reconfigure its own plumbing; the Nexus AiSettingsPage owns these" + }, + { + "path": "ai.geminiApiKey", + "reason": "[ai-credentials] plaintext credential — never exposed as a tool" + }, + { + "path": "ai.geminiUrl", + "reason": "[ai-endpoints] network endpoint the shell sends data to — outside the settings tool surface" + }, + { + "path": "ai.loginTerminal", + "reason": "[ai-executables] binary/path the shell executes — never a settings tool" + }, + { + "path": "ai.ollamaHistoryJson", + "reason": "[ai-internal-state] internally-managed state blob" + }, + { + "path": "ai.ollamaModel", + "reason": "[ai-provider-selfconfig] AI-provider self-configuration (models/providers/accounts): the assistant must not reconfigure its own plumbing; the Nexus AiSettingsPage owns these" + }, + { + "path": "ai.ollamaUrl", + "reason": "[ai-endpoints] network endpoint the shell sends data to — outside the settings tool surface" + }, + { + "path": "ai.openaiApiKey", + "reason": "[ai-credentials] plaintext credential — never exposed as a tool" + }, + { + "path": "ai.openaiUrl", + "reason": "[ai-endpoints] network endpoint the shell sends data to — outside the settings tool surface" + }, + { + "path": "ai.opencodeApiKey", + "reason": "[ai-credentials] plaintext credential — never exposed as a tool" + }, + { + "path": "ai.opencodeGoUrl", + "reason": "[ai-endpoints] network endpoint the shell sends data to — outside the settings tool surface" + }, + { + "path": "ai.opencodeUrl", + "reason": "[ai-endpoints] network endpoint the shell sends data to — outside the settings tool surface" + }, + { + "path": "ai.openrouterApiKey", + "reason": "[ai-credentials] plaintext credential — never exposed as a tool" + }, + { + "path": "ai.openrouterUrl", + "reason": "[ai-endpoints] network endpoint the shell sends data to — outside the settings tool surface" + }, + { + "path": "ai.orionModel", + "reason": "[ai-provider-selfconfig] AI-provider self-configuration (models/providers/accounts): the assistant must not reconfigure its own plumbing; the Nexus AiSettingsPage owns these" + }, + { + "path": "ai.saveChatHistory", + "reason": "[ai-provider-selfconfig] AI-provider self-configuration (models/providers/accounts): the assistant must not reconfigure its own plumbing; the Nexus AiSettingsPage owns these" + }, + { + "path": "ai.showCaelestiaMode", + "reason": "[ai-provider-selfconfig] AI-provider self-configuration (models/providers/accounts): the assistant must not reconfigure its own plumbing; the Nexus AiSettingsPage owns these" + }, + { + "path": "ai.showNews", + "reason": "[ai-provider-selfconfig] AI-provider self-configuration (models/providers/accounts): the assistant must not reconfigure its own plumbing; the Nexus AiSettingsPage owns these" + }, + { + "path": "ai.snapToDefaultOllama", + "reason": "[ai-provider-selfconfig] AI-provider self-configuration (models/providers/accounts): the assistant must not reconfigure its own plumbing; the Nexus AiSettingsPage owns these" + }, + { + "path": "appearance.animDurations.expressiveDefaultEffects", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "appearance.animDurations.expressiveDefaultSpatial", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "appearance.animDurations.expressiveFastEffects", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "appearance.animDurations.expressiveFastSpatial", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "appearance.animDurations.expressiveSlowEffects", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "appearance.animDurations.expressiveSlowSpatial", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "appearance.animDurations.extraLarge", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "appearance.animDurations.large", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "appearance.animDurations.normal", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "appearance.animDurations.small", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "appearance.curves.emphasized", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "appearance.curves.emphasizedAccel", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "appearance.curves.emphasizedDecel", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "appearance.curves.expressiveDefaultEffects", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "appearance.curves.expressiveDefaultSpatial", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "appearance.curves.expressiveFastEffects", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "appearance.curves.expressiveFastSpatial", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "appearance.curves.expressiveSlowEffects", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "appearance.curves.expressiveSlowSpatial", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "appearance.curves.standard", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "appearance.curves.standardAccel", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "appearance.curves.standardDecel", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "appearance.font.clock", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "appearance.font.icon.family", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "appearance.font.workspaces", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "appearance.fontSize.extraLarge", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "appearance.fontSize.large", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "appearance.fontSize.larger", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "appearance.fontSize.monoLarge", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "appearance.fontSize.monoMedium", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "appearance.fontSize.monoSmall", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "appearance.fontSize.normal", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "appearance.fontSize.small", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "appearance.fontSize.smaller", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "appearance.padding.extraExtraLarge", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "appearance.padding.extraLarge", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "appearance.padding.extraLargeIncreased", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "appearance.padding.extraSmall", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "appearance.padding.large", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "appearance.padding.largeIncreased", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "appearance.padding.medium", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "appearance.padding.small", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "appearance.rounding.extraExtraLarge", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "appearance.rounding.extraLarge", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "appearance.rounding.extraLargeIncreased", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "appearance.rounding.extraSmall", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "appearance.rounding.full", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "appearance.rounding.large", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "appearance.rounding.largeIncreased", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "appearance.rounding.medium", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "appearance.rounding.small", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "appearance.spacing.extraExtraLarge", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "appearance.spacing.extraLarge", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "appearance.spacing.extraLargeIncreased", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "appearance.spacing.extraSmall", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "appearance.spacing.large", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "appearance.spacing.largeIncreased", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "appearance.spacing.medium", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "appearance.spacing.small", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "audio.sounds.disabledNotifApps", + "reason": "[complex-control] the shipped control is 'chips list (StyledInputField add/remove)', not a scalar setter" + }, + { + "path": "audio.sounds.notificationSound", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "background.desktopClock.background.blur", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "background.desktopClock.background.enabled", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "background.desktopClock.background.opacity", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "background.desktopClock.shadow.blur", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "background.desktopClock.shadow.enabled", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "background.desktopClock.shadow.opacity", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "background.desktopLyrics.background.blur", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "background.desktopLyrics.background.enabled", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "background.desktopLyrics.background.opacity", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "background.desktopLyrics.shadow.blur", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "background.desktopLyrics.shadow.enabled", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "background.desktopLyrics.shadow.opacity", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "background.enabled", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "bar.clock.centerClock", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "bar.dock.monitorCenter", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "bar.dock.pinnedApps", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "bar.entries", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "bar.excludedScreens", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "bar.greeter.afternoonGif", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "bar.greeter.afternoonText", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "bar.greeter.eveningGif", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "bar.greeter.eveningText", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "bar.greeter.morningGif", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "bar.greeter.morningText", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "bar.greeter.nightGif", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "bar.greeter.nightText", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "bar.greeter.slideshowFolders", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "bar.greeter.slideshowGifs", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "bar.greeter.slideshowIcon", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "bar.greeter.slideshowText", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "bar.perElementFontScale", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "bar.perElementPreviewScale", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "bar.performance.showText", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "bar.popouts.clock", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "bar.previewFontScales.audio", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "bar.previewFontScales.battery", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "bar.previewFontScales.bluetooth", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "bar.previewFontScales.clock", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "bar.previewFontScales.dock", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "bar.previewFontScales.github", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "bar.previewFontScales.greeter", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "bar.previewFontScales.kblayout", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "bar.previewFontScales.lockStatus", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "bar.previewFontScales.network", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "bar.previewFontScales.notifications", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "bar.previewFontScales.peripheralBattery", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "bar.previewFontScales.trayMenu", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "bar.previewFontScales.wirelessPassword", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "bar.previewScales.clock", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "bar.previewScales.kblayout", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "bar.status.peripheralBatteryExcluded", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "bar.status.showAudio", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "bar.status.showBattery", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "bar.status.showBluetooth", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "bar.status.showKbLayout", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "bar.status.showLockStatus", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "bar.status.showMicrophone", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "bar.status.showNetwork", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "bar.status.showNightLight", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "bar.status.showNotifications", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "bar.status.showPeripheralBattery", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "bar.tray.hiddenIcons", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "bar.workspaces.activeLabel", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "bar.workspaces.capitalisation", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "bar.workspaces.ignoredTags", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "bar.workspaces.label", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "bar.workspaces.monitorCenter", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "bar.workspaces.occupiedLabel", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "bar.workspaces.perMonitorWorkspaces", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "bar.workspaces.useIcon", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "dashboard.profilePicShape", + "reason": "[dynamic-enum] the SelectRow's value list is dynamic, numeric-coded without per-value ids, or not a frozen enumeration" + }, + { + "path": "dashboard.showHyprlandSplash", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "enabled", + "reason": "[master-switch] ConfigRoot master switch — a bad write disables the entire shell" + }, + { + "path": "general.apps.audio", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "general.apps.explorer", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "general.apps.playback", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "general.apps.terminal", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "general.caelestiaMode", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "general.debugLogs", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "general.krohnkiteEnabled", + "reason": "[kwinrc-companion-writes] the shipped Nexus control writes companion kwinrc keys (or installs a kwin script) alongside this key; a shell.json-only write would desync the two stores" + }, + { + "path": "general.krohnkiteLastLayout", + "reason": "[kwinrc-companion-writes] the shipped Nexus control writes companion kwinrc keys (or installs a kwin script) alongside this key; a shell.json-only write would desync the two stores" + }, + { + "path": "general.language", + "reason": "[dynamic-enum] the SelectRow's value list is dynamic, numeric-coded without per-value ids, or not a frozen enumeration" + }, + { + "path": "general.logo", + "reason": "[free-string] free-form string with no frozen enumeration" + }, + { + "path": "general.magicLampEnabled", + "reason": "[kwinrc-companion-writes] the shipped Nexus control writes companion kwinrc keys (or installs a kwin script) alongside this key; a shell.json-only write would desync the two stores" + }, + { + "path": "general.mediaGifSpeedAdjustment", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "general.sessionGifSpeed", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "general.showOverFullscreen", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "launcher.actionPrefix", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "launcher.favouriteApps", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "launcher.favouriteClips", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "launcher.favouriteEmojis", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "launcher.hiddenApps", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "launcher.specialPrefix", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "launcher.useFuzzy.clipboard", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "launcher.useFuzzy.emoji", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "lock.enableHowdy", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "lock.maxHowdyTries", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "lock.profilePicShape", + "reason": "[dynamic-enum] the SelectRow's value list is dynamic, numeric-coded without per-value ids, or not a frozen enumeration" + }, + { + "path": "lock.triggerHowdyOnWake", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "nexus.maxNetworksShown", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "nexus.wallpapersPerRow", + "reason": "[complex-control] the shipped control is '(no control; read-only Repeater model)', not a scalar setter" + }, + { + "path": "paths.cacheDir", + "reason": "[filesystem-paths] filesystem path redirection; the wallpaper/CLI surface owns this" + }, + { + "path": "paths.lockNoNotifsPic", + "reason": "[filesystem-paths] filesystem path redirection; the wallpaper/CLI surface owns this" + }, + { + "path": "paths.lyricsDir", + "reason": "[filesystem-paths] filesystem path redirection; the wallpaper/CLI surface owns this" + }, + { + "path": "paths.mediaGif", + "reason": "[filesystem-paths] filesystem path redirection; the wallpaper/CLI surface owns this" + }, + { + "path": "paths.noNotifsPic", + "reason": "[filesystem-paths] filesystem path redirection; the wallpaper/CLI surface owns this" + }, + { + "path": "paths.sessionGif", + "reason": "[filesystem-paths] filesystem path redirection; the wallpaper/CLI surface owns this" + }, + { + "path": "paths.wallpaperDir", + "reason": "[filesystem-paths] filesystem path redirection; the wallpaper/CLI surface owns this" + }, + { + "path": "services.arpcAppName", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "services.arpcClientId", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "services.arpcDetails", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "services.arpcLargeImage", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "services.arpcSmallImage", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "services.arpcState", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "services.arpcSteamBlacklist", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "services.arpcTargetWindowLabels", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "services.arpcTargetWindows", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "services.autoSchemeDarkTime", + "reason": "[string-stepper] the shipped stepper stores a transformed string (e.g. HH:MM); not a passthrough scalar" + }, + { + "path": "services.autoSchemeLightTime", + "reason": "[string-stepper] the shipped stepper stores a transformed string (e.g. HH:MM); not a passthrough scalar" + }, + { + "path": "services.bluetoothAutoReconnectDevices", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "services.defaultPlayer", + "reason": "[dynamic-enum] the SelectRow's value list is dynamic, numeric-coded without per-value ids, or not a frozen enumeration" + }, + { + "path": "services.lyricsBackend", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "services.useFahrenheit", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "services.useFahrenheitPerformance", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "services.useSystemd", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "services.useTwelveHourClock", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "services.wallhavenApiKey", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "services.weatherLocation", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "session.commands.hibernate", + "reason": "[session-commands] command lists the session menu executes — never a settings tool" + }, + { + "path": "session.commands.logout", + "reason": "[session-commands] command lists the session menu executes — never a settings tool" + }, + { + "path": "session.commands.reboot", + "reason": "[session-commands] command lists the session menu executes — never a settings tool" + }, + { + "path": "session.commands.shutdown", + "reason": "[session-commands] command lists the session menu executes — never a settings tool" + }, + { + "path": "session.icons.hibernate", + "reason": "[session-icons] icon-name strings with no shipped range/format control" + }, + { + "path": "session.icons.logout", + "reason": "[session-icons] icon-name strings with no shipped range/format control" + }, + { + "path": "session.icons.reboot", + "reason": "[session-icons] icon-name strings with no shipped range/format control" + }, + { + "path": "session.icons.shutdown", + "reason": "[session-icons] icon-name strings with no shipped range/format control" + }, + { + "path": "sizes.bar.audioWidth", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "sizes.bar.batteryWidth", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "sizes.bar.innerWidth", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "sizes.bar.kbLayoutWidth", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "sizes.bar.networkWidth", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "sizes.bar.trayMenuWidth", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "sizes.bar.windowPreviewSize", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "sizes.dashboard.dateTimeWidth", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "sizes.dashboard.logoSize", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "sizes.dashboard.mediaCoverArtSize", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "sizes.dashboard.mediaProgressSweep", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "sizes.dashboard.mediaProgressThickness", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "sizes.dashboard.mediaSectionWidth", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "sizes.dashboard.mediaTabHeight", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "sizes.dashboard.mediaTabWidth", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "sizes.dashboard.mediaWidth", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "sizes.dashboard.perfBattHeight", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "sizes.dashboard.perfBattWidth", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "sizes.dashboard.perfBattWidthSingle", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "sizes.dashboard.perfHeroCardWidth", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "sizes.dashboard.perfNetworkCardHeight", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "sizes.dashboard.perfNetworkCardWidth", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "sizes.dashboard.perfPlaceholderWidth", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "sizes.dashboard.perfStorageTextWidth", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "sizes.dashboard.perfUsageShapeSize", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "sizes.dashboard.resourceProgressThickness", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "sizes.dashboard.tabIndicatorHeight", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "sizes.dashboard.tabIndicatorSpacing", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "sizes.dashboard.uptimeSize", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "sizes.dashboard.userWidth", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "sizes.dashboard.weatherWidth", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "sizes.launcher.browseHeight", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "sizes.launcher.browseMinHeight", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "sizes.launcher.browseSidebarWidth", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "sizes.launcher.browseTileHeight", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "sizes.launcher.browseTileWidth", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "sizes.launcher.browseWidth", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "sizes.launcher.itemHeight", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "sizes.launcher.itemWidth", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "sizes.launcher.wallpaperHeight", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "sizes.launcher.wallpaperWidth", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "sizes.launcher.windowSwitcherHeight", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "sizes.launcher.windowSwitcherWidth", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "sizes.lock.centerWidth", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "sizes.lock.fetch3LinesHeight", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "sizes.lock.fetch4LinesHeight", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "sizes.lock.forecastItemWidth", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "sizes.lock.heightMult", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "sizes.lock.largeFontWidth", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "sizes.lock.largeLogoWidth", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "sizes.lock.ratio", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "sizes.lock.showColourBoxRowHeight", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "sizes.lock.showForecastHeight", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "sizes.lock.showWeatherDetailsHeight", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "sizes.nexus.heightMult", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "sizes.nexus.maxContentWidth", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "sizes.nexus.maxDialogHeight", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "sizes.nexus.maxDialogWidth", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "sizes.nexus.maxNavWidth", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "sizes.nexus.maxPopupHeight", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "sizes.nexus.minHeight", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "sizes.nexus.minPopupHeight", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "sizes.nexus.minWidth", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "sizes.nexus.networkShowEthDetailWidth", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "sizes.nexus.networkShowVpnDetailWidth", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "sizes.nexus.popupWidth", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "sizes.nexus.ratio", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "sizes.nexus.smallTextFieldWidth", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "sizes.nexus.textFieldWidth", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "sizes.notifs.badge", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "sizes.notifs.image", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "sizes.notifs.width", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "sizes.osd.sliderHeight", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "sizes.osd.sliderWidth", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "sizes.session.button", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "sizes.sidebar.width", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "sizes.utilities.toastWidth", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "sizes.utilities.width", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "sizes.winfo.detailsWidth", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "sizes.winfo.heightMult", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "tabSwitch.enabled", + "reason": "[kwinrc-companion-writes] the shipped Nexus control writes companion kwinrc keys (or installs a kwin script) alongside this key; a shell.json-only write would desync the two stores" + }, + { + "path": "tabSwitch.layout", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "utilities.gameMode.autoEnableRegexes", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "utilities.quickToggles", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "utilities.toasts.audioInputChanged", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "utilities.toasts.audioOutputChanged", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "utilities.toasts.capsLockChanged", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "utilities.toasts.clipboardChanged", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "utilities.toasts.dndChanged", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "utilities.toasts.kbLayoutChanged", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "utilities.toasts.kbLimit", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "utilities.toasts.nowPlaying", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "utilities.toasts.numLockChanged", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "utilities.toasts.vpnChanged", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "utilities.vpn.enabled", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "utilities.vpn.selectedProvider", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + } + ], + "presets": [ + { + "name": "compact", + "label": "Compact", + "description": "Smaller dock icons and tighter spacing/padding/rounding — the same keys the Nexus steppers expose.", + "calls": [ + { + "tool": "setDockIconSize", + "value": 24 + }, + { + "tool": "setSpacingScale", + "value": 0.8 + }, + { + "tool": "setPaddingScale", + "value": 0.8 + }, + { + "tool": "setRoundingScale", + "value": 0.8 + } + ] + }, + { + "name": "minimal", + "label": "Minimal", + "description": "Issue #120's own example direction: smaller bar and dock, lower rounding, faster animations, badges and previews off.", + "calls": [ + { + "tool": "setBarScale", + "value": 0.7 + }, + { + "tool": "setDockIconSize", + "value": 20 + }, + { + "tool": "setRoundingScale", + "value": 0.5 + }, + { + "tool": "setAnimationSpeed", + "value": 0.5 + }, + { + "tool": "setSpacingScale", + "value": 0.7 + }, + { + "tool": "setDockBadges", + "value": false + }, + { + "tool": "setLivePreviews", + "value": false + } + ] + }, + { + "name": "gaming", + "label": "Gaming", + "description": "Snappier shell, no blur/transparency compositing, no popup notifications. (Game Mode itself is a service toggle, not a shell.json scalar — this bundle is the config-side reduction only.)", + "calls": [ + { + "tool": "setBlurEnabled", + "value": false + }, + { + "tool": "setTransparencyEnabled", + "value": false + }, + { + "tool": "setAnimationSpeed", + "value": 0.25 + }, + { + "tool": "setNotifsMaxPopups", + "value": 0 + } + ] + }, + { + "name": "battery-saver", + "label": "Battery saver", + "description": "Reduce compositing and background work: blur, ambient glow and wallpaper recolour off, animations fast.", + "calls": [ + { + "tool": "setBlurEnabled", + "value": false + }, + { + "tool": "setAnimationSpeed", + "value": 0.25 + }, + { + "tool": "setAmbientColor", + "value": false + }, + { + "tool": "setWallpaperRecolor", + "value": false + } + ] + }, + { + "name": "macos-like", + "label": "More like macOS", + "description": "Always-visible bottom dock with larger icons, rounder corners, roomier spacing and badges on — the keys the shipped controls already expose.", + "calls": [ + { + "tool": "setBarPosition", + "value": "bottom" + }, + { + "tool": "setBarPersistent", + "value": true + }, + { + "tool": "setDockIconSize", + "value": 48 + }, + { + "tool": "setRoundingScale", + "value": 1.3 + }, + { + "tool": "setSpacingScale", + "value": 1.1 + }, + { + "tool": "setPaddingScale", + "value": 1.1 + }, + { + "tool": "setAnimationSpeed", + "value": 1.0 + }, + { + "tool": "setDockBadges", + "value": true + } + ] + } + ], + "explain_rules": [ + { + "path": "appearance.blur", + "when": "appearance.blur == true and appearance.transparency.enabled == true", + "answer": "Blur is enabled because transparency is currently active and appearance.blur is on — the blur regions gate on both ({cite}).", + "cites": [ + "shell/modules/drawers/blur/BlurOffsets.qml:17" + ] + }, + { + "path": "appearance.blur", + "when": "appearance.blur == true and appearance.transparency.enabled == false", + "answer": "Blur is ON but has no effect, because transparency is currently disabled — the blur regions gate on transparency.enabled && blur together ({cite}).", + "cites": [ + "shell/modules/drawers/blur/BlurOffsets.qml:17" + ] + }, + { + "path": "appearance.transparency.enabled", + "when": "appearance.transparency.enabled == true and utilities.gameMode.disableShellTransparency == true and _gamemode == true", + "answer": "Transparency is configured ON but is currently suppressed, because Game Mode is active with 'disable shell transparency' set — the colour service gates on that pair ({cite}).", + "cites": [ + "shell/services/Colours.qml:418" + ] + }, + { + "path": "appearance.transparency.base", + "when": "appearance.transparency.base > 0 and _light == true", + "answer": "Surfaces look less transparent than the configured base opacity {appearance.transparency.base}, because light mode trims the base by 0.1 ({cite}).", + "cites": [ + "shell/services/Colours.qml:419" + ] + }, + { + "path": "appearance.pitchBlack", + "when": "appearance.pitchBlack == true", + "answer": "Surfaces are fully opaque and pure black because Pitch Black (bezel mode) is active — it forces opacity 1 ({cite1}) and #000000 surfaces ({cite2}).", + "cites": [ + "shell/modules/drawers/ContentWindow.qml:383", + "shell/modules/drawers/ContentWindow.qml:394" + ] + }, + { + "path": "overview.enableOverviewBlur", + "when": "overview.enableOverviewBlur == true and appearance.blur == false", + "answer": "The overview blur setting is ON but has no effect, because the global appearance blur is off — the overview effect gates on both ({cite}).", + "cites": [ + "shell/modules/drawers/ContentWindow.qml:374" + ] + }, + { + "path": "appearance.anim.durations.scale", + "when": "appearance.anim.durations.scale != 1", + "answer": "Animations feel {slower|faster} because the animation duration scale is currently set to {appearance.anim.durations.scale} — every duration token is multiplied by it, so lower means faster ({cite}).", + "cites": [ + "shell/plugin/src/Caelestia/Config/appearanceconfig.cpp:209" + ] + }, + { + "path": "appearance.ambientColor", + "when": "appearance.ambientColor == true and _light == true", + "answer": "The ambient glow is configured ON but is currently hidden, because ambient glow only renders in dark mode — it gates on ambientColor && !light ({cite}).", + "cites": [ + "shell/components/effects/AmbientGlow.qml:34" + ] + }, + { + "path": "bar.persistent", + "when": "bar.persistent == false", + "answer": "The bar hides because bar persistence is currently off — a non-persistent bar dodges or auto-hides instead of staying put ({cite}).", + "cites": [ + "shell/modules/bar/BarWrapper.qml:62" + ] + }, + { + "path": "bar.dodgeWindows", + "when": "bar.dodgeWindows == true and bar.persistent == false", + "answer": "Window dodging has no effect, because dodge mode requires a persistent bar — the dodge gate is dodgeWindows && persistent ({cite}).", + "cites": [ + "shell/modules/bar/BarWrapper.qml:27" + ] + }, + { + "path": "bar.scale", + "when": "bar.scale < 0.6", + "answer": "The bar is not as small as asked: the effective bar scale is floored at 0.6 ({cite}); the configured value is {bar.scale}.", + "cites": [ + "shell/modules/bar/BarWrapper.qml:24" + ] + } + ] +} diff --git a/plugins/caelestia-assistant/assistant/bin/caelestia-assist b/plugins/caelestia-assistant/assistant/bin/caelestia-assist new file mode 100755 index 0000000..a4e33d4 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/bin/caelestia-assist @@ -0,0 +1,27 @@ +#!/usr/bin/env bash +# caelestia-assist - on-device assistant for caelestia-kde. +# +# Routes to every assistant module (see `caelestia-assist --help`). Nothing it +# runs executes commands, touches the network, or edits config files, except +# the explicitly gated writes documented by each module (settings --apply, +# issue draft --confirm, brain ledger/state files). +# +# Usage: +# caelestia-assist diagnose diagnose text from a file +# cat journal.log | caelestia-assist diagnose - +# caelestia-assist selfcheck validate rules + import policy +# caelestia-assist brain organize ~/notes lean intelligence layer +# echo '{"op":"ledger_list"}' | caelestia-assist api + +set -euo pipefail + +SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)" +REPO_ROOT="$(cd -- "$SCRIPT_DIR/../.." && pwd)" + +if ! command -v python3 >/dev/null 2>&1; then + echo "caelestia-assist: python3 is required" >&2 + exit 1 +fi + +export PYTHONPATH="${REPO_ROOT}${PYTHONPATH:+:${PYTHONPATH}}" +exec python3 -m assistant.hub "$@" diff --git a/plugins/caelestia-assistant/metadata.json b/plugins/caelestia-assistant/metadata.json new file mode 100644 index 0000000..19c1f8f --- /dev/null +++ b/plugins/caelestia-assistant/metadata.json @@ -0,0 +1,23 @@ +{ + "id": "caelestia-assistant", + "name": "Caelestia Assistant", + "description": "Offline-first assistant for the Caelestia shell: deterministic diagnostics, learned routing, natural-language settings editing, stream scanning, and a consent-gated agent. Python stdlib only; ships optional Quickshell sidebar/services integration surfaces for the shell.", + "version": "0.1.0", + "type": "quickshell", + "author": { + "name": "0x0nYx", + "url": "https://github.com/0x0nYx" + }, + "license": "GPL-3.0-or-later", + "keywords": [ + "assistant", + "ai", + "diagnostics", + "settings", + "agent", + "cli", + "offline" + ], + "homepage": "https://github.com/ladybug-me/caelestia-kde", + "repository": "https://github.com/0x0nYx/caelestia-assistant" +} diff --git a/plugins/caelestia-assistant/pyproject.toml b/plugins/caelestia-assistant/pyproject.toml new file mode 100644 index 0000000..8e71b79 --- /dev/null +++ b/plugins/caelestia-assistant/pyproject.toml @@ -0,0 +1,44 @@ +[build-system] +requires = ["setuptools>=68"] +build-backend = "setuptools.build_meta" + +[project] +name = "caelestia-assistant" +# ONE version source: assistant/__init__.__version__ (0.1.0). pyproject +# no longer carries its own copy — the two disagreed (0.2.0 vs 0.1.0) +# and the package attribute wins. +dynamic = ["version"] +description = "Offline-first, no-LLM intelligence core for caelestia-kde — deterministic diagnostics, learned routing, natural-language settings (issue #120), stream scanning, and a consent-gated agent, in Python stdlib only. Also ships the optional in-shell AI sidebar (shell/), an opt-in, user-keyed cloud chat tier used strictly as a fallback for requests outside the local ontology — every state-changing tool call it can trigger goes through a validated allow-list, preview-and-confirm gate." +readme = "README.md" +requires-python = ">=3.12" +license = { text = "GPL-3.0-or-later" } +authors = [{ name = "0x0nYx" }] +keywords = ["kde", "quickshell", "caelestia", "assistant", "offline", "agent"] +classifiers = [ + "Environment :: Console", + "Intended Audience :: End Users/Desktop", + "License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)", + "Operating System :: POSIX :: Linux", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", + "Topic :: Utilities", +] +dependencies = [] + +[project.optional-dependencies] +# the extras tier: never required, every accelerator has an identical- +# result pure-Python fallback (pinned by tests) +accelerate = ["numpy>=1.26"] +encode = ["onnxruntime>=1.17"] +all = ["numpy>=1.26", "onnxruntime>=1.17"] + +[project.scripts] +caelestia-assist = "assistant.hub:_run" + +[tool.setuptools.dynamic] +version = { attr = "assistant.__version__" } + +[tool.setuptools.packages.find] +include = ["assistant*"] +exclude = ["assistant/data/corpus", "assistant/data/index"] From 3451c49422dfd92052e03b7ea8665172cf69f2eb Mon Sep 17 00:00:00 2001 From: 0x0nYx <0x0nYx@users.noreply.github.com> Date: Fri, 9 Oct 2026 12:18:54 +0000 Subject: [PATCH 03/10] feat(assistant): capability package foundation: guard, dedupe, devflow, issues, scan (migration chunk 2/12) Zero-dependency capability tier: the capability package marker, its manifest registry, and the guard (memory pressure), dedupe, devflow, issues and scan capabilities. These import only the capability package itself, so they form a self-consistent stratum. (graph/ lands later: its query layer imports genius.) Chunk contents (26 files): - assistant/capabilities/__init__.py - assistant/capabilities/_registry.py - assistant/capabilities/dedupe/__init__.py - assistant/capabilities/dedupe/manifest.py - assistant/capabilities/dedupe/scan.py - assistant/capabilities/devflow/__init__.py - assistant/capabilities/devflow/__main__.py - assistant/capabilities/devflow/diffstat.py - assistant/capabilities/devflow/manifest.py - assistant/capabilities/devflow/risk.py - assistant/capabilities/devflow/todo.py - assistant/capabilities/guard/__init__.py - ... and 14 more Source: 0x0nYx/caelestia-assistant@2c193e7 (main, v0.1) Faithfulness: byte-identical copy (sha256-verified in the migration audit; only metadata.json / README.md are plugin-store scaffolding, and .caelestia-audit-ignore documents scanner false positives). Safety audit: 0 errors; 14 line-level findings documented in .caelestia-audit-ignore (string vocabularies / rulepack prose / test assertion targets / opt-in provider calls - nothing executes). Store CI: validate.py OK - check_safety.py OK - check_scope.py OK. Next chunk: plugin/caelestia-assistant/03-core-nlu-foundation --- .../assistant/capabilities/__init__.py | 2 + .../assistant/capabilities/_registry.py | 47 ++ .../assistant/capabilities/dedupe/__init__.py | 4 + .../assistant/capabilities/dedupe/manifest.py | 10 + .../assistant/capabilities/dedupe/scan.py | 180 ++++++++ .../capabilities/devflow/__init__.py | 30 ++ .../capabilities/devflow/__main__.py | 75 ++++ .../capabilities/devflow/diffstat.py | 228 ++++++++++ .../capabilities/devflow/manifest.py | 10 + .../assistant/capabilities/devflow/risk.py | 190 ++++++++ .../assistant/capabilities/devflow/todo.py | 109 +++++ .../assistant/capabilities/guard/__init__.py | 3 + .../assistant/capabilities/guard/pressure.py | 131 ++++++ .../assistant/capabilities/issues/__init__.py | 33 ++ .../assistant/capabilities/issues/cli.py | 242 +++++++++++ .../assistant/capabilities/issues/manifest.py | 10 + .../assistant/capabilities/issues/template.py | 409 ++++++++++++++++++ .../assistant/capabilities/scan/__init__.py | 33 ++ .../assistant/capabilities/scan/__main__.py | 4 + .../assistant/capabilities/scan/ac.py | 124 ++++++ .../assistant/capabilities/scan/bloom.py | 70 +++ .../assistant/capabilities/scan/cli.py | 98 +++++ .../assistant/capabilities/scan/manifest.py | 10 + .../assistant/capabilities/scan/scanner.py | 165 +++++++ .../assistant/capabilities/scan/simhash.py | 204 +++++++++ .../assistant/capabilities/scan/sketch.py | 392 +++++++++++++++++ 26 files changed, 2813 insertions(+) create mode 100644 plugins/caelestia-assistant/assistant/capabilities/__init__.py create mode 100644 plugins/caelestia-assistant/assistant/capabilities/_registry.py create mode 100644 plugins/caelestia-assistant/assistant/capabilities/dedupe/__init__.py create mode 100644 plugins/caelestia-assistant/assistant/capabilities/dedupe/manifest.py create mode 100644 plugins/caelestia-assistant/assistant/capabilities/dedupe/scan.py create mode 100644 plugins/caelestia-assistant/assistant/capabilities/devflow/__init__.py create mode 100644 plugins/caelestia-assistant/assistant/capabilities/devflow/__main__.py create mode 100644 plugins/caelestia-assistant/assistant/capabilities/devflow/diffstat.py create mode 100644 plugins/caelestia-assistant/assistant/capabilities/devflow/manifest.py create mode 100644 plugins/caelestia-assistant/assistant/capabilities/devflow/risk.py create mode 100644 plugins/caelestia-assistant/assistant/capabilities/devflow/todo.py create mode 100644 plugins/caelestia-assistant/assistant/capabilities/guard/__init__.py create mode 100644 plugins/caelestia-assistant/assistant/capabilities/guard/pressure.py create mode 100755 plugins/caelestia-assistant/assistant/capabilities/issues/__init__.py create mode 100755 plugins/caelestia-assistant/assistant/capabilities/issues/cli.py create mode 100644 plugins/caelestia-assistant/assistant/capabilities/issues/manifest.py create mode 100755 plugins/caelestia-assistant/assistant/capabilities/issues/template.py create mode 100644 plugins/caelestia-assistant/assistant/capabilities/scan/__init__.py create mode 100644 plugins/caelestia-assistant/assistant/capabilities/scan/__main__.py create mode 100644 plugins/caelestia-assistant/assistant/capabilities/scan/ac.py create mode 100644 plugins/caelestia-assistant/assistant/capabilities/scan/bloom.py create mode 100644 plugins/caelestia-assistant/assistant/capabilities/scan/cli.py create mode 100644 plugins/caelestia-assistant/assistant/capabilities/scan/manifest.py create mode 100644 plugins/caelestia-assistant/assistant/capabilities/scan/scanner.py create mode 100644 plugins/caelestia-assistant/assistant/capabilities/scan/simhash.py create mode 100644 plugins/caelestia-assistant/assistant/capabilities/scan/sketch.py diff --git a/plugins/caelestia-assistant/assistant/capabilities/__init__.py b/plugins/caelestia-assistant/assistant/capabilities/__init__.py new file mode 100644 index 0000000..f503773 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/capabilities/__init__.py @@ -0,0 +1,2 @@ +"""Capability plugins: one directory per capability.""" + diff --git a/plugins/caelestia-assistant/assistant/capabilities/_registry.py b/plugins/caelestia-assistant/assistant/capabilities/_registry.py new file mode 100644 index 0000000..f486ff6 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/capabilities/_registry.py @@ -0,0 +1,47 @@ +"""Capability manifests: permissions, risk tier, ms/MB budgets. + +One manifest per capability plugin, typed by CapManifest. The loader +(``all_manifests`` / ``manifest_for``) is the only sanctioned way to +read them; budgets are advisory upper bounds for the resource governor +(Phase 4.9), enforced at the call surface, not inside the plugin. +""" +from __future__ import annotations + +from dataclasses import dataclass +from importlib import import_module +from typing import Dict, List + +__all__ = ["CapManifest", "all_manifests", "manifest_for"] + +# risk tiers, ordered by autonomy ladder (see executor.plan.Reversibility): +# read_only - runs without prompts +# journaled - runs without prompts; every write is journaled+reversible +# confirm - requires explicit confirmation per change-set +# privileged - requires confirmation + capability flag (file edit, never NL) +TIERS = ("read_only", "journaled", "confirm", "privileged") + + +@dataclass(frozen=True) +class CapManifest: + name: str + permissions: tuple # e.g. ("fs:read",) — declared capability surface + risk_tier: str # one of TIERS + latency_budget_ms: int # p95 budget for one CLI call + memory_budget_mb: int # peak RSS budget + + +_ALL = ("diagnostics", "retrieval", "generative", "issues", "settings", + "graph", "brain", "genius", "agent", "devflow", "scan", "shellkb") + + +def all_manifests() -> List[CapManifest]: + out = [] + for name in _ALL: + mod = import_module(f"assistant.capabilities.{name}.manifest") + out.append(mod.MANIFEST) + return out + + +def manifest_for(name: str) -> CapManifest: + mod = import_module(f"assistant.capabilities.{name}.manifest") + return mod.MANIFEST diff --git a/plugins/caelestia-assistant/assistant/capabilities/dedupe/__init__.py b/plugins/caelestia-assistant/assistant/capabilities/dedupe/__init__.py new file mode 100644 index 0000000..2fc025c --- /dev/null +++ b/plugins/caelestia-assistant/assistant/capabilities/dedupe/__init__.py @@ -0,0 +1,4 @@ +"""dedupe — the cleanup brain (capability 5): duplicate detection +(size -> partial hash -> full hash), last-access survival ranking, +and TTL quarantine instead of deletion. Every destructive step is a +journaled move with a restore path.""" diff --git a/plugins/caelestia-assistant/assistant/capabilities/dedupe/manifest.py b/plugins/caelestia-assistant/assistant/capabilities/dedupe/manifest.py new file mode 100644 index 0000000..bc4b578 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/capabilities/dedupe/manifest.py @@ -0,0 +1,10 @@ +"""Manifest for the dedupe capability.""" +from assistant.capabilities._registry import CapManifest + +MANIFEST = CapManifest( + name="dedupe", + permissions=("fs:read", "fs:quarantine-move-journaled"), + risk_tier="journaled", + latency_budget_ms=1500, + memory_budget_mb=40, +) diff --git a/plugins/caelestia-assistant/assistant/capabilities/dedupe/scan.py b/plugins/caelestia-assistant/assistant/capabilities/dedupe/scan.py new file mode 100644 index 0000000..7691a42 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/capabilities/dedupe/scan.py @@ -0,0 +1,180 @@ +"""dedupe.scan — duplicate detection with a three-stage funnel. + +size -> partial hash (first 4 KiB) -> full hash. Identical-result +discipline: the funnel can only ever return a SUPERSET at each stage, +so the full-hash stage decides. Deterministic ordering everywhere +(groups sorted by total size desc, members sorted by path). +""" +from __future__ import annotations + +import hashlib +import os +from pathlib import Path +from typing import Dict, List, Tuple + +__all__ = ["scan_duplicates", "survival_scores", "quarantine"] + +_PARTIAL_BYTES = 4096 + + +def _hash_file(path: Path, partial: bool = False) -> str: + h = hashlib.sha256() + with open(path, "rb") as fh: + if partial: + h.update(fh.read(_PARTIAL_BYTES)) + else: + for chunk in iter(lambda: fh.read(1 << 16), b""): + h.update(chunk) + return h.hexdigest() + + +def scan_duplicates(roots: List[str], min_size: int = 1) -> List[Dict]: + """Duplicate groups under ``roots``. Returns a list of + {"size", "hash", "paths"} sorted by total wasted size desc.""" + by_size: Dict[int, List[Path]] = {} + for root in roots: + base = Path(root) + if base.is_file(): + entries = [base] + elif base.is_dir(): + entries = sorted(base.rglob("*")) + else: + continue + for p in entries: + try: + if p.is_file() and not p.is_symlink(): + st = p.stat() + if st.st_size >= min_size: + by_size.setdefault(st.st_size, []).append(p) + except OSError: + continue # unreadable entries are honestly skipped + # stage 2: partial hash + by_partial: Dict[Tuple[int, str], List[Path]] = {} + for size, paths in by_size.items(): + if len(paths) < 2: + continue + for p in paths: + try: + by_partial.setdefault((size, _hash_file(p, partial=True)), + []).append(p) + except OSError: + continue + # stage 3: full hash decides + groups: List[Dict] = [] + for (size, _part), paths in sorted(by_partial.items(), + key=lambda kv: (-kv[0][0], kv[0][1])): + if len(paths) < 2: + continue + by_full: Dict[str, List[str]] = {} + for p in paths: + try: + by_full.setdefault(_hash_file(p), []).append(str(p)) + except OSError: + continue + for digest, members in by_full.items(): + if len(members) > 1: + groups.append({ + "size": size, + "wasted": size * (len(members) - 1), + "hash": digest, + "paths": sorted(members), + }) + groups.sort(key=lambda g: (-g["wasted"], g["hash"])) + return groups + + +def survival_scores(paths: List[str], now: float) -> Dict[str, float]: + """Last-access-based survival score in [0,1]: 1.0 for entries + accessed within a day, decaying by half every 30 days after that. + Honest about atime-unreliability: the note field of the caller's + report should carry that this is a PRIOR, not a verdict.""" + scores: Dict[str, float] = {} + for p in paths: + try: + atime = os.stat(p).st_atime + except OSError: + scores[p] = 0.0 + continue + age_days = max(0.0, (now - atime) / 86400.0) + if age_days <= 1.0: + scores[p] = 1.0 + else: + scores[p] = round(0.5 ** ((age_days - 1.0) / 30.0), 4) + return scores + + +def quarantine(paths: List[str], quarantine_dir: str, now: float, + ttl_days: int = 30) -> Dict[str, Any]: + """TTL quarantine: move files into quarantine_dir with a manifest + recording origin + expiry; restore() undoes it; a purge after the + TTL is a SEPARATE explicit action. Journaled by construction (the + manifest is the journal). Returns {"moved": [...], "errors": [...]}.""" + import json + import time + qdir = Path(quarantine_dir) + qdir.mkdir(parents=True, exist_ok=True) + manifest_path = qdir / "manifest.json" + try: + manifest: Dict[str, Any] = json.loads( + manifest_path.read_text(encoding="utf-8")) + except (OSError, ValueError): + manifest = {"entries": []} + moved, errors = [], [] + for p in paths: + src = Path(p) + if not src.is_file(): + errors.append({"path": p, "error": "not a regular file"}) + continue + dest = qdir / f"{int(now * 1000)}-{src.name}" + try: + os.replace(src, dest) + except OSError as exc: + errors.append({"path": p, "error": f"{type(exc).__name__}: {exc}"}) + continue + manifest["entries"].append({ + "original": str(src), + "quarantined_at": now, + "purge_after": now + ttl_days * 86400.0, + "file": dest.name, + }) + moved.append(str(dest)) + manifest["entries"].sort(key=lambda e: (e["quarantined_at"], e["file"])) + manifest_path.write_text( + json.dumps(manifest, indent=1, sort_keys=True) + "\n", + encoding="utf-8") + return {"moved": moved, "errors": errors, + "manifest": str(manifest_path)} + + +def restore(quarantine_dir: str, now: float) -> Dict[str, Any]: + """Undo every quarantine entry whose TTL has expired or that is due + to be purged later — restore ALL entries the caller asks for via + ttl_expired_only=False; default restores only expired ones.""" + import json + qdir = Path(quarantine_dir) + manifest_path = qdir / "manifest.json" + try: + manifest = json.loads(manifest_path.read_text(encoding="utf-8")) + except (OSError, ValueError): + return {"restored": [], "errors": [{"error": "no manifest"}]} + restored, errors, keep = [], [], [] + for entry in manifest.get("entries", []): + dest = qdir / entry["file"] + src = Path(entry["original"]) + if entry["purge_after"] > now: + keep.append(entry) # TTL not yet reached: leave quarantined + continue + try: + if dest.is_file(): + src.parent.mkdir(parents=True, exist_ok=True) + os.replace(dest, src) + restored.append(entry["original"]) + except OSError as exc: + errors.append({"path": entry["original"], + "error": f"{type(exc).__name__}: {exc}"}) + keep.append(entry) + manifest["entries"] = keep + manifest_path.write_text( + json.dumps(manifest, indent=1, sort_keys=True) + "\n", + encoding="utf-8") + return {"restored": restored, "errors": errors} diff --git a/plugins/caelestia-assistant/assistant/capabilities/devflow/__init__.py b/plugins/caelestia-assistant/assistant/capabilities/devflow/__init__.py new file mode 100644 index 0000000..dd5a001 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/capabilities/devflow/__init__.py @@ -0,0 +1,30 @@ +"""assistant.capabilities.devflow — developer-workflow drafting tools. + +SCOPE DISCLAIMER (the reason this is a separate top-level package): +this domain exists for the DEVELOPER'S OWN workflow — commit-message +drafting, PR-description skeletons, TODO/FIXME triage over source trees. +It has NO relationship to caelestia-kde issue #120 or the KDE shell, it +is NOT part of the assistant's shell-facing feature surface, and it must +never be included in any upstream-bound pull request under any framing. +If a #120-scoped task ever seems to need this package, that is a signal +the partition is wrong — stop and re-scope, don't cross it. + +What it does, all deterministic and templated (NO generation, no model): + +- diffstat.commit_message: a conventional-commit skeleton from + ``git diff --numstat`` text — keyword-to-type classification + (tests/docs/ci/feat/refactor/chore), mechanical scope from the common + top-level directory, subject/body filled with the REAL file/line + deltas. The human writes the actual prose; this is scaffolding. +- diffstat.pr_skeleton: a PR-description skeleton from the same stats, + shaped like the upstream project's PR template (what/why, changes by + area with real deltas, testing checklist, type checkboxes pre-filled + by the same classification). +- todo.triage_tree: TODO/FIXME/XXX/HACK/BUG marker triage over a source + tree, reusing the scan layer's Aho-Corasick automaton (built for logs, + equally exact over source) — one pass per file, marker + line number + + the comment's own text, grouped by marker. + +Stdlib only like everything else; reads only the tree the caller names; +writes nothing, ever. +""" diff --git a/plugins/caelestia-assistant/assistant/capabilities/devflow/__main__.py b/plugins/caelestia-assistant/assistant/capabilities/devflow/__main__.py new file mode 100644 index 0000000..3626196 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/capabilities/devflow/__main__.py @@ -0,0 +1,75 @@ +"""python3 -m assistant.capabilities.devflow — the developer-workflow drafting CLI. + + git diff --numstat > /tmp/numstat && python3 -m assistant.capabilities.devflow commit < /tmp/numstat + python3 -m assistant.capabilities.devflow pr --base dev --head my-branch < /tmp/numstat + python3 -m assistant.capabilities.devflow todo ~/my-checkout + +SCOPE: this domain serves the developer's own workflow. It has NO +relationship to issue #120 or the KDE shell and is never part of any +upstream-bound PR (see assistant/devflow/README.md). +""" +import argparse +import sys + + +def main(argv=None) -> int: + parser = argparse.ArgumentParser( + prog="python3 -m assistant.capabilities.devflow", + description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter) + sub = parser.add_subparsers(dest="cmd") + + commit_p = sub.add_parser("commit", help="commit-message skeleton from " + "git diff --numstat text (stdin)") + pr_p = sub.add_parser("pr", help="PR-description skeleton from the same " + "stats (stdin)") + pr_p.add_argument("--base", default="main") + pr_p.add_argument("--head", default="dev") + todo_p = sub.add_parser("todo", help="TODO/FIXME triage over a source tree") + todo_p.add_argument("root", help="the tree (or single file) to triage") + risk_p = sub.add_parser("risk", help="commit-risk score: McCabe " + "cyclomatic complexity x recent " + "churn (log text on stdin)") + risk_p.add_argument("--source", required=True, + help="the CURRENT Python file the churn touches") + risk_p.add_argument("--before", default=None, + help="the PRE-change version of that file " + "(reports the peak-CC delta)") + risk_p.add_argument("--halflife", type=int, default=5, + help="churn recency half-life in commits (default 5)") + + args = parser.parse_args(argv) + if args.cmd is None: + parser.print_help() + return 0 + + if args.cmd == "commit": + from .diffstat import commit_message + print(commit_message(sys.stdin.read())) + return 0 + if args.cmd == "pr": + from .diffstat import pr_skeleton + print(pr_skeleton(sys.stdin.read(), base=args.base, head=args.head)) + return 0 + if args.cmd == "todo": + from .todo import render, triage_tree + print(render(triage_tree(args.root))) + return 0 + if args.cmd == "risk": + # exponential-build 2.5: complexity x churn from piped text — + # no subprocess anywhere on this path + from .risk import commit_risk + source = open(args.source, encoding="utf-8", errors="replace").read() + before = (open(args.before, encoding="utf-8", errors="replace").read() + if args.before else None) + import json as _json + print(_json.dumps(commit_risk(sys.stdin.read(), source, before, + halflife_commits=args.halflife), + indent=2, default=str)) + return 0 + parser.print_help() + return 2 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/plugins/caelestia-assistant/assistant/capabilities/devflow/diffstat.py b/plugins/caelestia-assistant/assistant/capabilities/devflow/diffstat.py new file mode 100644 index 0000000..2eb47f6 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/capabilities/devflow/diffstat.py @@ -0,0 +1,228 @@ +"""devflow.diffstat — commit-message and PR skeletons from git diff stats. + +Input contract (caller-supplied text, never a subprocess — the import +policy forbids one anyway): the standard ``git diff --numstat`` line +format, tab-separated:: + + \t\t + +with the usual special cases honored: ``-`` for binary files and +``{old => new}`` renames. Everything derived below is a mechanical +template over those numbers and paths — the tool never generates prose +and never invents a "why"; the human supplies that. + +Classification (deterministic keyword table, most-specific rule wins): + +====================== ========================================== +rule conventional type +====================== ========================================== +path under tests/ or test +matching test_*.py +*.md / docs/ / LICENSE docs +.github/ / *ci* / ci + scripts/ci* +new file with only feat + additions +deletions dominate refactor +(>= 2:1 del:add) chore (fallback) +====================== ========================================== + +Scope: the most common top-level directory among changed files, when one +directory covers at least half of them. +""" + +from __future__ import annotations + +import re +from collections import Counter +from typing import Dict, List, Optional + +__all__ = ["parse_numstat", "classify_change", "dominant_type", + "commit_message", "pr_skeleton", "subject_limit"] + +SUBJECT_LIMIT = 72 # the classic git convention + +_NUMSTAT_RE = re.compile(r"^(\d+|-)\t(\d+|-)\t(.+)$") +_RENAME_RE = re.compile(r"\{(.+) => (.+)\}") + + +def parse_numstat(numstat_text: str) -> List[Dict[str, object]]: + """``git diff --numstat`` text -> one row per file: + {"path", "added", "deleted", "binary", "renamed_from"}.""" + rows: List[Dict[str, object]] = [] + for line in numstat_text.splitlines(): + line = line.strip() + if not line: + continue + match = _NUMSTAT_RE.match(line) + if not match: + continue + added_s, deleted_s, raw_path = match.groups() + binary = added_s == "-" or deleted_s == "-" + renamed_from: Optional[str] = None + rename = _RENAME_RE.search(raw_path) + if rename: + renamed_from = _RENAME_RE.sub(rename.group(1), raw_path, count=1) + rows.append({ + "path": raw_path, + "renamed_from": renamed_from, + "added": 0 if binary else int(added_s), + "deleted": 0 if binary else int(deleted_s), + "binary": binary, + }) + return rows + + +def classify_change(row: Dict[str, object]) -> str: + """The conventional-commit type one file most likely belongs to + (deterministic keyword rules; the least-specific rule is the honest + fallback, never a guess about intent).""" + path = str(row.get("path", "")).lower() + if "/tests/" in f"/{path}" or path.startswith("tests/") \ + or re.search(r"(^|/)(test_[^/]+\.py|[^/]+_test\.[a-z]+)$", path): + return "test" + if path.endswith((".md", ".rst", ".txt")) or path.startswith(("docs/", "doc/")) \ + or "/license" in path: + return "docs" + if ".github/" in path or "/ci/" in path or "workflow" in path: + return "ci" + if row.get("renamed_from") is None and row.get("added", 0) > 0 \ + and row.get("deleted", 0) == 0: + return "feat" + if row.get("deleted", 0) >= 2 * max(1, row.get("added", 0)) \ + and row.get("deleted", 0) > 0: + return "refactor" + return "chore" + + +def dominant_type(rows: List[Dict[str, object]]) -> str: + """The most common classification, ties broken alphabetically — + deterministic under every reordering of the input.""" + counts = Counter(classify_change(row) for row in rows) + if not counts: + return "chore" + return sorted(counts.items(), key=lambda kv: (-kv[1], kv[0]))[0][0] + + +def _scope(rows: List[Dict[str, object]]) -> Optional[str]: + """The common top-level directory when one covers >= half the files.""" + if not rows: + return None + tops: Counter = Counter() + for row in rows: + path = str(row.get("path", "")) + parts = path.split("/") + if len(parts) > 1 and parts[0] not in (".", "..", ""): + tops[parts[0]] += 1 + if not tops: + return None + name, count = sorted(tops.items(), key=lambda kv: (-kv[1], kv[0]))[0] + return name if count >= (len(rows) + 1) // 2 else None + + +def _area(path: str) -> str: + """The area a file belongs to: first directory, else the file itself.""" + parts = path.split("/") + return parts[0] if len(parts) > 1 else "(root)" + + +def commit_message(numstat_text: str) -> str: + """A deterministic commit-message SKELETON from numstat text: + conventional-commit header with real deltas, body grouped by area. + The ```` slots are the human's to fill.""" + rows = parse_numstat(numstat_text) + if not rows: + return "(no changes in the numstat input)" + kind = dominant_type(rows) + scope = _scope(rows) + added = sum(int(r["added"]) for r in rows) + deleted = sum(int(r["deleted"]) for r in rows) + header_scope = f"({scope})" if scope else "" + subject = (f"{kind}{header_scope}: " + f"[{len(rows)} file(s), +{added}/-{deleted}]") + if len(subject) > SUBJECT_LIMIT: + subject = (f"{kind}{header_scope}: " + f"[{len(rows)} files +{added}/-{deleted}]") + + areas: Dict[str, List[Dict[str, object]]] = {} + for row in rows: + areas.setdefault(_area(str(row["path"])), []).append(row) + + lines = [subject, "", + ""] + for area in sorted(areas): + area_rows = areas[area] + area_add = sum(int(r["added"]) for r in area_rows) + area_del = sum(int(r["deleted"]) for r in area_rows) + lines.append("") + lines.append(f"- {area}: {len(area_rows)} file(s) " + f"(+{area_add}/-{area_del})") + for row in area_rows[:8]: + note = " (binary)" if row.get("binary") else "" + rename = "" + if row.get("renamed_from"): + rename = f" (renamed from {row['renamed_from']})" + lines.append(f" {row['path']}{note}{rename}") + if len(area_rows) > 8: + lines.append(f" ... and {len(area_rows) - 8} more") + return "\n".join(lines) + + +def pr_skeleton(numstat_text: str, base: str = "main", + head: str = "dev") -> str: + """A PR-description skeleton from the same stats, shaped like the + upstream project's PR template (What does this change / How did you + test it / Type / Notes), with the mechanical parts filled in and the + judgment parts left as explicit placeholders. Deterministic.""" + rows = parse_numstat(numstat_text) + if not rows: + return "(no changes in the numstat input)" + kind = dominant_type(rows) + added = sum(int(r["added"]) for r in rows) + deleted = sum(int(r["deleted"]) for r in rows) + areas: Dict[str, List[Dict[str, object]]] = {} + for row in rows: + areas.setdefault(_area(str(row["path"])), []).append(row) + + type_map = { + "feat": "New feature", "fix": "Bug fix", "test": "Other", + "docs": "Docs", "ci": "Other", "refactor": "Refactor", + "chore": "Other", + } + out: List[str] = [ + f"## What does this change?", + "", + f" ({len(rows)} file(s), +{added}/-{deleted}, " + f"`{base}...{head}`)", + "", + "## Changes by area", + "", + ] + for area in sorted(areas): + area_rows = areas[area] + area_add = sum(int(r["added"]) for r in area_rows) + area_del = sum(int(r["deleted"]) for r in area_rows) + out.append(f"- **{area}**: {len(area_rows)} file(s) " + f"(+{area_add}/-{area_del})") + out.extend([ + "", + "## How did you test it?", + "", + "- [ ] ", + "", + "## Type", + "", + f"- [ ] Bug fix", + f"- [x] {type_map.get(kind, 'Other')} (classified from the diff " + f"stats: {kind}; uncheck and correct if wrong)", + "- [ ] Config / theme", + "- [ ] Docs", + "- [ ] Refactor", + "- [ ] Other", + "", + "## Notes for reviewers", + "", + "", + "", + ]) + return "\n".join(out) diff --git a/plugins/caelestia-assistant/assistant/capabilities/devflow/manifest.py b/plugins/caelestia-assistant/assistant/capabilities/devflow/manifest.py new file mode 100644 index 0000000..54b1257 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/capabilities/devflow/manifest.py @@ -0,0 +1,10 @@ +"""Manifest for the devflow capability: permissions, risk tier, budgets.""" +from assistant.capabilities._registry import CapManifest + +MANIFEST = CapManifest( + name="devflow", + permissions=("fs:read", "git:read",), + risk_tier="read_only", + latency_budget_ms=500, + memory_budget_mb=40, +) diff --git a/plugins/caelestia-assistant/assistant/capabilities/devflow/risk.py b/plugins/caelestia-assistant/assistant/capabilities/devflow/risk.py new file mode 100644 index 0000000..640daf7 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/capabilities/devflow/risk.py @@ -0,0 +1,190 @@ +"""devflow.risk — a commit-risk score: McCabe cyclomatic complexity x +recent churn, both from CALLER-PIPED TEXT (the diffstat.py input +contract: no subprocess, ever — the import policy forbids one and the +caller already has the data):: + + git log --numstat > /tmp/log.txt + python3 -m assistant.capabilities.devflow risk --source changed.py < /tmp/log.txt + +The two factors: + +- COMPLEXITY: cyclomatic complexity per function from the ``ast`` of + the supplied Python source — 1 + decision points, counting each + if/elif, loop, except handler, assert, ternary, comprehension clause + and (on 3.10+) match case, and each additional and/or operand + (McCabe 1976, "A Complexity Measure", IEEE TSE 4). The PEAK function + complexity is the risk driver. +- CHURN: the ``git log --numstat`` text parsed into commits (newest + first, the order git prints); per-file churn decays by commit + recency with a fixed half-life (default 5 commits), so yesterday's + hot file outweighs a touch from last month. The parse reuses + ``diffstat.parse_numstat`` for the file rows — one numstat + implementation, not two. + + risk = peak_cc * log2(1 + decayed_churn) + +Deterministic, pure, dimensionless. The score is a REPORT for the +human's review, not a gate: nothing blocks, nothing executes. A +non-Python or unparsable source is an honest refusal of the complexity +half (churn is still reported) — never an invented number. +""" +from __future__ import annotations + +import ast +import math +import re +from typing import Any, Dict, List, Optional + +from .diffstat import parse_numstat + +__all__ = ["cyclomatic_complexity", "parse_log_numstat", "recent_churn", + "commit_risk"] + +_COMMIT_RE = re.compile(r"^commit\s+([0-9a-f]{7,40})", re.I) +_RISK_TIERS = ((20.0, "low"), (60.0, "medium")) # else high + + +def cyclomatic_complexity(source: str) -> Dict[str, Any]: + """Per-function cyclomatic complexity (McCabe 1976) from the AST. + + Raises ValueError for unparsable source — the honest refusal, never + a guessed score.""" + try: + tree = ast.parse(source) + except SyntaxError as exc: + raise ValueError(f"source does not parse as Python: {exc}") from exc + rows: List[Dict[str, Any]] = [] + + def decisions(node: ast.AST) -> int: + total = 0 + for child in ast.walk(node): + if isinstance(child, (ast.If, ast.While, ast.For, ast.AsyncFor, + ast.ExceptHandler, ast.IfExp, ast.Assert)): + total += 1 + elif isinstance(child, ast.BoolOp): + total += max(0, len(child.values) - 1) + elif isinstance(child, ast.comprehension): + total += 1 + len(child.ifs) + elif hasattr(ast, "Match") and isinstance(child, ast.Match): + total += len(child.cases) + return total + + def walk(node: ast.AST, prefix: str = "") -> None: + for child in ast.iter_child_nodes(node): + if isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef)): + name = f"{prefix}{child.name}" + # decisions belonging to NESTED functions are the + # nested function's own; walk() recurses and the inner + # entry carries them, so exclude nested defs here + inner = sum(decisions(d) for d in ast.walk(child) + if isinstance(d, (ast.FunctionDef, + ast.AsyncFunctionDef)) + and d is not child) + rows.append({"name": name, + "cc": 1 + decisions(child) - inner, + "lineno": child.lineno}) + walk(child, prefix=name + ".") + else: + walk(child, prefix) + + walk(tree) + rows.sort(key=lambda r: (-r["cc"], r["name"])) + if not rows: + raise ValueError("source defines no functions — nothing to score") + return { + "functions": rows, + "peak_cc": rows[0]["cc"], + "peak_function": rows[0]["name"], + "n_functions": len(rows), + "algorithm": ("cyclomatic complexity (McCabe 1976): 1 + decision " + "points, from the stdlib ast"), + } + + +def parse_log_numstat(log_text: str) -> List[Dict[str, Any]]: + """``git log --numstat`` text -> one entry per commit, newest first + (the order git prints). File rows reuse diffstat.parse_numstat — + the ONE numstat parser.""" + commits: List[Dict[str, Any]] = [] + current: Optional[Dict[str, Any]] = None + for line in log_text.splitlines(): + m = _COMMIT_RE.match(line.strip()) + if m: + current = {"commit": m.group(1), "lines": []} + commits.append(current) + continue + if current is not None and line.strip(): + current["lines"].append(line) + for c in commits: + c["rows"] = parse_numstat("\n".join(c.pop("lines"))) + c["added"] = sum(int(r["added"]) for r in c["rows"]) + c["deleted"] = sum(int(r["deleted"]) for r in c["rows"]) + return commits + + +def recent_churn(log_text: str, halflife_commits: int = 5 + ) -> Dict[str, Any]: + """Per-file churn with recency decay: commit i (0 = newest) weighs + 0.5 ** (i / halflife_commits). Deterministic; no timestamps needed + (git's own newest-first order IS the recency signal).""" + if halflife_commits <= 0: + raise ValueError("halflife_commits must be >= 1") + commits = parse_log_numstat(log_text) + churn: Dict[str, float] = {} + for idx, c in enumerate(commits): + w = 0.5 ** (idx / float(halflife_commits)) + for r in c["rows"]: + path = str(r["path"]) + churn[path] = churn.get(path, 0.0) + \ + (int(r["added"]) + int(r["deleted"])) * w + files = sorted(({"path": p, "churn": round(v, 2)} + for p, v in churn.items()), + key=lambda d: (-d["churn"], d["path"])) + return {"files": files, "total": round(sum(churn.values()), 2), + "n_commits": len(commits), + "halflife_commits": halflife_commits} + + +def commit_risk(log_text: str, source: str, + source_before: Optional[str] = None, + halflife_commits: int = 5) -> Dict[str, Any]: + """The product the score is named for: peak cyclomatic complexity of + the CURRENT source x log2(1 + decayed churn), tiered low/medium/ + high at stated thresholds. With ``source_before`` the CC delta is + reported too. Unparsable source reports churn alone with the + refusal named — the score stays None, never a guess.""" + churn = recent_churn(log_text, halflife_commits) + out: Dict[str, Any] = { + "churn": churn, + "algorithm": ("risk = peak_cc (McCabe 1976) x log2(1 + " + "recency-decayed churn); a report, not a gate"), + } + try: + cc = cyclomatic_complexity(source) + cc_before = (cyclomatic_complexity(source_before) + if source_before is not None else None) + except ValueError as exc: + out.update({"risk": None, "tier": None, + "complexity_refused": str(exc), + "note": "churn reported alone — supply parsable " + "Python source for the complexity half"}) + return out + delta = None + if cc_before is not None: + delta = cc["peak_cc"] - cc_before["peak_cc"] + h = math.log2(1.0 + churn["total"]) + score = round(cc["peak_cc"] * h, 2) + tier = "high" + for bound, name in _RISK_TIERS: + if score < bound: + tier = name + break + out.update({ + "risk": score, "tier": tier, + "peak_cc": cc["peak_cc"], "peak_function": cc["peak_function"], + "cc_delta": delta, + "churn_factor": round(h, 3), + "thresholds": {"low_below": _RISK_TIERS[0][0], + "medium_below": _RISK_TIERS[1][0]}, + }) + return out diff --git a/plugins/caelestia-assistant/assistant/capabilities/devflow/todo.py b/plugins/caelestia-assistant/assistant/capabilities/devflow/todo.py new file mode 100644 index 0000000..07c4fe7 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/capabilities/devflow/todo.py @@ -0,0 +1,109 @@ +"""devflow.todo — TODO/FIXME triage over a source tree, via scan's Aho-Corasick. + +The scan layer's automaton was built for one-pass matching of many known +signatures over huge logs; a source tree is the same problem with fewer +lines. This module reuses it exactly (no second matcher): one automaton +over the marker vocabulary, one scan per file, marker + line number + +the comment's own text out the other end. + +Bounds: file count capped (default 2000), per-file size capped, symlinks +never followed, hidden and build directories skipped. Reads only what the +caller names; writes nothing. +""" + +from __future__ import annotations + +from pathlib import Path +from typing import Any, Dict, List, Tuple + +from assistant.capabilities.scan import Automaton + +__all__ = ["MARKERS", "triage_tree", "render", "MAX_FILES", "MAX_FILE_BYTES"] + +MARKERS: Tuple[str, ...] = ("TODO", "FIXME", "XXX", "HACK", "BUG") +MAX_FILES = 2000 +MAX_FILE_BYTES = 2_000_000 +SKIP_DIRS = {".git", ".hg", ".svn", "__pycache__", "node_modules", + ".venv", "venv", "build", "dist", ".mypy_cache"} + +_EXTENSIONS = (".py", ".qml", ".js", ".ts", ".sh", ".c", ".cpp", ".cc", + ".hpp", ".h", ".rs", ".go", ".java", ".md", ".json", + ".yaml", ".yml", ".toml") + + +def triage_tree(root: str, markers: Tuple[str, ...] = MARKERS, + extensions: Tuple[str, ...] = _EXTENSIONS) -> Dict[str, Any]: + """Walk ``root`` (bounded) and report every marker line, grouped for + triage: {"root", "files", "items": [{file, line, marker, text}], + "by_marker": {marker: count}, "skipped": [...]}.""" + root_path = Path(root) + automaton = Automaton(list(markers)) + items: List[Dict[str, Any]] = [] + files = 0 + skipped: List[str] = [] + if root_path.is_file(): + candidates = [root_path] + else: + candidates = sorted( + p for p in root_path.rglob("*") + if p.is_file() and not any(part in SKIP_DIRS + for part in p.parts)) + for path in candidates: + if files >= MAX_FILES: + skipped.append(f"file cap reached ({MAX_FILES})") + break + if path.suffix.lower() not in extensions: + continue + try: + if path.stat().st_size > MAX_FILE_BYTES: + skipped.append(f"too large: {path}") + continue + text = path.read_text(encoding="utf-8", errors="replace") + except OSError as exc: + skipped.append(f"unreadable: {path} ({exc.__class__.__name__})") + continue + files += 1 + for lineno, line in enumerate(text.splitlines(), start=1): + hits = automaton.scan(line) + if not hits: + continue + # scan() returns (end_index_exclusive, pid); recover the + # marker's original spelling from the line, group canonically + end, pid = min(hits, key=lambda h: (h[0], -len(automaton.pattern(h[1])))) + marker_len = len(automaton.pattern(pid)) + marker = line[max(0, end - marker_len):end].upper() + tail = line[end:].strip().lstrip(":-— ").strip() + items.append({ + "file": str(path.relative_to(root_path)), + "line": lineno, + "marker": marker, + "text": tail[:100], + }) + by_marker: Dict[str, int] = {m: 0 for m in markers} + for item in items: + by_marker[item["marker"]] = by_marker.get(item["marker"], 0) + 1 + return {"root": str(root), "files": files, "items": items, + "by_marker": by_marker, "skipped": skipped} + + +def render(report: Dict[str, Any]) -> str: + """Plain-text triage list, grouped by marker, most numerous first.""" + if not report["items"]: + return (f"no TODO/FIXME markers under {report['root']} " + f"({report['files']} file(s) scanned)") + lines = [f"{len(report['items'])} marker(s) in {report['files']} " + f"file(s) under {report['root']}"] + order = sorted(report["by_marker"].items(), + key=lambda kv: (-kv[1], kv[0])) + for marker, count in order: + if not count: + continue + lines.append("") + lines.append(f"{marker} ({count}):") + for item in report["items"]: + if item["marker"] == marker: + lines.append(f" {item['file']}:{item['line']} {item['text']}") + if report["skipped"]: + lines.append("") + lines.append("skipped: " + "; ".join(report["skipped"][:5])) + return "\n".join(lines) diff --git a/plugins/caelestia-assistant/assistant/capabilities/guard/__init__.py b/plugins/caelestia-assistant/assistant/capabilities/guard/__init__.py new file mode 100644 index 0000000..9005c5f --- /dev/null +++ b/plugins/caelestia-assistant/assistant/capabilities/guard/__init__.py @@ -0,0 +1,3 @@ +"""guard — resource-pressure watchdogs (capability 4): PSI trends, +time-to-danger estimates, and relief PROPOSALS. Proposals only: this +package never applies anything itself.""" diff --git a/plugins/caelestia-assistant/assistant/capabilities/guard/pressure.py b/plugins/caelestia-assistant/assistant/capabilities/guard/pressure.py new file mode 100644 index 0000000..2c8be7d --- /dev/null +++ b/plugins/caelestia-assistant/assistant/capabilities/guard/pressure.py @@ -0,0 +1,131 @@ +"""capabilities.guard.pressure — the memory-pressure guard (capability 4). + +Reads /proc/pressure/memory (PSI), tracks trends with an EWMA, and +estimates time-to-OOM with a Weibull-shaped extrapolation of the +full-stall growth rate. It PROPOSES actions (zram size, swappiness, +top-RSS app closure) — it never applies anything: every proposal is a +typed ActionPlan with read-only probes and confirm-class mutations for +a human to approve. + +Honest degradation: absent PSI (pre-4.20 kernels, non-Linux) every +function returns an {"available": False} dict instead of guessing. +""" +from __future__ import annotations + +import math +import re +from pathlib import Path +from typing import Any, Dict, List, Optional + +__all__ = ["read_psi", "PressureTracker", "propose_relief"] + +_PSI_PATH = Path("/proc/pressure/memory") +_TAIL_RE = re.compile( + r"^(avg10|avg60|avg300)=(?P[\d.]+) (?P[\d.]+) (?P[\d.]+)") + + +def read_psi(path: Optional[Path] = None) -> Dict[str, Any]: + """Parse one PSI snapshot: {"available": True, "some": {...}, + "full": {...}} with avg10/avg60/avg300 per line.""" + target = Path(path) if path else _PSI_PATH + try: + text = target.read_text(encoding="utf-8") + except OSError: + return {"available": False, "reason": "no /proc/pressure/memory (PSI)"} + out: Dict[str, Dict[str, float]] = {} + for line in text.splitlines(): + kind, _, rest = line.partition(" ") + m = _TAIL_RE.match(rest.strip()) + if not m: + continue + out[kind] = { + "avg10": float(m.group("v10")), + "avg60": float(m.group("v60")), + "avg300": float(m.group("v300")), + } + if not out: + return {"available": False, "reason": "PSI lines unparsable"} + return {"available": True, "some": out.get("some", {}), + "full": out.get("full", {})} + + +class PressureTracker: + """EWMA over PSI 'some.avg10' samples + a Weibull-shaped + time-to-OOM estimate. Deterministic given the sample stream. + + The estimator is deliberately CONSERVATIVE and SAYS SO: it reports + seconds-to-danger only when the trend is monotonic rising over the + window; anything flatter is an honest 'no trend' (a flat high PSI + is a condition, not an imminent OOM).""" + + ALPHA = 0.3 # EWMA smoothing + WINDOW = 8 # trend window (samples) + DANGER_PCT = 60.0 # 'some' avg10 level treated as danger + + def __init__(self): + self._ewma: Optional[float] = None + self._history: List[float] = [] + + def observe(self, psi: Dict[str, Any]) -> Dict[str, Any]: + if not psi.get("available"): + return {"available": False, "reason": psi.get("reason", "no PSI")} + level = float(psi.get("some", {}).get("avg10", 0.0)) + self._ewma = level if self._ewma is None \ + else self.ALPHA * level + (1 - self.ALPHA) * self._ewma + self._history.append(level) + recent = self._history[-self.WINDOW:] + rising = len(recent) == self.WINDOW and all( + recent[i] <= recent[i + 1] + 1e-9 + for i in range(len(recent) - 1)) and recent[-1] > recent[0] + 1e-6 + out: Dict[str, Any] = { + "available": True, + "level": level, + "ewma": round(self._ewma, 3), + "trend": "rising" if rising else "no-trend", + } + if rising: + rate = (recent[-1] - recent[0]) / (len(recent) - 1) + if rate > 1e-9: + # Weibull-shaped extrapolation (shape k=1.5, the classic + # wear-out shape for exhaustion processes): the estimate + # is seconds until the DANGER_PCT level at the observed + # rate, shrunk by the shape factor for conservatism. + seconds = max(0.0, (self.DANGER_PCT - recent[-1])) / rate + k = 1.5 + eta = seconds / math.gamma(1 + 1 / k) if seconds > 0 else 0.0 + out["seconds_to_danger"] = round(eta, 1) + out["note"] = ("Weibull (k=1.5) extrapolation of a rising " + "PSI trend — an estimate, never a promise") + if self._ewma >= self.DANGER_PCT: + out["danger"] = True + return out + + +def propose_relief(top_rss_procs: Optional[List[Dict[str, Any]]] = None) -> Dict[str, Any]: + """Build the PROPOSAL payload: zram sizing, swappiness, and (when the + caller supplies the process table) the top-RSS app candidates. Pure + function over its inputs; the caller decides what to do — this + module never executes.""" + proposals: List[Dict[str, Any]] = [ + {"action": "ensure_zram", + "risk_tier": "confirm", + "evidence": "memory pressure guard: zram absorbs anonymous " + "page pressure without a swap-device cliff"}, + {"action": "tune_swappiness", + "risk_tier": "confirm", + "evidence": "swappiness 180 (zram-appropriate default) vs the " + "current value; journaled, single sysctl write"}, + ] + if top_rss_procs: + for proc in top_rss_procs[:3]: + proposals.append({ + "action": "close_app", + "target": proc.get("name", "?"), + "rss_mb": proc.get("rss_mb"), + "risk_tier": "confirm", + "evidence": f"top RSS consumer ({proc.get('rss_mb')} MB); " + "closing is user-data-safe only for apps with " + "session restore — always confirmed first", + }) + return {"available": True, "proposals": proposals, + "note": "proposals only — nothing here applies anything"} diff --git a/plugins/caelestia-assistant/assistant/capabilities/issues/__init__.py b/plugins/caelestia-assistant/assistant/capabilities/issues/__init__.py new file mode 100755 index 0000000..5b54df5 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/capabilities/issues/__init__.py @@ -0,0 +1,33 @@ +"""Layer 4: issue-DRAFTING helper (drafts only — never files anything). + +This layer composes clean, paste-ready issue text from a described problem +and STOPS THERE. Guarantees, same safety box as the rest of the assistant: + +- No network code of any kind (no http/urllib/socket imports; the whole- + assistant import scan in assistant/diagnostics/schema_lint.py enforces it). +- Drafts are written ONLY to local files, and ONLY when the CLI is invoked + with --confirm. The default is preview-only: the draft is printed to + stdout and nothing touches the filesystem. +- Nothing is ever posted, submitted, opened, or transmitted. The user + copy-pastes the draft into GitHub's new-issue form themselves. + +Scope note (from the maintainer threads captured in the retrieval corpus, +ISS-120 / ISS-802): the assistant's job is "issue reportings to repo +directly" as DRAFTING ONLY — this layer implements exactly that boundary. +""" + +from pathlib import Path + +ISSUES_DIR = Path(__file__).resolve().parent +REPO_ROOT = ISSUES_DIR.parent.parent +TEMPLATES_DIR = REPO_ROOT / ".github" / "ISSUE_TEMPLATE" +BUG_TEMPLATE_FILE = TEMPLATES_DIR / "1-issue.yml" +FEATURE_TEMPLATE_FILE = TEMPLATES_DIR / "2-feature_request.yml" + +__all__ = [ + "BUG_TEMPLATE_FILE", + "FEATURE_TEMPLATE_FILE", + "ISSUES_DIR", + "REPO_ROOT", + "TEMPLATES_DIR", +] diff --git a/plugins/caelestia-assistant/assistant/capabilities/issues/cli.py b/plugins/caelestia-assistant/assistant/capabilities/issues/cli.py new file mode 100755 index 0000000..fdfd26b --- /dev/null +++ b/plugins/caelestia-assistant/assistant/capabilities/issues/cli.py @@ -0,0 +1,242 @@ +"""CLI for Layer 4 issue drafting. Drafts ONLY — nothing is ever filed. + +Usage: + python3 -m assistant.capabilities.issues.cli draft --title "..." [--type bug|feature] + [--from-file PATH | stdin] [--out PATH] [--confirm] [--list-similar] + python3 -m assistant.capabilities.issues.cli list-similar --title "..." [--from-file PATH | stdin] [-k N] + +Gate mechanics: +- WITHOUT --confirm the command is PREVIEW-ONLY: the draft is printed to + stdout and no file is written anywhere. +- WITH --confirm the draft is written to a LOCAL file only: --out PATH, or + $XDG_DATA_HOME/caelestia/assistant/drafts/issue-draft-YYYYmmdd-HHMMSS.md + (default ~/.local/share/...). Nothing is posted, sent, or transmitted. +- --list-similar just prints the retrieval hits for the described problem: + no file write, no --confirm needed. + +Guarantees: pure stdlib, no network code, no subprocess — the only commands +that appear in output are inert SUGGESTED_NOT_EXECUTED strings the user runs +themselves. Environment facts are assembled from pure file reads only +(/etc/os-release, .git/HEAD + .git/refs/heads/, ~/.config/caelestia/version). +""" + +from __future__ import annotations + +import argparse +import os +import sys +from datetime import datetime +from pathlib import Path +from typing import Any, Dict, List, Optional + +from . import template +from assistant.capabilities.retrieval import search as retrieval_search + +DEFAULT_TOP_K = 3 +LIST_SIMILAR_TOP_K = 5 + +DRAFTS_SUBDIR = Path("caelestia") / "assistant" / "drafts" + +REPO_ROOT = Path(__file__).resolve().parents[2] + +EPILOG = ( + "This tool drafts issues only: it never posts, submits, opens, or transmits anything. " + "You copy-paste the draft into GitHub's new-issue form yourself." +) + + +def default_drafts_dir() -> Path: + """$XDG_DATA_HOME/caelestia/assistant/drafts (default ~/.local/share/...).""" + data_home = os.environ.get("XDG_DATA_HOME") + base = Path(data_home) if data_home else Path.home() / ".local" / "share" + return base / DRAFTS_SUBDIR + + +def default_draft_path(now: Optional[datetime] = None) -> Path: + stamp = (now or datetime.now()).strftime("%Y%m%d-%H%M%S") + return default_drafts_dir() / f"issue-draft-{stamp}.md" + + +def read_os_release() -> str: + """PRETTY_NAME (or NAME) from /etc/os-release — pure file read, '' if absent.""" + for key in ("PRETTY_NAME", "NAME"): + value = _os_release_field(key) + if value: + return value + return "" + + +def _os_release_field(key: str) -> str: + try: + text = Path("/etc/os-release").read_text(encoding="utf-8") + except OSError: + return "" + for line in text.splitlines(): + if line.startswith(key + "="): + return line.split("=", 1)[1].strip().strip('"').strip("'") + return "" + + +def read_commit_info(repo_root: Path = REPO_ROOT) -> str: + """Branch + commit from .git files (pure reads); '' when unavailable. + + Never shells out: reads .git/HEAD, then .git/refs/heads/ directly. + The refs/heads/ prefix is stripped for display (feat/assistant, not refs/...). + """ + git_dir = repo_root / ".git" + head_path = git_dir / "HEAD" + try: + head = head_path.read_text(encoding="utf-8").strip() + except OSError: + return "" + if head.startswith("ref:"): + branch = head[len("ref:"):].strip() + branch = branch.split("refs/heads/", 1)[-1] # display form: feat/assistant + ref_path = git_dir / "refs" / "heads" / branch + try: + commit = ref_path.read_text(encoding="utf-8").strip() + except OSError: + return branch + return f"{commit} (branch {branch})" + return head # detached HEAD: the sha itself + + +def read_shell_version() -> str: + """Best-effort pure read of ~/.config/caelestia/version; '' if absent.""" + try: + return Path.home().joinpath(".config", "caelestia", "version").read_text(encoding="utf-8").strip() + except OSError: + return "" + + +def gather_description(args: argparse.Namespace, stdin_text: Optional[str]) -> str: + """Description from --from-file, else stdin text; '' when neither given.""" + if getattr(args, "from_file", None): + return Path(args.from_file).read_text(encoding="utf-8") + return (stdin_text or "").strip() + + +def fetch_similar(query: str, k: int = DEFAULT_TOP_K) -> List[Dict[str, Any]]: + """Top-k retrieval hits for the described problem; [] if retrieval fails.""" + if not query.strip(): + return [] + try: + return retrieval_search.search(query, k=k) + except Exception: # noqa: BLE001 — retrieval must never break drafting + return [] + + +def build_env_block(commit_info: str = "") -> Dict[str, str]: + """Environment facts assembled from pure local file reads only.""" + commit_info = commit_info or read_commit_info() + branch = "" + if "(branch " in commit_info: + branch = commit_info.split("(branch ", 1)[1].rstrip(")") + return { + "distro": read_os_release(), + "caelestia_version": read_shell_version(), + "branch": branch, + "commit": commit_info.split(" ", 1)[0] if commit_info else "", + } + + +def _print_similar(hits: List[Dict[str, Any]]) -> None: + print("Similar existing material (local offline index — advisory only; nothing was sent anywhere):") + if not hits: + print(" (no hits)") + return + for i, hit in enumerate(hits, 1): + print(f" {i}. {hit.get('doc_id', '?')} score {hit.get('score', 0)} {hit.get('title', '')}") + if hit.get("source"): + print(f" source: {hit['source']}") + if hit.get("snippet"): + print(f" snippet: {hit['snippet']}") + print("The template asks you to search existing issues first;") + print("give an existing one a thumbs up instead of filing a duplicate.") + + +def run_list_similar(args: argparse.Namespace, stdin_text: Optional[str]) -> int: + query = " ".join(part for part in [args.title or "", gather_description(args, stdin_text)] if part) + hits = fetch_similar(query, k=getattr(args, "k", LIST_SIMILAR_TOP_K)) + _print_similar(hits) + return 0 + + +def run_draft(args: argparse.Namespace, stdin_text: Optional[str]) -> int: + description = gather_description(args, stdin_text) + query_text = " ".join(part for part in [args.title, description] if part) + + if args.list_similar: + _print_similar(fetch_similar(query_text, k=DEFAULT_TOP_K)) + print("(--list-similar mode: no draft composed, no file written)") + return 0 + + if not description: + print("error: empty description — pass --from-file PATH or pipe the description on stdin", file=sys.stderr) + return 2 + similar = fetch_similar(query_text, k=DEFAULT_TOP_K) + + commit_info = read_commit_info() + env_block = build_env_block(commit_info) + generated_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S") + draft_text = template.render_draft( + issue_type=args.type, + title=args.title, + body=description, + env_block=env_block, + similar=similar, + commit_info=commit_info or None, + generated_at=generated_at, + ) + + if not args.confirm: + print(draft_text, end="") + print("(preview only — no file written; pass --confirm to write the draft to a local file)") + return 0 + + out_path = Path(args.out) if args.out else default_draft_path() + out_path.parent.mkdir(parents=True, exist_ok=True) + out_path.write_text(draft_text, encoding="utf-8") + print(f"Draft written: {out_path}") + print("Reminder: nothing was submitted anywhere — the assistant cannot file issues.") + print("Review the draft, then copy-paste it into GitHub's new-issue form yourself.") + return 0 + + +def build_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser( + prog="python3 -m assistant.capabilities.issues.cli", + description="Issue-DRAFTING helper: composes paste-ready issue text. Drafts only, local files only.", + epilog=EPILOG, + ) + sub = parser.add_subparsers(dest="command", required=True) + + draft = sub.add_parser("draft", help="compose an issue draft (preview by default)") + draft.add_argument("--title", required=True, help="proposed issue title") + draft.add_argument("--type", choices=["bug", "feature"], default="bug", help="issue template (default: bug)") + draft.add_argument("--from-file", default=None, help="read the problem description from PATH (else stdin)") + draft.add_argument("--out", default=None, help="write the draft to PATH (default under XDG_DATA_HOME)") + draft.add_argument("--confirm", action="store_true", help="write the draft file (without it: preview only)") + draft.add_argument("--list-similar", action="store_true", help="print retrieval hits only; no draft, no file") + draft.set_defaults(func=run_draft) + + similar = sub.add_parser("list-similar", help="print retrieval hits for a described problem (no file write)") + similar.add_argument("--title", default="", help="short description of the problem") + similar.add_argument("--from-file", default=None, help="read a longer description from PATH (else stdin)") + similar.add_argument("-k", type=int, default=LIST_SIMILAR_TOP_K, help="number of hits (default 5)") + similar.set_defaults(func=run_list_similar) + return parser + + +def main(argv: Optional[List[str]] = None, stdin_text: Optional[str] = None) -> int: + """Entry point. stdin_text overrides sys.stdin (tests pass text directly).""" + parser = build_parser() + args = parser.parse_args(argv) + stdin_payload = stdin_text + if stdin_payload is None and not getattr(args, "from_file", None) and not sys.stdin.isatty(): + stdin_payload = sys.stdin.read() + return int(args.func(args, stdin_payload)) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/plugins/caelestia-assistant/assistant/capabilities/issues/manifest.py b/plugins/caelestia-assistant/assistant/capabilities/issues/manifest.py new file mode 100644 index 0000000..3679426 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/capabilities/issues/manifest.py @@ -0,0 +1,10 @@ +"""Manifest for the issues capability: permissions, risk tier, budgets.""" +from assistant.capabilities._registry import CapManifest + +MANIFEST = CapManifest( + name="issues", + permissions=("fs:write-drafts-only", "fs:read",), + risk_tier="journaled", + latency_budget_ms=500, + memory_budget_mb=40, +) diff --git a/plugins/caelestia-assistant/assistant/capabilities/issues/template.py b/plugins/caelestia-assistant/assistant/capabilities/issues/template.py new file mode 100755 index 0000000..48e3fa0 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/capabilities/issues/template.py @@ -0,0 +1,409 @@ +"""Issue-template loading and draft rendering for Layer 4 (drafting only). + +Guarantees: +- Pure stdlib, offline, deterministic: identical inputs always render an + identical draft. No parsing library is used — the two GitHub issue + templates (.github/ISSUE_TEMPLATE/1-issue.yml, 2-feature_request.yml) are + extracted with a hand-rolled, line-based reader that only understands the + shapes actually present in those two files (top-level name/description; + a body list of markdown / checkboxes / textarea / input items with label, + description, placeholder, value, options and validations.required). +- Clear failure mode: if the template files are missing, unreadable, or the + line-based reader finds nothing it recognises, load_template falls back to + hardcoded mirrors of the two templates (FALLBACK_* below) so a draft can + always be rendered. +- This module RENDERS TEXT and nothing else: no network, no subprocess, no + filesystem writes (writing is the CLI's job, behind --confirm). +""" + +from __future__ import annotations + +import re +from pathlib import Path +from typing import Any, Dict, List, Optional, Tuple + +from . import BUG_TEMPLATE_FILE, FEATURE_TEMPLATE_FILE + +# Exact banner that starts every rendered draft and every written file. +BANNER = ( + "DRAFT — NOT SUBMITTED TO ANYWHERE. Review, then copy-paste into GitHub's " + "new-issue form yourself. This file was created by the caelestia assistant (offline)." +) + +# Advisory dedup threshold: if the top retrieval hit scores above this, the +# draft header gains a "possible duplicate" warning line. Advisory only — +# drafting is never blocked. +DUPLICATE_WARN_SCORE = 8.0 + +# Commands the assistant would otherwise have to run to fill in logs. They are +# NEVER executed here; they are rendered as inert SUGGESTED_NOT_EXECUTED lines. +SUGGESTED_COMMANDS = [ + "journalctl --user -u caelestia-shell --no-pager -n 100", + "plasmashell --version", + "quickshell --version", +] + +VERSION_FILE_SUGGESTION = "cat ~/.config/caelestia/version" + +TEMPLATE_FILES = {"bug": BUG_TEMPLATE_FILE, "feature": FEATURE_TEMPLATE_FILE} + +GITHUB_ISSUES_URL = "https://github.com/ladybug-me/caelestia-kde/issues" + +# --------------------------------------------------------------------------- +# Hardcoded mirrors (fallback when the yml files cannot be parsed) +# --------------------------------------------------------------------------- + +FALLBACK_BUG_META = {"name": "Bug report", "description": "Something's not working right"} +FALLBACK_BUG_FIELDS: List[Dict[str, Any]] = [ + { + "kind": "markdown", + "value": ( + "Thanks for taking the time to report a bug!\n\nA quick search of [existing issues]" + f"({GITHUB_ISSUES_URL}?q=is%3Aissue) helps avoid duplicates - if you find one," + " give it a thumbs up instead." + ), + }, + { + "kind": "checkboxes", + "label": "Issue type", + "description": "Pick one label that best describes this issue.", + "options": [ + "Bug - something is broken or not working correctly", + "Help wanted - I need assistance with configuration, setup, or usage", + ], + "required": True, + }, + { + "kind": "textarea", + "label": "What happened?", + "description": "What went wrong? What did you expect instead?", + "placeholder": ( + 'The launcher froze when I typed "terminal" and pressed Enter. ' + "I expected it to open Konsole." + ), + "required": True, + }, + { + "kind": "textarea", + "label": "Steps to reproduce", + "description": "How can someone else trigger this?", + "placeholder": '1. Open the launcher (Super+Space)\n2. Type "terminal"\n3. Press Enter', + "required": False, + }, + { + "kind": "input", + "label": "Caelestia version", + "description": ( + "What version of Caelestia are you running? Check with `cat ~/.config/caelestia/version`" + " or look for the version string in the shell." + ), + "placeholder": "e.g. v2.2.2", + "required": True, + }, + { + "kind": "input", + "label": "Distro", + "description": "Which Linux distribution are you on?", + "placeholder": "e.g. CachyOS, Arch, Fedora", + "required": True, + }, + { + "kind": "textarea", + "label": "Logs or screenshots", + "description": ( + "If relevant, paste logs or drag in screenshots. The `caelestia-shell-ipc log`" + " command shows live shell logs." + ), + "placeholder": "Drag and drop images here, or paste log output.", + "required": False, + }, +] + +FALLBACK_FEATURE_META = {"name": "Feature request", "description": "Got an idea? We'd love to hear it"} +FALLBACK_FEATURE_FIELDS: List[Dict[str, Any]] = [ + { + "kind": "markdown", + "value": ( + "Thanks for the idea!\n\nA quick search of [existing requests](" + f"{GITHUB_ISSUES_URL}?q=is%3Aissue+label%3Afeature) avoids duplicates" + " - if you find one, give it a thumbs up instead." + ), + }, + { + "kind": "textarea", + "label": "What's the idea?", + "description": ( + "Describe what you'd like to see. Mockups, screenshots, or examples from other projects all help." + ), + "placeholder": "A widget that shows the current weather in the top bar.", + "required": True, + }, + { + "kind": "textarea", + "label": "Why would it be useful?", + "description": "What problem does it solve, or what workflow does it improve?", + "placeholder": "I check the weather frequently and hate pulling out my phone.", + "required": False, + }, +] + +# --------------------------------------------------------------------------- +# Line-based template reader (minimal YAML awareness, shape-specific) +# --------------------------------------------------------------------------- + +_BLOCK_SCALAR_KEYS = ("value", "placeholder", "description") +_ATTRIBUTE_KEYS = ("label", "description", "placeholder", "value") +_QUOTED_RE = re.compile(r"^\"(.*)\"$|^'(.*)'$") + + +def _strip_quotes(value: str) -> str: + match = _QUOTED_RE.match(value) + if match: + return match.group(1) or match.group(2) or "" + return value + + +def parse_issue_template(path: Path) -> Tuple[Dict[str, str], List[Dict[str, Any]]]: + """Extract (meta, fields) from one GitHub issue-template yml file. + + Understands ONLY the shapes present in 1-issue.yml / 2-feature_request.yml. + Returns empty items when nothing recognizable is found — the caller is + responsible for falling back to the hardcoded mirrors. + """ + template_path = Path(path) + if not template_path.is_file(): + return {}, [] + meta: Dict[str, str] = {} + fields: List[Dict[str, Any]] = [] + current: Optional[Dict[str, Any]] = None + pending_key: Optional[str] = None + pending_indent = 0 + in_body = False + in_options = False + in_validations = False + for raw in template_path.read_text(encoding="utf-8").splitlines(): + stripped = raw.strip() + if not stripped or stripped.startswith("#"): + if pending_key is not None and current is not None: + current[pending_key].append("") # keep blank lines inside block scalars + continue + indent = len(raw) - len(raw.lstrip(" ")) + if pending_key is not None and current is not None and indent >= pending_indent: + current[pending_key].append(stripped) + continue + pending_key = None + if indent == 0: + key, _, val = stripped.partition(":") + if key == "body" and not val.strip(): + in_body = True + elif key in ("name", "description") and val.strip(): + meta[key] = _strip_quotes(val.strip()) + continue + if in_body and stripped.startswith("- type:"): + current = {"kind": stripped.split(":", 1)[1].strip()} + fields.append(current) + in_options = False + in_validations = False + continue + if current is None: + continue + if in_options and stripped.startswith("- label:"): + current.setdefault("options", []).append(_strip_quotes(stripped.split(":", 1)[1].strip())) + continue + if stripped == "options:": + in_options, in_validations = True, False + continue + if stripped == "validations:": + in_validations, in_options = True, False + continue + if stripped.startswith("required:") and in_validations: + current["required"] = stripped.split(":", 1)[1].strip() == "true" + continue + for key in _ATTRIBUTE_KEYS: + if stripped.startswith(key + ":"): + val = stripped[len(key) + 1:].strip() + if val in ("|", "|-", "|+"): + pending_key = key + pending_indent = indent + 1 + current[key] = [] + elif val: + current[key] = _strip_quotes(val) + break + # Join collected block-scalar lines back into strings. + for field in fields: + for key in _BLOCK_SCALAR_KEYS: + if isinstance(field.get(key), list): + field[key] = "\n".join(field[key]).strip("\n") + return meta, fields + + +def load_template(issue_type: str) -> Tuple[Dict[str, str], List[Dict[str, Any]]]: + """Load one template; falls back to hardcoded mirrors on any failure. + + The lookup of parse_issue_template is a module-global lookup on purpose so + tests can monkeypatch it to return nothing and exercise the fallback. + """ + if issue_type not in TEMPLATE_FILES: + raise ValueError(f"unknown issue type {issue_type!r} (expected bug|feature)") + try: + meta, fields = parse_issue_template(TEMPLATE_FILES[issue_type]) + except Exception: # noqa: BLE001 — any reader failure must fall back, never crash drafting + meta, fields = {}, [] + if not fields: + if issue_type == "bug": + return dict(FALLBACK_BUG_META), [dict(f) for f in FALLBACK_BUG_FIELDS] + return dict(FALLBACK_FEATURE_META), [dict(f) for f in FALLBACK_FEATURE_FIELDS] + if "name" not in meta: + meta["name"] = "Bug report" if issue_type == "bug" else "Feature request" + return meta, fields + + +def top_hit_is_strong(similar: List[Dict[str, Any]]) -> bool: + """True when the top retrieval hit is strong enough to warn about.""" + return bool(similar) and float(similar[0].get("score", 0.0)) > DUPLICATE_WARN_SCORE + + +def _field_suffix(field: Dict[str, Any]) -> str: + required = "required" if field.get("required") else "optional" + return f"[{field['kind']}] ({required})" + + +def _fill_in_hint(field: Dict[str, Any]) -> str: + placeholder = str(field.get("placeholder", "")).replace("\n", " / ") + return f"(fill in yourself — template example: {placeholder})" if placeholder else "(fill in yourself)" + + +def _env_or_suggestion(field: Dict[str, Any], env_block: Dict[str, str]) -> List[str]: + """Fill an input/textarea field from the env block or a suggested command.""" + label = field.get("label", "") + if label == "Caelestia version": + value = env_block.get("caelestia_version", "").strip() + if value: + return [value, "(read locally from ~/.config/caelestia/version by the assistant)"] + return [ + f"SUGGESTED_NOT_EXECUTED: {VERSION_FILE_SUGGESTION}", + "(run this yourself and paste the output)", + ] + if label == "Distro": + value = env_block.get("distro", "").strip() + return [value] if value else ["(fill in — run: cat /etc/os-release)"] + if label == "Logs or screenshots": + out = ["Commands only you can run (run these yourself and paste output here if relevant):"] + out.extend(f" SUGGESTED_NOT_EXECUTED: {cmd}" for cmd in SUGGESTED_COMMANDS) + return out + return [_fill_in_hint(field)] + + +def body_label(fields: List[Dict[str, Any]]) -> str: + """Label of the template's first textarea — the field receiving the body.""" + for field in fields: + if field.get("kind") == "textarea": + return str(field.get("label", "")) + return "" + + +def _render_similar(similar: List[Dict[str, Any]]) -> List[str]: + lines = [ + "=" * 78, + "Before filing — similar existing material (advisory only, from the local offline index)", + "=" * 78, + "The template asks you to search existing issues first and give an existing one a", + "thumbs up instead of filing a duplicate. Local index hits for this problem:", + ] + if not similar: + lines.append(" (no similar material found in the local index — searching manually is still worth it)") + return lines + for hit in similar: + lines.append( + f" - {hit.get('doc_id', '?')} (score {hit.get('score', 0)}) {hit.get('title', '')}" + ) + if hit.get("source"): + lines.append(f" source: {hit['source']}") + if hit.get("snippet"): + lines.append(f" snippet: {hit['snippet']}") + lines.append("(dedup is advisory only — the assistant never blocks filing and never files anything)") + return lines + + +def _render_environment(env_block: Dict[str, str]) -> List[str]: + lines = [ + "=" * 78, + "Environment (assembled locally by the assistant — pure file reads, nothing sent anywhere)", + "=" * 78, + ] + labels = ( + ("Distro", "distro"), + ("Caelestia version", "caelestia_version"), + ("Branch", "branch"), + ("Commit", "commit"), + ) + for label, key in labels: + value = env_block.get(key, "").strip() + lines.append(f"- {label}: {value if value else '(unknown — fill in yourself)'}") + lines.append("Commands only you can run (run these yourself and paste output):") + lines.extend(f" SUGGESTED_NOT_EXECUTED: {cmd}" for cmd in SUGGESTED_COMMANDS) + return lines + + +def render_draft( + issue_type: str, + title: str, + body: str, + env_block: Dict[str, str], + similar: List[Dict[str, Any]], + commit_info: Optional[str], + generated_at: str, +) -> str: + """Render a paste-ready issue draft as markdown text. Writes nothing. + + Mirrors the real repo template (sections, labels, descriptions, options, + required-ness) field by field so each rendered section can be copied into + the matching box of GitHub's new-issue form. + """ + meta, fields = load_template(issue_type) + template_file = TEMPLATE_FILES[issue_type].name + lines: List[str] = [BANNER, f"Generated: {generated_at} (local time)"] + if commit_info: + lines.append(f"Source repo commit: {commit_info}") + desc = meta.get("description", "") + lines.append(f"Template: {meta.get('name', issue_type)} ({desc}) — mirrors .github/ISSUE_TEMPLATE/{template_file}") + lines.append(f"Proposed title: {title}") + if top_hit_is_strong(similar): + lines.append(f"possible duplicate — check {similar[0].get('doc_id', '?')} first (see similar section below)") + lines.append("") + + for field in fields: + if field.get("kind") == "markdown": + lines.append("Template notice (from the template itself):") + for md_line in str(field.get("value", "")).splitlines(): + lines.append(f" {md_line}" if md_line else "") + lines.append("") + continue + lines.append("-" * 78) + number = sum(1 for ln in lines if ln.startswith("### ")) + lines.append(f"### {number + 1}. {field.get('label', '?')} {_field_suffix(field)}") + if field.get("description"): + lines.append(f" ") + if field.get("kind") == "checkboxes": + for option in field.get("options", []): + tick = "[x]" if issue_type == "bug" and option.startswith("Bug") else "[ ]" + lines.append(f" {tick} {option}") + elif field.get("kind") == "textarea" and field.get("label") == body_label(fields): + lines.append(str(body).strip() or "(empty — describe the problem)") + else: + lines.extend(_env_or_suggestion(field, env_block)) + lines.append("") + + lines.extend(_render_similar(similar)) + lines.append("") + lines.extend(_render_environment(env_block)) + lines.append("") + lines.append("-" * 78) + lines.append( + "Reminder: this draft exists only as a local file on this machine. Nothing was posted, sent," + ) + lines.append( + "or transmitted anywhere — the assistant has no way to file issues. You file it yourself" + ) + lines.append("by copy-pasting the fields above into GitHub's new-issue form.") + return "\n".join(lines).rstrip() + "\n" diff --git a/plugins/caelestia-assistant/assistant/capabilities/scan/__init__.py b/plugins/caelestia-assistant/assistant/capabilities/scan/__init__.py new file mode 100644 index 0000000..717d14e --- /dev/null +++ b/plugins/caelestia-assistant/assistant/capabilities/scan/__init__.py @@ -0,0 +1,33 @@ +"""assistant.capabilities.scan — bounded-memory stream intelligence for huge logs. + +The low-end-device story: a 2 GB journalctl dump cannot be regex-scanned +rule-by-rule (O(rules x lines) and a pile of Python re machinery) and cannot +be loaded into RAM. This package answers the stream questions with the +classical probabilistic data structures — all stdlib, all with proven error +bounds, all JSON-serialisable so a scan can be paused, persisted, resumed: + +| Module | Structures | Question it answers | +| --- | --- | --- | +| `ac` | Aho-Corasick automaton (goto/fail/output) | Which of my 500 known error signatures appear anywhere in this stream, in ONE pass, at O(lines) regardless of rule count? | +| `bloom` | Bloom filter (double hashing over hashlib) | Have I seen this exact error line before? (no false negatives, tunable false-positive rate) | +| `sketch` | Count-Min Sketch | Approximate token frequencies under a fixed memory cap, with the epsilon bound | +| `sketch` | HyperLogLog (flajolet) | How many DISTINCT error lines/hosts/units in the stream, ~1-2% typical error? | +| `sketch` | Reservoir sampler | A uniform random sample of k matching lines from a stream of unknown length (Vitter R) | +| `sketch` | EWMA + Page-Hinkley | Is the error rate stable, or has something just changed? (change-point alarm) | + +`scanner.scan_stream` composes all of them: one pass over the lines, a +summary dict out. Nothing here executes anything, reads anything but the +caller-provided line iterable, or needs the whole file in memory. +""" +from .ac import Automaton +from .bloom import BloomFilter +from .simhash import NearDupTracker, hamming, near_duplicate, simhash +from .sketch import (CountMinSketch, HyperLogLog, Reservoir, EWMA, + page_hinkley) +from .scanner import scan_stream, scan_text, render + +__all__ = [ + "Automaton", "BloomFilter", "CountMinSketch", "HyperLogLog", "Reservoir", + "EWMA", "page_hinkley", "scan_stream", "scan_text", "render", + "simhash", "hamming", "near_duplicate", "NearDupTracker", +] diff --git a/plugins/caelestia-assistant/assistant/capabilities/scan/__main__.py b/plugins/caelestia-assistant/assistant/capabilities/scan/__main__.py new file mode 100644 index 0000000..bfdcd0c --- /dev/null +++ b/plugins/caelestia-assistant/assistant/capabilities/scan/__main__.py @@ -0,0 +1,4 @@ +from .cli import main + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/plugins/caelestia-assistant/assistant/capabilities/scan/ac.py b/plugins/caelestia-assistant/assistant/capabilities/scan/ac.py new file mode 100644 index 0000000..e77d6cd --- /dev/null +++ b/plugins/caelestia-assistant/assistant/capabilities/scan/ac.py @@ -0,0 +1,124 @@ +"""scan.ac — Aho-Corasick multi-pattern matcher. + +Builds the goto/fail/output automaton ONCE over every known signature +(keyword anchors) and then scans any amount of text in a single pass: +O(len(text) + matches) INDEPENDENT of the number of patterns. This is the +algorithmic difference between "scan my 2 GB journal against the 500 known +caelestia signatures" being impossible and being trivial. + +The implementation is the standard dictionary-automaton: + + 1. goto: trie over the patterns + 2. fail: BFS-computed failure links (longest proper suffix that is also + a pattern prefix) + 3. output: per-state pattern ids, plus dictionary-output chaining so a + single position reports every pattern ending there + +Deterministic; matches reported as (end_index, pattern_id). Also exposes +`first_match` for hot loops. +""" +from __future__ import annotations + +from collections import deque +from typing import Dict, Iterable, List, Optional, Tuple + +__all__ = ["Automaton"] + +_FAILURE = "\0__fail__" # sentinel key outside the byte/alphabet space + + +class Automaton: + """Aho-Corasick automaton over literal patterns (bytes/str, casefolded + if built with ignore_case=True).""" + + def __init__(self, patterns: Iterable[str], ignore_case: bool = True) -> None: + self.ignore_case = ignore_case + self._patterns: List[str] = [] + self._goto: List[Dict[str, int]] = [{}] + self._fail: List[int] = [0] + self._out: List[List[int]] = [[]] + for pat in patterns: + self.add(pat) + self._build() + + # ------------------------------------------------------------------ + def add(self, pattern: str) -> int: + """Add one pattern (call before `finalize`/matching; the automaton + rebuilds lazily). Returns the pattern id.""" + if self.ignore_case: + pattern = pattern.casefold() + pid = len(self._patterns) + self._patterns.append(pattern) + state = 0 + for ch in pattern: + nxt = self._goto[state].get(ch) + if nxt is None: + self._goto.append({}) + self._fail.append(0) + self._out.append([]) + nxt = len(self._goto) - 1 + self._goto[state][ch] = nxt + state = nxt + self._out[state].append(pid) + self._dirty = True + return pid + + # ------------------------------------------------------------------ + def _build(self) -> None: + """BFS the trie, wiring failure links and merging dictionary outputs.""" + queue: deque = deque() + for ch, s in self._goto[0].items(): + self._fail[s] = 0 + queue.append(s) + while queue: + r = queue.popleft() + for ch, s in self._goto[r].items(): + queue.append(s) + f = self._fail[r] + while f and ch not in self._goto[f]: + f = self._fail[f] + self._fail[s] = self._goto[f].get(ch, 0) + if self._fail[s] == s: + self._fail[s] = 0 + self._out[s] = self._out[s] + self._out[self._fail[s]] + self._dirty = False + + def _ensure_built(self) -> None: + if getattr(self, "_dirty", False): + self._build() + + # ------------------------------------------------------------------ + def scan(self, text: str) -> List[Tuple[int, int]]: + """All matches as (end_index_exclusive, pattern_id), non-overlapping + per position but exhaustive across the dictionary-output chain.""" + self._ensure_built() + if self.ignore_case: + text = text.casefold() + hits: List[Tuple[int, int]] = [] + state = 0 + for i, ch in enumerate(text, 1): + while state and ch not in self._goto[state]: + state = self._fail[state] + state = self._goto[state].get(ch, 0) + for pid in self._out[state]: + hits.append((i, pid)) + return hits + + def first_match(self, text: str) -> Optional[Tuple[int, int]]: + self._ensure_built() + if self.ignore_case: + text = text.casefold() + state = 0 + for i, ch in enumerate(text, 1): + while state and ch not in self._goto[state]: + state = self._fail[state] + state = self._goto[state].get(ch, 0) + if self._out[state]: + return (i, self._out[state][0]) + return None + + def pattern(self, pid: int) -> str: + return self._patterns[pid] + + def count(self) -> int: + return len(self._patterns) diff --git a/plugins/caelestia-assistant/assistant/capabilities/scan/bloom.py b/plugins/caelestia-assistant/assistant/capabilities/scan/bloom.py new file mode 100644 index 0000000..4d246ea --- /dev/null +++ b/plugins/caelestia-assistant/assistant/capabilities/scan/bloom.py @@ -0,0 +1,70 @@ +"""scan.bloom — a Bloom filter over hashlib (double hashing, Kirsch-Mitzenmacher). + +"No false negatives, bounded false positives": if `__contains__` says a line +was never seen, that is CERTAIN; if it says maybe-seen, the false-positive +rate is at most (1 - e^(-kn/m))^k — for the defaults here (1% target) that is +the expected order. Used by the scanner to deduplicate repeated error lines +in a journal without storing the lines themselves. + +Memory is m bits in a bytearray — for 1M entries at 1% FPR that is ~1.2 MB, +constant regardless of how long the entries are. +""" +from __future__ import annotations + +import hashlib +import math +from typing import Any, Dict + +__all__ = ["BloomFilter"] + + +class BloomFilter: + def __init__(self, capacity: int = 100_000, error_rate: float = 0.01) -> None: + if capacity <= 0 or not (0.0 < error_rate < 1.0): + raise ValueError("capacity > 0 and 0 < error_rate < 1 required") + m = -capacity * math.log(error_rate) / (math.log(2.0) ** 2) + self.m = max(8, int(math.ceil(m))) + self.k = max(1, int(round((self.m / capacity) * math.log(2.0)))) + self.bits = bytearray((self.m + 7) // 8) + self.n = 0 + + # ------------------------------------------------------------------ + def _hashes(self, item: str): + h1 = int.from_bytes(hashlib.sha256(item.encode("utf-8")).digest()[:8], "big") + h2 = int.from_bytes(hashlib.md5(item.encode("utf-8")).digest()[:8], "big") + return ((h1 + i * h2) % self.m for i in range(1, self.k + 1)) + + def _setbit(self, idx: int) -> None: + self.bits[idx >> 3] |= 1 << (idx & 7) + + def _getbit(self, idx: int) -> int: + return (self.bits[idx >> 3] >> (idx & 7)) & 1 + + # ------------------------------------------------------------------ + def add(self, item: str) -> None: + for h in self._hashes(item): + self._setbit(h) + self.n += 1 + + def __contains__(self, item: str) -> bool: + return all(self._getbit(h) for h in self._hashes(item)) + + def add_if_absent(self, item: str) -> bool: + """Add and report whether it was (probably) new — the dedup fast path.""" + if item in self: + return False + self.add(item) + return True + + # ------------------------------------------------------------------ + + def to_dict(self) -> Dict[str, Any]: + return {"m": self.m, "k": self.k, "n": self.n, + "bits": self.bits.hex()} + + @classmethod + def from_dict(cls, d: Dict[str, Any]) -> "BloomFilter": + bf = cls.__new__(cls) + bf.m, bf.k, bf.n = d["m"], d["k"], d["n"] + bf.bits = bytearray.fromhex(d["bits"]) + return bf diff --git a/plugins/caelestia-assistant/assistant/capabilities/scan/cli.py b/plugins/caelestia-assistant/assistant/capabilities/scan/cli.py new file mode 100644 index 0000000..e0f48a9 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/capabilities/scan/cli.py @@ -0,0 +1,98 @@ +"""scan.cli — command surface for the stream scanner. + + python3 -m assistant.capabilities.scan FILE [--pattern "quickshell crashed"] [--json] + python3 -m assistant.capabilities.scan --demo # synthetic stream, no file + cat journal.log | python3 -m assistant.capabilities.scan + +Read-only over the caller-provided stream; nothing executes, nothing leaves +the machine. The default pattern set ships the well-known caelestia/Quickshell +anchors so `caelestia-assist scan journal.log` is useful with zero setup. +""" +from __future__ import annotations + +import argparse +import json +import sys +from typing import List, Optional + +from .ac import Automaton +from .scanner import render, scan_stream + +DEFAULT_PATTERNS: List[str] = [ + "quickshell has crashed", + "quickshell", + "pragma", + "signal handoff", + "sigsegv", + "segfault", + "cannot open", + "no such file or directory", + "permission denied", + "failed to", + "error", + "critical", + "journal", + "vesktop", + "gamescope", + "pacman", + "wayland", + "kwin", + "dbus", + "timeout", +] + + +def build_parser() -> argparse.ArgumentParser: + p = argparse.ArgumentParser( + prog="assistant.capabilities.scan", + description="One-pass bounded-memory log scanner (Aho-Corasick + " + "Bloom + Count-Min + HyperLogLog + reservoir + Page-Hinkley)") + p.add_argument("file", nargs="?", help="log file to scan ('-' or omitted = stdin)") + p.add_argument("--pattern", action="append", default=[], + help="extra literal pattern to track (repeatable)") + p.add_argument("--chunk", type=int, default=500, help="lines per rate chunk") + p.add_argument("--json", action="store_true", help="machine output") + p.add_argument("--demo", action="store_true", + help="scan a synthetic demo stream instead of a file") + return p + + +def _demo_lines() -> List[str]: + lines: List[str] = [] + for i in range(2000): + if i % 97 == 0: + lines.append(f"sep 25 10:{i % 60:02d} quickshell[666]: error: QML Quickshell: something (demo)") + elif i % 211 == 0: + lines.append("kwin_wayland: dbus call failed: timeout") + else: + lines.append(f"systemd[1]: normal demo line {i} doing nothing interesting") + # a mid-stream burst so Page-Hinkley has something honest to find + for i in range(300): + lines.insert(1200, "quickshell has crashed: signal handoff (demo burst)") + return lines + + +def main(argv: Optional[List[str]] = None) -> int: + args = build_parser().parse_args(argv) + patterns = list(DEFAULT_PATTERNS) + list(args.pattern) + auto = Automaton(patterns) + + if args.demo: + lines: List[str] = _demo_lines() + else: + if args.file and args.file != "-": + with open(args.file, "r", encoding="utf-8", errors="replace") as fh: + lines = fh.readlines() + else: + lines = sys.stdin.readlines() + + summary = scan_stream(lines, auto, chunk_size=max(10, args.chunk)) + if args.json: + print(json.dumps(summary, indent=2)) + else: + print(render(summary)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/plugins/caelestia-assistant/assistant/capabilities/scan/manifest.py b/plugins/caelestia-assistant/assistant/capabilities/scan/manifest.py new file mode 100644 index 0000000..b8b417b --- /dev/null +++ b/plugins/caelestia-assistant/assistant/capabilities/scan/manifest.py @@ -0,0 +1,10 @@ +"""Manifest for the scan capability: permissions, risk tier, budgets.""" +from assistant.capabilities._registry import CapManifest + +MANIFEST = CapManifest( + name="scan", + permissions=("fs:read-one-pass",), + risk_tier="read_only", + latency_budget_ms=400, + memory_budget_mb=40, +) diff --git a/plugins/caelestia-assistant/assistant/capabilities/scan/scanner.py b/plugins/caelestia-assistant/assistant/capabilities/scan/scanner.py new file mode 100644 index 0000000..0e340c0 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/capabilities/scan/scanner.py @@ -0,0 +1,165 @@ +"""scan.scanner — the one-pass stream scanner composing every structure. + + from assistant.capabilities.scan import Automaton, scan_stream + auto = Automaton(["quickshell has crashed", "pragma", "signal handoff"]) + summary = scan_stream(lines, auto) + +`scan_stream` walks the line iterable exactly once and returns a plain dict: +per-pattern hit counts, unique-line tracking (Bloom), distinct-line estimate +(HLL), token frequency sketch (Count-Min), a reservoir of example lines, and +the EWMA + Page-Hinkley rate-drift alarm over fixed-size chunks. For the QML +bridge the same dict is what `{"op":"scan_text"}` returns. + +Nothing is executed, nothing is stored beyond the bounded structures, and a +2 GB log and a 2 KB log cost the same RAM. +""" +from __future__ import annotations + +from typing import Any, Dict, Iterable, List, Optional + +from .ac import Automaton +from .bloom import BloomFilter +from .sketch import (CountMinSketch, HyperLogLog, NgramDivergence, + Reservoir, EWMA, page_hinkley) + +__all__ = ["scan_stream", "scan_text", "render"] + +_STOP = {"the", "a", "an", "and", "or", "of", "to", "in", "on", "for", "is", + "at", "by", "with", "from", "was", "were", "be", "this", "that", + "it", "as", "not", "but", "are", "into", "my"} + + +def scan_stream(lines: Iterable[str], automaton: Automaton, + chunk_size: int = 500, reservoir_k: int = 40, + bloom_capacity: int = 200_000, + token_top_candidates: Optional[List[str]] = None, + novelty: bool = False, novelty_block_lines: int = 500, + ) -> Dict[str, Any]: + """One pass over `lines`; the returned summary is JSON-serialisable. + + ``novelty=True`` (opt-in, B1) adds a "novelty" section: the windowed + KL divergence of the log's token n-gram distribution per block against + the running baseline (previous block + the scanner's Count-Min), plus + a Page-Hinkley alarm over the KL series. Still one pass, still bounded + RAM (two block-sized dicts); the default summary is unchanged.""" + bloom = BloomFilter(capacity=bloom_capacity) + hll = HyperLogLog(precision=12) + cms = CountMinSketch(epsilon=0.002, delta=0.001) + reservoir = Reservoir(k=reservoir_k) + ewma = EWMA(alpha=0.05) + divergence = NgramDivergence(block_lines=novelty_block_lines) if novelty else None + novelty_blocks: List[Dict[str, Any]] = [] + + hits_by_pattern: Dict[int, int] = {} + lines_total = 0 + matching = 0 + unique_matching = 0 + chunk_counts: List[int] = [] + cur_chunk = 0 + tokens: List[str] = [] + + for raw in lines: + line = raw.rstrip("\n") + lines_total += 1 + if divergence is not None: + report = divergence.offer(line) + if report is not None: + novelty_blocks.append(report) + hits = automaton.scan(line) + cur_chunk += len(hits) + for _, pid in hits: + hits_by_pattern[pid] = hits_by_pattern.get(pid, 0) + 1 + if hits: + matching += 1 + reservoir.offer(line) + norm = line.strip().lower() + hll.add(norm) + if bloom.add_if_absent(norm): + unique_matching += 1 + for tok in norm.replace(":", " ").replace(",", " ").split(): + if tok not in _STOP and len(tok) > 2 and not tok.isdigit(): + cms.add(tok) + tokens.append(tok) + if lines_total % chunk_size == 0: + chunk_counts.append(cur_chunk) + ewma.update(cur_chunk / chunk_size) + cur_chunk = 0 + + if lines_total % chunk_size: + chunk_counts.append(cur_chunk) + ewma.update(cur_chunk / max(1, lines_total % chunk_size)) + + drift = page_hinkley([c / float(chunk_size) for c in chunk_counts], + threshold=4.0, min_instances=10) + top: List[List[Any]] = [] + if token_top_candidates: + for cnt, tok in cms.top_candidates(token_top_candidates, k=12): + top.append([tok, cnt]) + + summary = { + "lines_scanned": lines_total, + "lines_matching": matching, + "unique_matching_estimate": round(hll.count()), + "unique_matching_exact_new": unique_matching, + "pattern_hits": [ + {"pattern": automaton.pattern(pid), "hits": n} + for pid, n in sorted(hits_by_pattern.items(), key=lambda kv: -kv[1]) + ], + "top_tokens": top, + "examples": reservoir.sample, + "rate": { + "ewma_per_line": round(ewma.mean, 6) if ewma.mean is not None else None, + "page_hinkley_change_at_chunk": drift["change_at"], + "chunks": len(chunk_counts), + }, + "state": { + "bloom": bloom.to_dict(), + "hll": hll.to_dict(), + "cms": cms.to_dict(), + "reservoir": reservoir.to_dict(), + "ewma": ewma.to_dict(), + }, + } + if divergence is not None: + summary["novelty"] = { + "blocks": novelty_blocks, + "last_vs_cms": divergence.kl_vs_cms(), + "alarm": divergence.alarm(), + } + return summary + + +def scan_text(text: str, automaton: Automaton, **kwargs: Any) -> Dict[str, Any]: + return scan_stream(text.splitlines(), automaton, **kwargs) + + +# --------------------------------------------------------------------------- +def render(summary: Dict[str, Any]) -> str: + """Human renderer — mirrors the other layers' plain-text style.""" + out: List[str] = [] + n = summary["lines_scanned"] + m = summary["lines_matching"] + out.append(f"scanned {n} lines; {m} matched known signatures " + f"({summary['unique_matching_estimate']} distinct by HLL estimate)") + hits = summary["pattern_hits"] + if hits: + out.append("signature hits:") + for h in hits[:10]: + out.append(f" {h['hits']:>6} {h['pattern']}") + if summary["top_tokens"]: + toks = ", ".join(f"{t}({c})" for t, c in summary["top_tokens"][:8]) + out.append(f"dominant tokens (Count-Min): {toks}") + rate = summary["rate"] + if rate["page_hinkley_change_at_chunk"] is not None: + out.append(f"RATE CHANGE: Page-Hinkley alarmed at chunk " + f"{rate['page_hinkley_change_at_chunk']} — the error rate " + f"shifted partway through this stream") + if summary["examples"]: + out.append("sampled matching lines (reservoir):") + for line in summary["examples"][:5]: + shown = line if len(line) <= 110 else line[:107] + "..." + out.append(f" {shown}") + if not hits: + out.append("no known signature matched; run: caelestia-assist diagnose " + "with a pasted excerpt for the full rule engine") + return "\n".join(out) diff --git a/plugins/caelestia-assistant/assistant/capabilities/scan/simhash.py b/plugins/caelestia-assistant/assistant/capabilities/scan/simhash.py new file mode 100644 index 0000000..7613eee --- /dev/null +++ b/plugins/caelestia-assistant/assistant/capabilities/scan/simhash.py @@ -0,0 +1,204 @@ +"""scan.simhash — SimHash fingerprints for near-duplicate text detection. + +A 64-bit fingerprint per text; two texts are NEAR DUPLICATES when their +fingerprints differ in at most ``threshold`` bit positions (Hamming +distance). This is the classical web-scale near-duplicate construction: +SimHash itself is Charikar's rounding technique ("Similarity Estimation +Techniques from Rounding Algorithms", STOC 2002), and its use for +near-duplicate detection at scale — 64-bit fingerprints, Hamming distance +<= 3 — is Manku, Jain & Das Sarma ("Detecting Near-Duplicates for Web +Crawling", WWW 2007). + +WHY THIS MODULE (and not an existing one) — the non-duplication note: + +- ``scan.bloom.BloomFilter`` answers EXACT-seen ("have I seen this exact + line?"), with no notion of similarity; a repeated line with a new PID + or timestamp is a new line to it. +- ``brain/minhash.py`` (MinHash + LSH banding) estimates Jaccard over + shingle sets for the PERSONAL-NOTES module, storing a 64-permutation + signature per document. Different layer, different data, heavier + per-document state. +- SimHash here is the stream-side answer: ONE machine word per text — + 64x smaller than a MinHash signature — cheap enough to keep a + fingerprint for every line of a bounded window, which is exactly what + a bounded-memory log/clipboard scan needs. scan/ had no near-duplicate + structure at all before this module. + +Construction (deterministic, stdlib only): tokens are lowercase word +runs with their counts as weights (a text with fewer than two word +tokens falls back to character 3-grams, so short/garbled lines still +fingerprint stably); each token is hashed with blake2b (64-bit digest) +and its weight is added to / subtracted from per-bit accumulators; the +fingerprint bit is the sign of each accumulator. Order-independent in +the tokens (a set-similarity signal, like Jaccard over token multisets), +sensitive to token-mass shifts, and stable across rewording of +connective text. + +HONEST OPERATING-POINT NOTE (measured, 2026-09-26): Hamming <= 3 is +Manku et al.'s operating point for LONG documents, where a one-word +edit barely moves the fingerprint. A log line has too little feature +mass for that: swapping "pid 1234, attempt 1" for "pid 9183, attempt 2" +measures ~15 bits apart on the raw text. The domain-correct fix is the +one journal dedup tools use — mask the volatile fields first: +``mask_digits=True`` replaces every digit run with ``#`` before +tokenizing, and those same two lines then fingerprint IDENTICALLY +(distance 0). ``NearDupTracker`` masks digits by default (its charter +is log/clipboard streams); ``simhash()`` defaults to the raw text and +takes the flag explicitly. Very short texts (< ~4 word tokens) carry +too little mass for ANY small threshold — mask or accept exact-match +semantics only. + +Deferred with a measured reason: perceptual-hash-for-images. The cost +is NOT the blocker — measured on this machine (2026-09-26), a stdlib +pHash of a 1920x1080 PNG costs ~0.02 s (zlib IDAT decode ~0.01 s, +32x32 luminance sample ~0.000 s, naive 32x32 DCT ~0.013 s). The blocker +is format coverage: wallpapers in the wild are heavily JPEG, and the +stdlib-only dependency set provides no JPEG +decoder, so a pHash here would silently cover only PNG — a partial +feature pretending to be a general one. If image near-dup matters +later, revisit with the coverage question answered first. +""" + +from __future__ import annotations + +import hashlib +import re +from collections import deque +from typing import Any, Dict, List, Optional + +__all__ = ["simhash", "hamming", "near_duplicate", "NearDupTracker", + "mask_digits"] + +_WORD_RE = re.compile(r"\w+", re.UNICODE) +# Volatile-field normalization for log-style text: every digit run +# (timestamps, PIDs, counters) collapses to '#' — the same idea journal +# dedup tools use, applied BEFORE tokenization. +_DIGIT_RE = re.compile(r"\d+") + +DEFAULT_BITS = 64 +DEFAULT_THRESHOLD = 3 # Manku et al.'s operating point for 64-bit fingerprints + + +def mask_digits(text: str) -> str: + """Replace every digit run with '#' (volatile-field normalization).""" + return _DIGIT_RE.sub("#", text) + + +def _tokens(text: str, masked: bool) -> List[str]: + """Lowercase word tokens; character 3-gram fallback for texts with + fewer than two word tokens (short or non-word lines still fingerprint).""" + if masked: + text = mask_digits(text) + words = _WORD_RE.findall(text.lower()) + if len(words) >= 2: + return words + compact = re.sub(r"\s+", "", text.lower()) + if len(compact) < 3: + return [compact] if compact else [] + return [compact[i:i + 3] for i in range(len(compact) - 2)] + + +def simhash(text: str, bits: int = DEFAULT_BITS, + mask_digits: bool = False) -> int: + """The SimHash fingerprint of ``text`` as an int with ``bits`` bits + (64 by default — one machine word). ``mask_digits=True`` normalizes + volatile numeric fields away first (see the module's operating-point + note). Deterministic: a pure function of the text, no seeding, no + state.""" + if bits < 8 or bits > 64: + raise ValueError("bits must be in [8, 64] (one word's worth)") + counts: Dict[str, int] = {} + for token in _tokens(text, mask_digits): + counts[token] = counts.get(token, 0) + 1 + if not counts: + return 0 + digest_size = 8 # 64 bits of blake2b per token, exactly one block + accum = [0] * bits + for token, weight in counts.items(): + h = int.from_bytes( + hashlib.blake2b(token.encode("utf-8", "replace"), + digest_size=digest_size).digest(), "big") + for i in range(bits): + accum[i] += weight if (h >> i) & 1 else -weight + out = 0 + for i in range(bits): + if accum[i] > 0: + out |= 1 << i + return out + + +def hamming(a: int, b: int) -> int: + """Bit positions in which the two fingerprints differ.""" + return bin(a ^ b).count("1") + + +def near_duplicate(a: int, b: int, threshold: int = DEFAULT_THRESHOLD) -> bool: + """Manku et al.'s operating rule: near-duplicate iff Hamming distance + is at most ``threshold`` (default 3 of 64 bits).""" + return hamming(a, b) <= threshold + + +class NearDupTracker: + """A bounded-memory near-duplicate detector over a stream of texts. + + Keeps the last ``window`` fingerprints (one machine word each) and + reports, for each observed text, whether it near-duplicates something + already in the window — the question the Bloom filter cannot answer + ("have I seen approximately this line before?") at the same order of + memory cost. JSON round-trippable like every other scan structure, so + a scan can be paused, persisted and resumed. + + A text that exactly repeats something in the window counts as a + near-duplicate too (distance 0). + """ + + def __init__(self, window: int = 500, threshold: int = DEFAULT_THRESHOLD, + bits: int = DEFAULT_BITS, mask_digits: bool = True) -> None: + if window < 1: + raise ValueError("window must be >= 1") + if threshold < 0 or threshold > bits: + raise ValueError("threshold must be in [0, bits]") + self.window = int(window) + self.threshold = int(threshold) + self.bits = int(bits) + self.mask_digits = bool(mask_digits) + self._ring: deque = deque(maxlen=self.window) + self.seen = 0 + self.near_dups = 0 + + def observe(self, text: str) -> Optional[int]: + """Fingerprint one text; returns the Hamming distance to its + nearest neighbor in the window if it is a near duplicate, else + None. O(window) bit-popcounts per line — 500 popcounts of one + machine word is the budgeted bound, no full re-comparisons. + Digit masking is ON by default: log lines whose only difference + is a PID/timestamp/count are exactly the stream case this + exists for.""" + fp = simhash(text, self.bits, self.mask_digits) + self.seen += 1 + best: Optional[int] = None + for other in self._ring: + d = hamming(fp, other) + if d <= self.threshold and (best is None or d < best): + best = d + self._ring.append(fp) + if best is not None: + self.near_dups += 1 + return best + + def to_dict(self) -> Dict[str, Any]: + return {"window": self.window, "threshold": self.threshold, + "bits": self.bits, "mask_digits": self.mask_digits, + "seen": self.seen, "near_dups": self.near_dups, + "fingerprints": list(self._ring)} + + @staticmethod + def from_dict(data: Dict[str, Any]) -> "NearDupTracker": + tracker = NearDupTracker(int(data.get("window", 500)), + int(data.get("threshold", DEFAULT_THRESHOLD)), + int(data.get("bits", DEFAULT_BITS)), + bool(data.get("mask_digits", True))) + tracker._ring.extend(int(fp) for fp in data.get("fingerprints", [])) + tracker.seen = int(data.get("seen", 0)) + tracker.near_dups = int(data.get("near_dups", 0)) + return tracker diff --git a/plugins/caelestia-assistant/assistant/capabilities/scan/sketch.py b/plugins/caelestia-assistant/assistant/capabilities/scan/sketch.py new file mode 100644 index 0000000..3738bb2 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/capabilities/scan/sketch.py @@ -0,0 +1,392 @@ +"""scan.sketch — Count-Min, HyperLogLog, reservoir sampling, EWMA, Page-Hinkley. + +Four classical stream structures, one module, all plain-data serialisable: + +- `CountMinSketch`: point-query frequencies with the (epsilon, delta) bound — + the estimate never UNDER-counts, and over-counts by at most eps*N with + probability 1-delta. Width/depth derived from the requested bounds. +- `HyperLogLog`: distinct count with ~1.04/sqrt(m) standard error using + hashlib registers and stochastic averaging (Flajolet et al. 2007). +- `Reservoir`: Vitter's algorithm R — a uniform sample of k items from a + stream of unknown length in one pass. +- `EWMA` + `page_hinkley`: exponentially weighted rate tracking and the + Page-Hinkley change detector (cumulative alarm over negative drifts) — + the honest way to say "the error rate just changed" without a model. +""" +from __future__ import annotations + +import hashlib +import math +import random +from typing import Any, Dict, List, Optional + +__all__ = ["CountMinSketch", "HyperLogLog", "Reservoir", "EWMA", + "page_hinkley"] + + +# --------------------------------------------------------------------------- +# Count-Min Sketch +# --------------------------------------------------------------------------- + +class CountMinSketch: + def __init__(self, epsilon: float = 0.002, delta: float = 0.001) -> None: + if epsilon <= 0 or not (0.0 < delta < 1.0): + raise ValueError("epsilon > 0 and 0 < delta < 1 required") + self.width = max(8, int(math.ceil(math.e / epsilon))) + self.depth = max(2, int(math.ceil(math.log(1.0 / delta)))) + self.counters = [[0] * self.width for _ in range(self.depth)] + self.total = 0 + + def _indices(self, item: str): + for d in range(self.depth): + h = hashlib.sha256(f"{d}:{item}".encode()).digest() + yield d, int.from_bytes(h[:8], "big") % self.width + + def add(self, item: str, count: int = 1) -> None: + self.total += count + for d, w in self._indices(item): + self.counters[d][w] += count + + def estimate(self, item: str) -> int: + return min(self.counters[d][w] for d, w in self._indices(item)) + + def top_candidates(self, candidates: List[str], k: int = 10) -> List[tuple]: + """Point-query a SHORTLIST (candidates must come from the caller — + a sketch cannot enumerate; honesty about that beats pretending).""" + pairs = [(self.estimate(c), c) for c in candidates] + pairs.sort(reverse=True) + return pairs[:k] + + def to_dict(self) -> Dict[str, Any]: + return {"width": self.width, "depth": self.depth, + "counters": self.counters, "total": self.total} + + @classmethod + def from_dict(cls, d: Dict[str, Any]) -> "CountMinSketch": + cms = cls.__new__(cls) + cms.width, cms.depth = d["width"], d["depth"] + cms.counters = d["counters"] + cms.total = d["total"] + return cms + + +# --------------------------------------------------------------------------- +# HyperLogLog +# --------------------------------------------------------------------------- + +class HyperLogLog: + def __init__(self, precision: int = 12) -> None: + if not (4 <= precision <= 16): + raise ValueError("precision must be in [4, 16]") + self.p = precision + self.m = 1 << precision + self.registers = [0] * self.m + + def _bucket_and_rho(self, item: str): + h = int.from_bytes(hashlib.sha256(str(item).encode()).digest(), "big") + bucket = h >> (256 - self.p) + rest = h & ((1 << (256 - self.p)) - 1) or 1 + rho = 1 + while not (rest & (1 << (255 - self.p))) and rho < 256 - self.p: + rest <<= 1 + rho += 1 + return bucket, rho + + def add(self, item: str) -> None: + bucket, rho = self._bucket_and_rho(item) + if rho > self.registers[bucket]: + self.registers[bucket] = rho + + def count(self) -> float: + m = self.m + alpha = { + 16: 0.673, 32: 0.697, 64: 0.709, + }.get(m, 0.7213 / (1.0 + 1.079 / m)) + Z = sum(2.0 ** -r for r in self.registers) + estimate = alpha * m * m / Z + zeros = self.registers.count(0) + if estimate <= 2.5 * m and zeros: + estimate = m * math.log(m / zeros) # linear counting for tiny N + return estimate + + def merge(self, other: "HyperLogLog") -> None: + if other.m != self.m: + raise ValueError("precision mismatch; cannot merge") + self.registers = [max(a, b) for a, b in zip(self.registers, other.registers)] + + def to_dict(self) -> Dict[str, Any]: + return {"p": self.p, "registers": self.registers} + + @classmethod + def from_dict(cls, d: Dict[str, Any]) -> "HyperLogLog": + hll = cls.__new__(cls) + hll.p, hll.m = d["p"], 1 << d["p"] + hll.registers = d["registers"] + return hll + + +# --------------------------------------------------------------------------- +# Reservoir sampling (Vitter R) +# --------------------------------------------------------------------------- + +class Reservoir: + def __init__(self, k: int = 50, seed: int = 7) -> None: + if k <= 0: + raise ValueError("k must be positive") + self.k = k + self.n = 0 + self.sample: List[str] = [] + self._rng = random.Random(seed) + + def offer(self, item: str) -> None: + self.n += 1 + if len(self.sample) < self.k: + self.sample.append(item) + else: + j = self._rng.randint(0, self.n - 1) + if j < self.k: + self.sample[j] = item + + def to_dict(self) -> Dict[str, Any]: + return {"k": self.k, "n": self.n, "sample": self.sample} + + @classmethod + def from_dict(cls, d: Dict[str, Any]) -> "Reservoir": + r = cls.__new__(cls) + r.k, r.n, r.sample = d["k"], d["n"], d["sample"] + r._rng = random.Random(0) + return r + + +# --------------------------------------------------------------------------- +# EWMA + Page-Hinkley change detection +# --------------------------------------------------------------------------- + +class EWMA: + """Exponentially weighted moving average of a 0/1 (or any) stream.""" + + def __init__(self, alpha: float = 0.05) -> None: + if not (0.0 < alpha <= 1.0): + raise ValueError("alpha in (0, 1]") + self.alpha = alpha + self.mean: Optional[float] = None + self.count = 0 + + def update(self, value: float) -> float: + if self.mean is None: + self.mean = value + else: + self.mean = self.alpha * value + (1.0 - self.alpha) * self.mean + self.count += 1 + return self.mean + + def to_dict(self) -> Dict[str, Any]: + return {"alpha": self.alpha, "mean": self.mean, "count": self.count} + + @classmethod + def from_dict(cls, d: Dict[str, Any]) -> "EWMA": + e = cls.__new__(cls) + e.alpha, e.mean, e.count = d["alpha"], d["mean"], d["count"] + return e + + +def page_hinkley(values: List[float], threshold: float = 12.0, + alpha: float = 0.98, delta: float = 0.005, + min_instances: int = 30) -> Dict[str, Any]: + """Page-Hinkley test for an upward mean change in a stream. + + Returns {"change_at": index or None, "magnitude": float} — change_at is + the FIRST index where the cumulative PH statistic crossed `threshold` + (with a warm-up of `min_instances`). Standard drift detector for the + "did my acceptance rate / error rate just jump?" question. The running + mean starts AT the first value (so a stream that is high from line one + is not mistaken for a rise from zero) and tracks with an EMA(alpha). + """ + if not values: + return {"change_at": None, "magnitude": 0.0, "threshold": threshold} + mean = values[0] + sum_xt = 0.0 + min_ht = math.inf + change_at: Optional[int] = None + for i, x in enumerate(values): + if i > 0: + mean = alpha * mean + (1.0 - alpha) * x + sum_xt += x - mean - delta + min_ht = min(min_ht, sum_xt) + if i >= min_instances and (sum_xt - min_ht) > threshold and change_at is None: + change_at = i + return {"change_at": change_at, + "magnitude": (sum_xt - min_ht), + "threshold": threshold} + + +class NgramDivergence: + """B1 — windowed KL novelty for one-pass log scanning. + + Distribution drift detector in the same bounded-RAM discipline as the + rest of this module: the log's token n-gram distribution is tracked + per fixed-size block (exact counts over the block's OWN vocabulary — + bounded by the block, enumerable by construction), and each full block + is compared to the running baseline by KL divergence with add-alpha + smoothing, + + D(P_block || Q_baseline) = sum_p p log(p / q) + + where Q_baseline is (a) the previous block (short-term novelty: "this + block looks different from the last one") and, when the caller wires + the scanner's Count-Min sketch, (b) the long-run running baseline + (``kl_vs_cms``) — a sketch cannot enumerate its support, but the + block's vocabulary is known exactly, so every q(p) point-query needed + by the sum is available; that is the honest way a CMS participates in + a KL (the enumerate-the-support side stays exact, the estimate side + is the sketch, with its (eps, delta) over-count bound). + + Single-pass and bounded, verified against the scanner's own charter + ("a 2 GB log and a 2 KB log cost the same RAM", scanner.py): state is + two block-sized dicts (current + reference) plus one internal running + Count-Min and HyperLogLog — never the whole stream. A 2 GB journal + and a 2 KB journal occupy the same RAM here too. + + Why an INTERNAL CMS rather than the scanner's: the scanner's sketch + only ever sees tokens from lines that MATCHED a signature, but a + novelty detector's whole job is the lines nothing matched (the new + failure mode is by definition outside the Aho-Corasick dictionary). + P and Q must be distributions over the same domain for KL to mean + anything, so this class runs its own running baseline over EVERY + line's n-grams — the scanner's own CMS stays untouched. + + Footprint (worst case, block 500 lines ~20 tokens/line): two dicts + of ~10k entries + one CMS (9,513 counters) + one HLL (4,096 + registers) — under 1 MB, independent of stream length. + """ + + def __init__(self, block_lines: int = 500, alpha: float = 0.5, + n: int = 1) -> None: + if block_lines < 1: + raise ValueError("block_lines must be >= 1") + if alpha <= 0: + raise ValueError("alpha must be > 0 (add-alpha smoothing)") + if n not in (1, 2): + raise ValueError("n must be 1 (unigrams) or 2 (bigrams)") + self.block_lines = block_lines + self.alpha = alpha + self.n = n + self._block: Dict[str, int] = {} + self._block_total = 0 + self._reference: Dict[str, int] = {} + self._reference_total = 0 + self._lines_in_block = 0 + self.kl_series: List[float] = [] + self._cms = CountMinSketch(epsilon=0.002, delta=0.001) + self._hll = HyperLogLog(precision=12) + + # ------------------------------------------------------------------ + def _ngrams(self, line: str) -> List[str]: + if self.n == 1: + return line.split() or [] + words = line.split() + return [f"{a} {b}" for a, b in zip(words, words[1:])] + + def offer(self, line: str) -> Optional[Dict[str, Any]]: + """Consume ONE line. Returns the divergence report when a block + just filled (every ``block_lines`` lines), else None.""" + for gram in self._ngrams(line): + self._block[gram] = self._block.get(gram, 0) + 1 + self._block_total += 1 + self._cms.add(gram) # the running baseline (every line) + self._hll.add(gram) + self._lines_in_block += 1 + if self._lines_in_block < self.block_lines: + return None + return self._close_block() + + def _close_block(self) -> Dict[str, Any]: + kl = self._kl(self._block, self._block_total, + self._reference, self._reference_total) + self.kl_series.append(round(kl, 6)) + report: Dict[str, Any] = { + "block_index": len(self.kl_series), + "kl_vs_previous_block": round(kl, 6), + "block_tokens": self._block_total, + "distinct_ngrams": len(self._block), + } + # The filled block becomes the next reference (bounded swap). + self._reference = self._block + self._reference_total = self._block_total + self._block = {} + self._block_total = 0 + self._lines_in_block = 0 + return report + + def _kl(self, p_counts: Dict[str, int], p_total: int, + q_counts: Dict[str, int], q_total: int) -> float: + """Add-alpha smoothed KL(P || Q) over P's exact support.""" + if not p_total or not q_total: + return 0.0 + support = set(p_counts) | set(q_counts) + vocab = len(support) + total = 0.0 + for gram, count in p_counts.items(): + p = (count + self.alpha) / (p_total + self.alpha * vocab) + q = (q_counts.get(gram, 0) + self.alpha) / (q_total + self.alpha * vocab) + total += p * math.log(p / q) + return total + + # ------------------------------------------------------------------ + def kl_vs_cms(self) -> Dict[str, Any]: + """Compare the CURRENT block against the running Count-Min + baseline (the whole stream so far, including this block's own + contribution — the standard self-inclusive streaming baseline). + + Returns per-ngram {"ngram", "block_share", "cms_share", + "lift"} rows for the biggest positive divergences (the movers a + human wants to see), sorted by lift, capped. Every row's cms + estimate is a point query (bounded over-count by the sketch's + (eps, delta) contract).""" + if not self._block_total: + return {"kl_vs_cms": 0.0, "movers": [], + "distinct_ngrams_estimate": round(self._hll.count())} + cms_total = max(1, self._cms.total) + vocab = len(self._block) + 1 + kl = 0.0 + movers: List[Dict[str, Any]] = [] + for gram, count in self._block.items(): + p = (count + self.alpha) / (self._block_total + self.alpha * vocab) + q = (self._cms.estimate(gram) + self.alpha) / (cms_total + self.alpha * vocab) + kl += p * math.log(p / q) + movers.append({ + "ngram": gram, + "block_share": round(count / self._block_total, 6), + "cms_share": round(self._cms.estimate(gram) / cms_total, 6), + "lift": round((count / self._block_total) / + max(1e-12, self._cms.estimate(gram) / cms_total), 3), + }) + movers.sort(key=lambda m: -m["lift"]) + return {"kl_vs_cms": round(kl, 6), "movers": movers[:10], + "distinct_ngrams_estimate": round(self._hll.count())} + + def alarm(self, threshold: float = 0.5, min_blocks: int = 3) -> Dict[str, Any]: + """The novelty verdict: the KL series fed to Page-Hinkley — + 'the distribution just changed', stated only after enough blocks.""" + verdict = page_hinkley(self.kl_series, threshold=threshold, + min_instances=min_blocks) + return { + "novelty_change_at_block": verdict["change_at"], + "novelty_magnitude": round(verdict["magnitude"], 6), + "kl_series": list(self.kl_series), + } + + def to_dict(self) -> Dict[str, Any]: + return {"block_lines": self.block_lines, "alpha": self.alpha, + "n": self.n, "kl_series": list(self.kl_series), + "cms": self._cms.to_dict(), "hll": self._hll.to_dict()} + + @classmethod + def from_dict(cls, d: Dict[str, Any]) -> "NgramDivergence": + nd = cls(block_lines=d["block_lines"], alpha=d["alpha"], n=d["n"]) + nd.kl_series = list(d.get("kl_series", [])) + if "cms" in d: + nd._cms = CountMinSketch.from_dict(d["cms"]) + if "hll" in d: + nd._hll = HyperLogLog.from_dict(d["hll"]) + return nd From 9ad36d558be1aeed4d33e7f6e7d1377ba3b1d492 Mon Sep 17 00:00:00 2001 From: 0x0nYx <0x0nYx@users.noreply.github.com> Date: Fri, 9 Oct 2026 12:18:56 +0000 Subject: [PATCH 04/10] feat(assistant): core NLU foundation: lexicon, concepts, features, learners, vectorization (migration chunk 3/12) The core engine's NLU foundation: lexicon and phonetics, confusables, concepts, context, features, corpus/FTS store, conformal/abers/adwin learners, CRF/slot taggers, vectorization. Everything above imports these primitives. Chunk contents (25 files): - assistant/core/__init__.py - assistant/core/abers.py - assistant/core/adwin.py - assistant/core/concepts.py - assistant/core/conformal.py - assistant/core/confusable_pairs.json - assistant/core/confusables.py - assistant/core/conservative.py - assistant/core/context.py - assistant/core/corpus.py - assistant/core/crf_tagger.py - assistant/core/dp.py - ... and 13 more Source: 0x0nYx/caelestia-assistant@2c193e7 (main, v0.1) Faithfulness: byte-identical copy (sha256-verified in the migration audit; only metadata.json / README.md are plugin-store scaffolding, and .caelestia-audit-ignore documents scanner false positives). Safety audit: 0 errors; 14 line-level findings documented in .caelestia-audit-ignore (string vocabularies / rulepack prose / test assertion targets / opt-in provider calls - nothing executes). Store CI: validate.py OK - check_safety.py OK - check_scope.py OK. Next chunk: plugin/caelestia-assistant/04-core-cortex-eval --- .../assistant/core/__init__.py | 21 + .../assistant/core/abers.py | 217 ++++++ .../assistant/core/adwin.py | 319 ++++++++ .../assistant/core/concepts.py | 287 ++++++++ .../assistant/core/conformal.py | 238 ++++++ .../assistant/core/confusable_pairs.json | 442 ++++++++++++ .../assistant/core/confusables.py | 318 ++++++++ .../assistant/core/conservative.py | 203 ++++++ .../assistant/core/context.py | 171 +++++ .../assistant/core/corpus.py | 307 ++++++++ .../assistant/core/crf_tagger.py | 374 ++++++++++ .../caelestia-assistant/assistant/core/dp.py | 328 +++++++++ .../assistant/core/features.py | 184 +++++ .../assistant/core/fts_store.py | 74 ++ .../assistant/core/guard.py | 183 +++++ .../assistant/core/label_fusion.json | 34 + .../assistant/core/label_fusion.py | 292 ++++++++ .../assistant/core/lexicon.py | 492 +++++++++++++ .../assistant/core/lexicon_diff.py | 485 +++++++++++++ .../assistant/core/memory.py | 241 +++++++ .../assistant/core/numpy_accel.py | 81 +++ .../assistant/core/phonetics.py | 67 ++ .../assistant/core/slot_tagger.py | 452 ++++++++++++ .../assistant/core/tree.py | 220 ++++++ .../assistant/core/vectorize.py | 680 ++++++++++++++++++ 25 files changed, 6710 insertions(+) create mode 100755 plugins/caelestia-assistant/assistant/core/__init__.py create mode 100644 plugins/caelestia-assistant/assistant/core/abers.py create mode 100644 plugins/caelestia-assistant/assistant/core/adwin.py create mode 100644 plugins/caelestia-assistant/assistant/core/concepts.py create mode 100644 plugins/caelestia-assistant/assistant/core/conformal.py create mode 100644 plugins/caelestia-assistant/assistant/core/confusable_pairs.json create mode 100644 plugins/caelestia-assistant/assistant/core/confusables.py create mode 100644 plugins/caelestia-assistant/assistant/core/conservative.py create mode 100644 plugins/caelestia-assistant/assistant/core/context.py create mode 100755 plugins/caelestia-assistant/assistant/core/corpus.py create mode 100644 plugins/caelestia-assistant/assistant/core/crf_tagger.py create mode 100644 plugins/caelestia-assistant/assistant/core/dp.py create mode 100644 plugins/caelestia-assistant/assistant/core/features.py create mode 100644 plugins/caelestia-assistant/assistant/core/fts_store.py create mode 100644 plugins/caelestia-assistant/assistant/core/guard.py create mode 100644 plugins/caelestia-assistant/assistant/core/label_fusion.json create mode 100644 plugins/caelestia-assistant/assistant/core/label_fusion.py create mode 100755 plugins/caelestia-assistant/assistant/core/lexicon.py create mode 100644 plugins/caelestia-assistant/assistant/core/lexicon_diff.py create mode 100755 plugins/caelestia-assistant/assistant/core/memory.py create mode 100644 plugins/caelestia-assistant/assistant/core/numpy_accel.py create mode 100644 plugins/caelestia-assistant/assistant/core/phonetics.py create mode 100644 plugins/caelestia-assistant/assistant/core/slot_tagger.py create mode 100644 plugins/caelestia-assistant/assistant/core/tree.py create mode 100755 plugins/caelestia-assistant/assistant/core/vectorize.py diff --git a/plugins/caelestia-assistant/assistant/core/__init__.py b/plugins/caelestia-assistant/assistant/core/__init__.py new file mode 100755 index 0000000..356074b --- /dev/null +++ b/plugins/caelestia-assistant/assistant/core/__init__.py @@ -0,0 +1,21 @@ +"""The cortex layer: learned intelligence for the assistant, no LLM. + +Package map (each module keeps its own guarantees docstring): + +- ``lexicon`` morphology + fuzzy matching + the domain lexicon (pure) +- ``corpus`` deterministic synthetic paraphrase corpus (pure) +- ``vectorize`` BM25+ index and PPMI/random-projection embeddings (seeded) +- ``router`` the universal intent router over every surface (pure) +- ``compound`` multi-intent clause splitting (pure) +- ``nlhistory`` natural-language undo/history queries (pure planning) +- ``session`` conversational state: anaphora, ellipsis, clarification +- ``memory`` episodic interaction memory with forgetting curve +- ``learn`` online learning loop (AdaGrad logistic, calibration, + bandit over routing strategies, drift monitor) +- ``pipeline`` the orchestrator wiring cortex into the settings spine + +Design spine (inherited from the rest of the assistant): every learned +component ranks and proposes; the settings planner/applier and the brain +ledger stay the only write paths; honest verdicts (AMBIGUOUS beats a +silent guess) everywhere; stdlib only. +""" diff --git a/plugins/caelestia-assistant/assistant/core/abers.py b/plugins/caelestia-assistant/assistant/core/abers.py new file mode 100644 index 0000000..f8eccfe --- /dev/null +++ b/plugins/caelestia-assistant/assistant/core/abers.py @@ -0,0 +1,217 @@ +"""cortex.abers — honest probability calibration (Group A3). + +The router's softmax p is a RANKING quantity, not a probability: the +arena's calibration suite has said so in cold-start ECE terms since it +existed. This module adds the two classical fixes, stdlib-only: + +- **Isotonic regression** (PAVA — pool-adjacent-violators, the standard + binomial-calibration staircase): a monotone step function fitted on + (score, outcome) pairs, optionally WEIGHTED. Deterministic; ties + break by insertion order. + +- **Venn-Abers predictive sets** (Vovk & Petej 2014; the IVAP form): + an exact distribution-free calibration INTERVAL. For a test score p, + run PAVA twice on the calibration pairs — once with (p, 1) appended, + once with (p, 0) appended — and read the two predictions at p: the + interval [p_lo, p_hi] is guaranteed to cover the true outcome + probability under exchangeability. The midpoint is the point + prediction; the WIDTH is honest abstention information (a wide + interval means the calibrator does not know). + +- **Weighted conformal**: the split-conformal quantile, re-derived with + importance WEIGHTS on the calibration scores — the honest tool when + the calibration stream (dev-shaped) may not match deployment + (real-shaped): weight the calibration rows by the dev-to-real + importance ratio and the quantile tracks the reweighted + distribution. Deterministic weighted quantile, bounded data. + +Reporting: ``eval calibration`` now reports ECE for the RAW softmax and +for isotonic / Venn-Abers after them, using deterministic every-4th-row +held-out folds (the corpus's own supervised-split convention) so the +numbers are honest out-of-sample, not in-sample self-grading. +""" + +from __future__ import annotations + +from typing import Any, Dict, List, Optional, Sequence, Tuple + +__all__ = ["isotonic_fit", "isotonic_predict", "venn_abers", + "weighted_conformal_quantile", "ece_report"] + +Infinity = float("inf") + + +# --------------------------------------------------------------------------- +# PAVA (weighted). +# --------------------------------------------------------------------------- + + +def isotonic_fit(pairs: Sequence[Tuple[float, float]], + weights: Optional[Sequence[float]] = None + ) -> List[Tuple[float, float]]: + """Weighted PAVA over (score, outcome) pairs sorted by score. + + Returns the fitted step function as [(x, y), ...] with x ascending + and y the pooled (isotonic) means — a monotone non-decreasing map. + Deterministic: stable sort by score then insertion order. + """ + if weights is not None and len(weights) != len(pairs): + raise ValueError("weights must match pairs") + data = sorted( + ((float(p), float(o), float(weights[i]) if weights is not None + else 1.0) for i, (p, o) in enumerate(pairs)), + key=lambda t: (t[0],)) + # blocks: (sum_w, sum_wy, mean, [xs...]) + blocks: List[List[Any]] = [] + for x, y, w in data: + if w <= 0: + continue + blocks.append([w, w * y, y / w, [x]]) + # pool while the previous mean exceeds the current (violation) + while len(blocks) >= 2 and blocks[-2][2] > blocks[-1][2] + 1e-15: + w2, wy2, _m2, xs2 = blocks.pop() + w1, wy1, _m1, xs1 = blocks.pop() + blocks.append([w1 + w2, wy1 + wy2, (wy1 + wy2) / (w1 + w2), + xs1 + xs2]) + steps: List[Tuple[float, float]] = [] + for _w, _wy, mean, xs in blocks: + for x in xs: # one (x, y) per calibration point: a step map + steps.append((x, mean)) + return steps + + +def isotonic_predict(fit_steps: Sequence[Tuple[float, float]], + x: float) -> float: + """Evaluate the PAVA step map at x (right-continuous; below the + first calibration point it returns the first pooled mean — the + honest flat extrapolation).""" + if not fit_steps: + return 0.5 + lo, hi = 0, len(fit_steps) - 1 + best = fit_steps[0][1] + while lo <= hi: + mid = (lo + hi) // 2 + if fit_steps[mid][0] <= x: + best = fit_steps[mid][1] + lo = mid + 1 + else: + hi = mid - 1 + return best + + +# --------------------------------------------------------------------------- +# Venn-Abers (IVAP form). +# --------------------------------------------------------------------------- + + +def venn_abers(calib: Sequence[Tuple[float, float]], + test_p: float) -> Tuple[float, float, float]: + """(p_lo, p_hi, midpoint) for one test score. + + p_hi: PAVA over calib + [(test_p, 1)], evaluated at test_p. + p_lo: PAVA over calib + [(test_p, 0)], evaluated at test_p. + The interval covers the true conditional probability under + exchangeability (Vovk & Petej 2014); the midpoint is the point + prediction used for scoring. + """ + hi = isotonic_predict(isotonic_fit(list(calib) + [(test_p, 1.0)]), + test_p) + lo = isotonic_predict(isotonic_fit(list(calib) + [(test_p, 0.0)]), + test_p) + lo = min(lo, hi) # numerical ordering guard + return lo, hi, (lo + hi) / 2.0 + + +# --------------------------------------------------------------------------- +# Weighted conformal quantile. +# --------------------------------------------------------------------------- + + +def weighted_conformal_quantile(scores: Sequence[float], + weights: Optional[Sequence[float]] = None, + alpha: float = 0.1) -> Optional[float]: + """The split-conformal quantile under importance WEIGHTS. + + Unweighted (weights=None) this is exactly the existing + ConformalCalibrator.threshold rule: ceil((n+1)(1-alpha))/n order + statistic. Weighted, the (n+1)(1-alpha) mass quantile of the + reweighted distribution — the honest shift tool: weight dev-shaped + calibration rows by their dev-to-real importance ratio and the + threshold tracks the real distribution, not the dev one. Returns + None when there is too little data (honesty: an empty calibration + set guarantees nothing). + """ + n = len(scores) + if n < 5: + return None + if not 0.0 < alpha < 1.0: + raise ValueError("alpha in (0, 1)") + if weights is None: + s = sorted(scores) + import math + rank = min(n, max(1, math.ceil((n + 1) * (1.0 - alpha)))) + return s[rank - 1] + if len(weights) != n: + raise ValueError("weights must match scores") + pairs = sorted(zip((float(s) for s in scores), + (float(w) for w in weights)), + key=lambda t: t[0]) + total = sum(w for _s, w in pairs) + if total <= 0: + return None + # (n+1)(1-alpha)/n of the TOTAL mass, matching the unweighted rule's + # finite-sample correction in the equal-weights limit + import math + # (n+1)/n finite-sample correction matches the unweighted rule in + # the equal-weights limit + target = min(1.0, ((n + 1) / n) * (1.0 - alpha)) + cum = 0.0 + for s, w in pairs: + cum += w / total + if cum >= target - 1e-12: + return s + return pairs[-1][0] + + +# --------------------------------------------------------------------------- +# ECE reporting (out-of-sample, deterministic folds). +# --------------------------------------------------------------------------- + + +def ece_report(rows: Sequence[Tuple[float, int]], + folds: int = 4, bins: int = 5) -> Dict[str, Any]: + """ECE before/after calibration over deterministic held-out folds. + + Fold i (every folds-th row, the corpus's own every-4th supervised + convention) is scored by calibrators fitted on the OTHER rows, so + the after numbers are out-of-sample. Raw ECE is fold-free (the + uncalibrated baseline has nothing to fit). + """ + from assistant.core.eval.stats import ece + + raw = ece([p for p, _o in rows], [o for _p, o in rows], bins=bins) + iso_vals: List[Tuple[float, int]] = [] + va_vals: List[Tuple[float, int]] = [] + wide = 0 + for i, (p, o) in enumerate(rows): + train = [r for j, r in enumerate(rows) if j % folds != i % folds] + if not train: + continue + steps = isotonic_fit(train) + iso_vals.append((isotonic_predict(steps, p), o)) + lo, hi, mid = venn_abers(train, p) + va_vals.append((mid, o)) + if hi - lo > 0.34: + wide += 1 + return { + "n": len(rows), + "ece_raw": round(raw, 4), + "ece_isotonic": round(ece([p for p, _ in iso_vals], + [o for _, o in iso_vals], bins=bins), 4), + "ece_venn_abers": round(ece([p for p, _ in va_vals], + [o for _, o in va_vals], bins=bins), 4), + "wide_va_intervals": wide, + "folds": folds, + "note": ("out-of-sample: fold i scored by calibrators fitted on " + "the other folds (deterministic, no RNG)"), + } diff --git a/plugins/caelestia-assistant/assistant/core/adwin.py b/plugins/caelestia-assistant/assistant/core/adwin.py new file mode 100644 index 0000000..6dee6c0 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/core/adwin.py @@ -0,0 +1,319 @@ +"""cortex.adwin — ADWIN, the SECOND drift detector beside Page-Hinkley +over the acceptance stream. + +Bifet & Gavaldà 2007, "Learning from Time-Changing Data with Adaptive +Windowing", SIAM Data Mining (SDM) 2007 — the compressed bucket-list +variant (the paper's Algorithm 1): an exponential histogram whose +buckets each summarize a run of 2^i consecutive elements as +(total, variance), at most ``max_buckets`` (M=5, the paper's value) +buckets per row. On every element the window is re-examined at every +bucket-boundary split: if the two subwindows' means differ by more +than the Hoeffding bound + + epsilon_cut = sqrt( ln(4/delta) / (2m) ), + m = 1 / (1/n0 + 1/n1) (the paper's effective sample size), + +the older subwindow is CUT — the window keeps only the recent, +apparently-homogeneous part. The 2009 Knowledge and Information Systems +journal version adds a variance-completion term to epsilon_cut; this +module implements the SDM 2007 variant (the plain Hoeffding bound) — +the buckets still carry (total, variance) per the paper's structure, +but the cut criterion uses only the means. Adapted, not invented: the +exponential-histogram compression is exactly the paper's. + +The API mirrors ``PageHinkleyDrift`` in cortex/conformal.py (same +update / to_dict / from_dict / reset shape) so a caller can hold one +of each; ``DriftConsensus`` below holds exactly that pair. + +THE CONSENSUS GATE (the integration requirement): drift is FLAGGED TO +THE USER only when BOTH detectors have alarmed — dual agreement is the +point, suppressing single-detector false alarms — while each +detector's own state is always reported individually. + +Honesty rules: warmup (width < 32: no alarm — the Hoeffding bound is +vacuous on tiny subwindows, so the check is simply not made and the +report says so); the estimate and width are always reported; alarms +LATCH (like Page-HinkleyDrift) until reset() — the alarm_at index is +the element count at which the first cut happened. Determinism: pure +arithmetic, no RNG anywhere. This module writes NOTHING: state moves +only through plain dicts (the caller's learned-state JSON path +persists them). A brute-force sliding-window cross-check of the cut +behaviour is pinned in tests/test_adwin.py. +""" +from __future__ import annotations + +import math +from typing import Any, Dict, List, Optional, Sequence, Tuple + +from .conformal import PageHinkleyDrift + +__all__ = ["ADWIN", "DriftConsensus", "consensus"] + + +# --------------------------------------------------------------------------- +# The detector +# --------------------------------------------------------------------------- + +class ADWIN: + """Adaptive Windowing over the accept/reject stream. + + ``update(accepted)`` returns ``{"drift": bool, "width": n, + "estimate": mean, "alarm_at": Optional[int]}`` — ``drift`` is the + EVENT (a cut happened during this update); ``alarm_at`` is the + latched index of the FIRST alarm (reset() clears it). ``width`` is + the current window size; ``estimate`` its mean. + """ + + def __init__(self, delta: float = 0.002, max_buckets: int = 5, + min_width: int = 32) -> None: + """``delta``: the paper's confidence parameter (default 0.002, + within the SDM paper's suggested range); ``max_buckets``: M=5 + rows of compression per level; ``min_width``: warmup — no cut + is even checked below this width (the Hoeffding bound is + vacuous on tiny subwindows).""" + if not (0.0 < delta < 1.0): + raise ValueError("delta in (0, 1)") + if max_buckets < 2: + raise ValueError("max_buckets >= 2") + if min_width < 2: + raise ValueError("min_width >= 2") + self.delta = float(delta) + self.max_buckets = int(max_buckets) + self.min_width = int(min_width) + # rows[i] holds buckets of size 2^i, oldest -> newest; each + # bucket is [total, variance]. width/mean are derived from the + # buckets (single source of truth, no bookkeeping to drift). + self.rows: List[List[List[float]]] = [[]] + self.n = 0 # elements added since reset + self.alarm_at: Optional[int] = None + + # -- bucket mechanics ------------------------------------------------ + + def _flat(self) -> List[Tuple[int, float, float]]: + """The bucket list as ONE chronological sequence oldest->newest: + [(size, total, variance), ...]. Invariant (kept by the + merge-oldest-first discipline, verified by tests): sizes are + non-increasing powers of two, so higher rows are always older.""" + out: List[Tuple[int, float, float]] = [] + for i in range(len(self.rows) - 1, -1, -1): + size = 1 << i + for total, variance in self.rows[i]: + out.append((size, total, variance)) + return out + + def _compress(self) -> None: + """Merge the two OLDEST buckets of any overflowing row into the + next row (the paper's compress step, cascading outward).""" + i = 0 + while i < len(self.rows): + while len(self.rows[i]) > self.max_buckets: + b1 = self.rows[i].pop(0) + b2 = self.rows[i].pop(0) + if i + 1 >= len(self.rows): + self.rows.append([]) + # pooled variance of the merged run (exact identity) + n1 = n2 = float(1 << i) + total = b1[0] + b2[0] + m1 = b1[0] / n1 + m2 = b2[0] / n2 + mean = total / (n1 + n2) + variance = ((n1 * (b1[1] + m1 * m1) + + n2 * (b2[1] + m2 * m2)) / (n1 + n2) + - mean * mean) + self.rows[i + 1].append([total, max(variance, 0.0)]) + i += 1 + + def _rebuild(self, flat: Sequence[Tuple[int, float, float]]) -> None: + """Reinstall the window from a flat bucket list (after a cut — + only bucket removal ever happens there, so every row stays + within the per-row cap).""" + self.rows = [[]] + for size, total, variance in flat: + row = size.bit_length() - 1 + while row + 1 > len(self.rows): + self.rows.append([]) + self.rows[row].append([total, variance]) + + def _cut_once(self) -> bool: + """The paper's cut check over every bucket-boundary split point: + W0 = the oldest prefix, W1 = the rest. Cut (drop W0) at the + first split where |mu0 - mu1| >= epsilon_cut. Returns whether a + cut happened. Below min_width nothing is checked (warmup).""" + flat = self._flat() + width = sum(size for size, _t, _v in flat) + if width < self.min_width: + return False + total = sum(t for _s, t, _v in flat) + n0 = 0 + t0 = 0.0 + for k in range(len(flat) - 1): # W0 = flat[:k+1] + size, bucket_total, _v = flat[k] + n0 += size + t0 += bucket_total + n1 = width - n0 + if n1 <= 0: + break + mu0 = t0 / n0 + mu1 = (total - t0) / n1 + m = 1.0 / (1.0 / n0 + 1.0 / n1) + epsilon = math.sqrt(math.log(4.0 / self.delta) / (2.0 * m)) + if abs(mu0 - mu1) >= epsilon: + self._rebuild(flat[k + 1:]) + return True + return False + + # -- the PH-shaped API ------------------------------------------------ + + def update(self, accepted: bool) -> Dict[str, Any]: + """Feed one accept (True) / reject (False); returns the report.""" + self.rows[0].append([1.0 if accepted else 0.0, 0.0]) + self.n += 1 + self._compress() + drift = False + while self._cut_once(): + drift = True + if self.alarm_at is None: + self.alarm_at = self.n + flat = self._flat() + width = sum(size for size, _t, _v in flat) + total = sum(t for _s, t, _v in flat) + return {"drift": drift, + "width": width, + "estimate": round(total / width, 6) if width else 0.0, + "alarm_at": self.alarm_at} + + def status(self) -> Dict[str, Any]: + flat = self._flat() + width = sum(size for size, _t, _v in flat) + total = sum(t for _s, t, _v in flat) + return { + "n": self.n, + "width": width, + "estimate": round(total / width, 6) if width else None, + "alarmed": self.alarm_at is not None, + "alarm_at": self.alarm_at, + "delta": self.delta, + "max_buckets": self.max_buckets, + "min_width": self.min_width, + "buckets": len(flat), + "warmup": width < self.min_width, + "message": (f"acceptance-rate mean shift detected — the window " + f"was cut at element {self.alarm_at}") + if self.alarm_at is not None else + ("no drift detected" if width >= self.min_width + else f"warmup: width {width} < {self.min_width}, " + f"no cut is checked yet"), + } + + def reset(self) -> None: + """Clear the window and the latch after acting.""" + self.rows = [[]] + self.n = 0 + self.alarm_at = None + + def to_dict(self) -> Dict[str, Any]: + flat = self._flat() + width = sum(size for size, _t, _v in flat) + total = sum(t for _s, t, _v in flat) + return {"delta": self.delta, "max_buckets": self.max_buckets, + "min_width": self.min_width, "n": self.n, + "alarm_at": self.alarm_at, "width": width, + "estimate": round(total / width, 6) if width else None, + "buckets": [[size, total, variance] + for size, total, variance in flat]} + + def from_dict(self, d: Dict[str, Any]) -> "ADWIN": + d = d if isinstance(d, dict) else {} + self.delta = float(d.get("delta", self.delta)) + self.max_buckets = int(d.get("max_buckets", self.max_buckets)) + self.min_width = int(d.get("min_width", self.min_width)) + self.n = int(d.get("n", 0)) + alarm = d.get("alarm_at") + self.alarm_at = int(alarm) if alarm is not None else None + self.rows = [[]] + for bucket in d.get("buckets", []) or []: + size, total, variance = bucket + row = int(size).bit_length() - 1 + while row + 1 > len(self.rows): + self.rows.append([]) + self.rows[row].append([float(total), float(variance)]) + return self + + +# --------------------------------------------------------------------------- +# The consensus gate +# --------------------------------------------------------------------------- + +def consensus(ph_state: Dict[str, Any], + adwin_state: Dict[str, Any]) -> Dict[str, Any]: + """Pure consensus over the two PERSISTED state dicts (for callers + that hold one detector of each without a DriftConsensus). The rule: + drift is FLAGGED TO THE USER only when BOTH detectors have alarmed + (dual agreement suppresses single-detector false alarms); each + detector's own state is always reported individually.""" + ph_alarm = ph_state.get("alarm_at") is not None + ad_alarm = adwin_state.get("alarm_at") is not None + flagged = ph_alarm and ad_alarm + return { + "page_hinkley": { + "alarmed": ph_alarm, + "alarm_at": ph_state.get("alarm_at"), + "n": ph_state.get("n"), + "rejection_ema": ph_state.get("mean"), + }, + "adwin": { + "alarmed": ad_alarm, + "alarm_at": adwin_state.get("alarm_at"), + "width": adwin_state.get("width"), + "estimate": adwin_state.get("estimate"), + }, + "flag_drift": flagged, + "rule": ("drift is flagged to the user only when BOTH detectors " + "have alarmed (dual agreement suppresses single-detector " + "false alarms); each detector's own state is always " + "reported individually"), + "summary": ("FLAGGED — both detectors alarmed" if flagged else + "not flagged (page-hinkley " + f"{'alarmed' if ph_alarm else 'quiet'}, adwin " + f"{'alarmed' if ad_alarm else 'quiet'})"), + } + + +class DriftConsensus: + """One PageHinkleyDrift + one ADWIN over the SAME acceptance + stream, with the consensus report on top. ``update(accepted)`` + feeds both and returns the combined report; ``status()`` is the + read-only view (both individual states + the joint flag).""" + + def __init__(self, ph: Optional[PageHinkleyDrift] = None, + adwin: Optional[ADWIN] = None) -> None: + self.ph = ph if ph is not None else PageHinkleyDrift() + self.adwin = adwin if adwin is not None else ADWIN() + + def update(self, accepted: bool) -> Dict[str, Any]: + ph_row = self.ph.update(accepted) + ad_row = self.adwin.update(accepted) + out = consensus(self.ph.to_dict(), self.adwin.to_dict()) + out["last_update"] = {"page_hinkley": ph_row, "adwin": ad_row} + return out + + def status(self) -> Dict[str, Any]: + return consensus(self.ph.to_dict(), self.adwin.to_dict()) + + def reset(self) -> None: + self.ph.reset() + self.adwin.reset() + + def to_dict(self) -> Dict[str, Any]: + return {"page_hinkley": self.ph.to_dict(), + "adwin": self.adwin.to_dict()} + + def from_dict(self, d: Dict[str, Any]) -> "DriftConsensus": + d = d if isinstance(d, dict) else {} + ph_data = d.get("page_hinkley") or {} + ad_data = d.get("adwin") or {} + self.ph = PageHinkleyDrift().from_dict( + ph_data if isinstance(ph_data, dict) else {}) + self.adwin = ADWIN().from_dict( + ad_data if isinstance(ad_data, dict) else {}) + return self diff --git a/plugins/caelestia-assistant/assistant/core/concepts.py b/plugins/caelestia-assistant/assistant/core/concepts.py new file mode 100644 index 0000000..70e02d3 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/core/concepts.py @@ -0,0 +1,287 @@ +"""Taught concepts (exp-build-5 F15): user-named bundles of validated +tool calls — "make it glassy" becomes a reusable, learnable command. + +Contract: +- A concept is created ONLY from calls the user explicitly named and + consented to (CLI teach, or a plan the user approved and then named). + Nothing is ever auto-created from utterances. +- Every call is registry-checked at teach time and re-validated by the + standard planner at apply time. Teaching validates, it never applies. +- Recall is char-n-gram Dice + lexicon overlap over the concept's name + and taught example utterances. Below threshold: ABSTAIN (honest miss). + Two concepts within the ambiguity gap: AMBIGUOUS. A strong built-in + preset match alongside: CONFLICT_ASK — both options are shown, the + user picks. Recall proposes; only the consent gate applies. +- Outcomes learn: per-(tool, value) Beta posteriors update on + accept/reject, surfaced in `list` (never silent replacement of the + built-in presets). +- Sharing: export/import is a reviewable, capped JSON diff (recipes + only — posteriors are personal and never exported). + +Bounded: MAX_CONCEPTS concepts, MAX_EXAMPLES examples, MAX_CALLS calls +per concept; import refuses overflow. Stdlib only. +""" + +from __future__ import annotations + +import re +from typing import Any, Dict, List, Optional, Tuple + +from assistant.adapters.caelestia.registry import tool_by_name + +__all__ = ["ConceptError", "teach", "forget", "recall", "record_outcome", + "list_concepts", "export_diff", "import_diff", + "MAX_CONCEPTS", "MAX_CALLS", "MAX_EXAMPLES"] + +MAX_CONCEPTS = 64 +MAX_CALLS = 12 +MAX_EXAMPLES = 4 +RECALL_THRESHOLD = 0.62 # Dice similarity to answer at all +AMBIGUOUS_GAP = 0.08 # two concepts closer than this ask instead +PRESET_MATCH = 0.55 # preset similarity that triggers CONFLICT_ASK +_STATE_KEY = "taught_concepts" + + +class ConceptError(RuntimeError): + pass + + +# --------------------------------------------------------------------------- +# storage shape: state[_STATE_KEY] = {name: {calls, examples, alpha, beta}} +# calls: [[tool, value]], alpha/beta: {"tool=": [a, b]} +# --------------------------------------------------------------------------- + + +def _table(state: Dict[str, Any]) -> Dict[str, Any]: + return state.setdefault(_STATE_KEY, {}) + + +def _call_key(tool: str, value: Any) -> str: + return f"{tool}={value!r}" + + +def _parse_call(call: Any) -> Tuple[str, Any]: + if isinstance(call, str): + name, sep, value_text = call.partition("=") + if not sep: + raise ConceptError(f"--call expects TOOL=VALUE (got {call!r})") + import json + try: + value = json.loads(value_text) + except ValueError: + value = value_text + return name.strip(), value + if isinstance(call, (list, tuple)) and len(call) == 2: + return str(call[0]), call[1] + raise ConceptError(f"bad call {call!r}") + + +def _ngrams(text: str, ns: Tuple[int, ...] = (2, 3, 4)) -> set: + t = re.sub(r"\s+", " ", text.lower()).strip() + grams: set = set() + for n in ns: + if len(t) < n: + grams.add(t) + continue + for i in range(len(t) - n + 1): + grams.add(t[i:i + n]) + return grams + + +def _dice(a: str, b: str) -> float: + ga, gb = _ngrams(a), _ngrams(b) + if not ga or not gb: + return 0.0 + return 2.0 * len(ga & gb) / (len(ga) + len(gb)) + + +def _content_words(text: str) -> List[str]: + return [w for w in re.findall(r"[a-z0-9]+", text.lower()) if len(w) >= 3] + + +# --------------------------------------------------------------------------- +# teach / forget / list +# --------------------------------------------------------------------------- + + +def teach(state: Dict[str, Any], name: str, calls: List[Any], + examples: Optional[List[str]] = None, + source: str = "explicit") -> Dict[str, Any]: + name = (name or "").strip().lower() + if not re.fullmatch(r"[a-z0-9][a-z0-9 _-]{1,39}", name): + raise ConceptError( + f"concept name must be 2-40 chars of letters/digits/space/-_: {name!r}") + if not calls: + raise ConceptError("a concept needs at least one call") + if len(calls) > MAX_CALLS: + raise ConceptError(f"a concept takes at most {MAX_CALLS} calls") + parsed: List[Tuple[str, Any]] = [_parse_call(c) for c in calls] + for tool, _value in parsed: + if tool_by_name(tool) is None: + raise ConceptError(f"{tool} is not a registry tool") + table = _table(state) + if name not in table and len(table) >= MAX_CONCEPTS: + raise ConceptError(f"concept store full ({MAX_CONCEPTS}); forget one first") + exs = [e.strip() for e in (examples or []) if e and e.strip()] + if len(exs) > MAX_EXAMPLES: + raise ConceptError(f"at most {MAX_EXAMPLES} example phrases") + old = table.get(name) or {} + table[name] = { + "calls": [[t, v] for t, v in parsed], + "examples": exs, + "alpha": old.get("alpha", {}), + "beta": old.get("beta", {}), + "source": source, + } + return {"name": name, "calls": table[name]["calls"], + "examples": exs, "n_concepts": len(table)} + + +def forget(state: Dict[str, Any], name: str) -> bool: + name = (name or "").strip().lower() + return bool(_table(state).pop(name, None)) + + +def list_concepts(state: Dict[str, Any]) -> List[Dict[str, Any]]: + out = [] + for name in sorted(_table(state)): + c = _table(state)[name] + posterior = [] + for tool, value in c["calls"]: + key = _call_key(tool, value) + a = c["alpha"].get(key, 0.0) + b = c["beta"].get(key, 0.0) + posterior.append({"tool": tool, "value": value, + "p": (round(a / (a + b), 3) if a + b else None), + "n": int(a + b)}) + out.append({"name": name, "calls": c["calls"], + "examples": c["examples"], "posterior": posterior, + "source": c.get("source", "explicit")}) + return out + + +# --------------------------------------------------------------------------- +# recall +# --------------------------------------------------------------------------- + + +def _concept_score(state: Dict[str, Any], text: str, + name: str) -> float: + c = _table(state)[name] + scores = [_dice(text, name.replace("_", " "))] + scores.extend(_dice(text, ex) for ex in c["examples"]) + best = max(scores) + words = _content_words(text) + named = _content_words(name) + if named and all(w in words for w in named): + best = min(1.0, best + 0.15) # all name words literally present + return best + + +def recall(state: Dict[str, Any], text: str, + presets: Optional[List[Dict[str, Any]]] = None) -> Dict[str, Any]: + """The recall verdict for one utterance: + ABSTAIN (no concept close), AMBIGUOUS (two concepts too close), + CONFLICT_ASK (a built-in preset matches too), or RECALL (propose the + concept's calls — the caller still gates the apply).""" + text = (text or "").strip() + table = _table(state) + if not table or not text: + return {"verdict": "ABSTAIN", "reason": "no concepts taught" + if not table else "empty utterance"} + ranked = sorted(((_concept_score(state, text, n), n) for n in table), + key=lambda kv: (-kv[0], kv[1])) + top, second = ranked[0], (ranked[1] if len(ranked) > 1 else (0.0, None)) + if top[0] < RECALL_THRESHOLD: + return {"verdict": "ABSTAIN", "reason": "no concept close enough", + "best": {"name": top[1], "score": round(top[0], 3)}} + if second[1] is not None and top[0] - second[0] < AMBIGUOUS_GAP \ + and second[0] >= RECALL_THRESHOLD: + return {"verdict": "AMBIGUOUS", + "candidates": [{"name": top[1], "score": round(top[0], 3)}, + {"name": second[1], "score": round(second[0], 3)}]} + preset_hit = None + text_words = set(_content_words(text)) + for p in (presets or []): + s = max(_dice(text, str(p.get("name", ""))), + _dice(text, str(p.get("label", ""))), + _dice(text, str(p.get("description", "")))) + # short preset names lose at raw Dice against a long utterance; + # if every distinctive name/label word appears literally, that is + # a real conflict signal, not a similarity artifact + name_words = [w for w in _content_words( + f"{p.get('name', '')} {p.get('label', '')}") if len(w) >= 4] + if name_words and all(w in text_words for w in name_words): + s = max(s, 0.85) + if s >= PRESET_MATCH: + preset_hit = {"name": str(p.get("name")), "score": round(s, 3)} + break + if preset_hit: + return {"verdict": "CONFLICT_ASK", "concept": {"name": top[1], + "score": round(top[0], 3)}, "preset": preset_hit, + "question": (f"use your taught concept {top[1]!r} or the " + f"built-in preset {preset_hit['name']!r}?")} + c = table[top[1]] + posterior = [] + for tool, value in c["calls"]: + k = _call_key(tool, value) + a, b = c["alpha"].get(k, 0.0), c["beta"].get(k, 0.0) + posterior.append({"tool": tool, "value": value, + "p": (round(a / (a + b), 3) if a + b else None), + "n": int(a + b)}) + return {"verdict": "RECALL", "name": top[1], "score": round(top[0], 3), + "calls": [{"name": t, "value": v} for t, v in c["calls"]], + "posterior": posterior} + + +def record_outcome(state: Dict[str, Any], name: str, + accepted: bool) -> Dict[str, Any]: + """Beta update per (tool, value) after a consented apply/reject.""" + name = (name or "").strip().lower() + c = _table(state).get(name) + if c is None: + raise ConceptError(f"unknown concept {name!r}") + for tool, value in c["calls"]: + key = _call_key(tool, value) + a, b = c["alpha"].get(key, 0.0), c["beta"].get(key, 0.0) + c["alpha"][key], c["beta"][key] = ( + (a + 1.0, b) if accepted else (a, b + 1.0)) + return {"name": name, "accepted": accepted} + + +# --------------------------------------------------------------------------- +# sharing: reviewable recipe diffs (no posteriors) +# --------------------------------------------------------------------------- + + +def export_diff(state: Dict[str, Any], + names: Optional[List[str]] = None) -> List[Dict[str, Any]]: + table = _table(state) + want = [n.lower() for n in (names or table)] if names else sorted(table) + out = [] + for n in want: + c = table.get(n) + if c is None: + raise ConceptError(f"unknown concept {n!r}") + out.append({"name": n, "calls": c["calls"], "examples": c["examples"]}) + return out + + +def import_diff(state: Dict[str, Any], entries: List[Dict[str, Any]], + force: bool = False) -> Dict[str, int]: + if not isinstance(entries, list) or len(entries) > MAX_CONCEPTS: + raise ConceptError(f"import expects a list of at most {MAX_CONCEPTS} entries") + added = updated = skipped = 0 + for e in entries: + name = str(e.get("name", "")).strip().lower() + exists = name in _table(state) + if exists and not force: + skipped += 1 + continue + teach(state, name, e.get("calls") or [], + examples=e.get("examples"), source="imported") + if exists: + updated += 1 + else: + added += 1 + return {"added": added, "updated": updated, "skipped": skipped} diff --git a/plugins/caelestia-assistant/assistant/core/conformal.py b/plugins/caelestia-assistant/assistant/core/conformal.py new file mode 100644 index 0000000..3b42ad3 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/core/conformal.py @@ -0,0 +1,238 @@ +"""cortex.conformal — distribution-free honesty for the router's verdicts. + +The router already reports a calibrated softmax confidence (Beta-Binomial +buckets). This module adds the statistical guarantee on top: + +- `ConformalCalibrator` — split-conformal prediction: from a calibration set + of (score, outcome) pairs it derives the smallest score level s such that + at least (1-alpha) of past accepted routes scored >= s. A NEW route whose + score clears that level carries a VALID coverage guarantee: "routes this + confident were right at least 90% of the time before" — a distribution-free + statement that needs no model assumptions, only exchangeability. + +- `query_by_committee` — active learning: when the router's weight profiles + (lexical-heavy / semantic-heavy / balanced) DISAGREE about the top surface, + the honest move is to ask the user, and the disagreement (vote entropy) is + exactly the information-gain measure. Returns the ranked "teach me" list. + +- `PageHinkleyDrift` — incremental drift detector over the acceptance stream: + the same statistic the scan layer uses on error rates, reused on YOUR + behaviour ("you started rejecting settings plans this week"). + +All state is JSON round-trippable through the cortex learner's state dict. +Nothing here writes files; nothing here is a chatbot. +""" +from __future__ import annotations + +import math +from typing import Any, Dict, List, Optional, Sequence, Tuple + +__all__ = ["ConformalCalibrator", "query_by_committee", "PageHinkleyDrift"] + + +# --------------------------------------------------------------------------- +class ConformalCalibrator: + """Split-conformal calibration over router scores. + + Feed (score, outcome) pairs as they are observed — `learn_feedback` + already produces them. `verdict(score, alpha)` then returns a + distribution-free statement about a new route. + """ + + def __init__(self, alpha: float = 0.1, max_history: int = 400) -> None: + if not (0.0 < alpha < 1.0): + raise ValueError("alpha in (0, 1)") + self.alpha = alpha + self.max_history = max_history + self.scores: List[float] = [] # scores of ACCEPTED routes only + self.all_scores: List[float] = [] + self.all_outcomes: List[int] = [] + + # ------------------------------------------------------------------ + def observe(self, score: float, outcome: str) -> None: + """outcome: 'applied' | 'approved' | 'rejected' | 'abstained'.""" + score = float(score) + self.all_scores.append(score) + self.all_outcomes.append(1 if outcome in ("applied", "approved") else 0) + if outcome in ("applied", "approved"): + self.scores.append(score) + if len(self.all_scores) > self.max_history: + overflow = len(self.all_scores) - self.max_history + del self.all_scores[:overflow] + del self.all_outcomes[:overflow] + if len(self.scores) > self.max_history: + del self.scores[:len(self.scores) - self.max_history] + + # ------------------------------------------------------------------ + def threshold(self, alpha: Optional[float] = None) -> Optional[float]: + """Conformal quantile: ceil((n+1)(1-alpha))/n empirical quantile of + accepted-route scores. None when there is not enough calibration + data (honesty: an empty calibration set guarantees nothing).""" + a = alpha if alpha is not None else self.alpha + n = len(self.scores) + if n < 5: + return None + scores = sorted(self.scores) + rank = min(n, max(1, math.ceil((n + 1) * (1.0 - a)))) + return scores[rank - 1] + + def verdict(self, score: float, alpha: Optional[float] = None) -> Dict[str, Any]: + t = self.threshold(alpha) + a = alpha if alpha is not None else self.alpha + n = len(self.scores) + if t is None: + return { + "covered": None, + "guarantee": None, + "reason": (f"insufficient calibration data ({n} accepted routes; " + f"need >= 5) — no distribution-free claim available"), + "score": round(score, 4), + "alpha": a, + } + covered = score >= t + return { + "covered": covered, + "guarantee": (f"routes at or above {round(t, 3)} were accepted " + f">= {round(1 - a, 2)} of the time historically " + f"(distribution-free, n={n})"), + "reason": "score clears the conformal threshold" if covered + else "score below the conformal threshold", + "score": round(score, 4), + "threshold": round(t, 4), + "alpha": a, + } + + # ------------------------------------------------------------------ + def empirical_accuracy(self, min_score: float = 0.0) -> Optional[float]: + pairs = [(s, o) for s, o in zip(self.all_scores, self.all_outcomes) + if s >= min_score] + if not pairs: + return None + return sum(o for _s, o in pairs) / len(pairs) + + def to_dict(self) -> Dict[str, Any]: + return {"alpha": self.alpha, "scores": self.scores, + "all_scores": self.all_scores, "all_outcomes": self.all_outcomes} + + def from_dict(self, d: Dict[str, Any]) -> "ConformalCalibrator": + self.alpha = d.get("alpha", self.alpha) + self.scores = list(d.get("scores", [])) + self.all_scores = list(d.get("all_scores", [])) + self.all_outcomes = list(d.get("all_outcomes", [])) + return self + + +# --------------------------------------------------------------------------- +def query_by_committee(candidates: Sequence[Dict[str, Any]], + committee_votes: Sequence[Dict[str, Dict[str, float]]], + top_k: int = 3) -> List[Dict[str, Any]]: + """Rank the requests worth TEACHING on (active learning). + + candidates: the request texts (dicts with at least {"text": ...}) + committee_votes: one dict per strategy; maps candidate index -> score + Returns the top_k candidates by COMMITTEE DISAGREEMENT — the standard + deviation of the members' raw scores. Spread, not normalized vote + entropy, is the right measure here: entropy cannot tell "both members + high" from "both members low", but those are the opposite teaching + cases, while a wide spread means the strategies genuinely chose + different surfaces and one label settles the fight. + """ + if len(candidates) != len(committee_votes[0] if committee_votes else {}): + raise ValueError("votes must score every candidate") + ranked: List[Tuple[float, Dict[str, Any]]] = [] + for i, cand in enumerate(candidates): + scores = [votes.get(i, 0.0) for votes in committee_votes] + n = len(scores) + mean = sum(scores) / n + var = sum((s - mean) ** 2 for s in scores) / n + disagreement = math.sqrt(var) + row = dict(cand) + row["disagreement"] = round(disagreement, 4) + row["mean_score"] = round(mean, 4) + ranked.append((disagreement, row)) + ranked.sort(key=lambda t: -t[0]) + out = [row for _e, row in ranked[:top_k]] + for row in out: + row["why"] = ("strategies disagree — labelling this buys the most " + "information for the router") + return out + + +# --------------------------------------------------------------------------- +class PageHinkleyDrift: + """Incremental Page-Hinkley over the accept/reject stream, oriented to + detect a DROP in acceptance (a preference shift), not a rise. + + Internally it runs the standard upward PH on the negated stream + (x' = 1 - x): "fewer accepts" == "more rejects" == an upward change in + x'. Hysteresis: one alarm latches the state so a single bad day is not + reported as a trend forever — `reset()` clears it after you have acted. + """ + + def __init__(self, threshold: float = 8.0, alpha: float = 0.98, + delta: float = 0.01, warmup: int = 25) -> None: + self.threshold = threshold + self.alpha = alpha + self.delta = delta + self.warmup = warmup + self.n = 0 + self.mean = 0.0 # EMA of the rejection stream + self.sum_xt = 0.0 + self.min_ht = math.inf + self.alarm_at: Optional[int] = None + + def update(self, accepted: bool) -> Dict[str, Any]: + x = 0.0 if accepted else 1.0 # negated stream: reject == 1 + if self.n == 0: + self.mean = x + self.n += 1 + self.mean = self.alpha * self.mean + (1.0 - self.alpha) * x + self.sum_xt += x - self.mean - self.delta + self.min_ht = min(self.min_ht, self.sum_xt) + stat = self.sum_xt - self.min_ht + alarmed = (self.n >= self.warmup and stat > self.threshold + and self.alarm_at is None) + if alarmed: + self.alarm_at = self.n + return {"n": self.n, "stat": round(stat, 4), "alarmed": alarmed} + + def reset(self) -> None: + """Clear the latch after acting (weights adapted, or user informed).""" + self.alarm_at = None + self.n = 0 + self.sum_xt = 0.0 + self.min_ht = math.inf + self.mean = 0.0 + + def status(self) -> Dict[str, Any]: + stat = self.sum_xt - self.min_ht + return { + "n": self.n, + "statistic": round(stat, 4), + "threshold": self.threshold, + "alarmed": self.alarm_at is not None, + "alarm_at": self.alarm_at, + "message": ("acceptance rate has DROPPED — your preferences " + "seem to have shifted; weights will adapt, but a " + "cortex reset-learning is available" ) + if self.alarm_at is not None else "no drift detected", + } + + def to_dict(self) -> Dict[str, Any]: + return {"threshold": self.threshold, "alpha": self.alpha, + "delta": self.delta, "warmup": self.warmup, "n": self.n, + "mean": self.mean, "sum_xt": self.sum_xt, + "min_ht": self.min_ht if self.min_ht != math.inf else None, + "alarm_at": self.alarm_at} + + def from_dict(self, d: Dict[str, Any]) -> "PageHinkleyDrift": + self.threshold = d.get("threshold", self.threshold) + self.alpha = d.get("alpha", self.alpha) + self.delta = d.get("delta", self.delta) + self.warmup = d.get("warmup", self.warmup) + self.n = d.get("n", 0) + self.mean = d.get("mean", 1.0) + self.sum_xt = d.get("sum_xt", 0.0) + self.min_ht = d.get("min_ht") if d.get("min_ht") is not None else math.inf + self.alarm_at = d.get("alarm_at") + return self diff --git a/plugins/caelestia-assistant/assistant/core/confusable_pairs.json b/plugins/caelestia-assistant/assistant/core/confusable_pairs.json new file mode 100644 index 0000000..20be0e4 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/core/confusable_pairs.json @@ -0,0 +1,442 @@ +{ + "generator": "assistant.core.confusables.mine_pairs", + "doc_sim_floor": 0.55, + "n_pairs": 29, + "pairs": [ + { + "a": "setAmbientOpacity", + "b": "setTransparencyBase", + "group": "effects", + "kind": "float", + "doc_similarity": 0.6837, + "question": "the AMBIENT background layer's opacity, or the GLOBAL transparency of the whole shell?", + "answers": { + "ambient": "setAmbientOpacity", + "global": "setTransparencyBase" + }, + "gain": 1.0, + "evidence": "dev m05: 'make the ambient background more opaque' takes the global transparency slider", + "source": "hand-pinned (arena failure class)" + }, + { + "a": "setAudioIncrement", + "b": "setBrightnessIncrement", + "group": "services", + "kind": "float", + "doc_similarity": 0.7508, + "question": "the step size for VOLUME, or for SCREEN BRIGHTNESS?", + "answers": { + "volume": "setAudioIncrement", + "brightness": "setBrightnessIncrement" + }, + "gain": 1.0, + "evidence": "dev m25/m26: identical sentence one noun apart; the brightness sibling wins both at cold start", + "source": "hand-pinned (arena failure class)" + }, + { + "a": "setDesktopLyricsPosition", + "b": "setDesktopLyricsAlignment", + "group": "wallpaper-scheme", + "kind": "enum", + "doc_similarity": 0.7143, + "question": "where the lyrics SIT on screen, or how the text ALIGNS inside its box?", + "answers": { + "where": "setDesktopLyricsPosition", + "align": "setDesktopLyricsAlignment" + }, + "gain": 1.0, + "evidence": "dev m15/m16: 'move the lyrics to the centre' and 'centre the lyrics text' rank each other's sibling first (sealed sr93 same class)", + "source": "hand-pinned (arena failure class)" + }, + { + "a": "setEnableOverviewBlur", + "b": "setDisableWallpaperBlur", + "group": "overview", + "kind": "bool", + "doc_similarity": 0.9326, + "question": "the blur of the OVERVIEW ITSELF (windows floating in it), or the WALLPAPER's blur while the overview is open?", + "answers": { + "overview itself": "setEnableOverviewBlur", + "wallpaper": "setDisableWallpaperBlur" + }, + "gain": 1.0, + "evidence": "dev m11/m12 (sealed sr67/sr68 same class): the two overview blur toggles swap under on/off phrasing", + "source": "hand-pinned (arena failure class)" + }, + { + "a": "setMaxFprintTries", + "b": "setPreviewScalesWirelessPassword", + "group": "lockscreen", + "kind": "int", + "doc_similarity": 0.0, + "question": "how many FINGERPRINT attempts before the password fallback — or how the password PREVIEW is scaled?", + "answers": { + "fingerprint attempts": "setMaxFprintTries", + "preview": "setPreviewScalesWirelessPassword" + }, + "gain": 1.0, + "evidence": "dev m14: 'fingerprint attempts before the password' lands on a preview-scale tool via the 'password' noun", + "source": "hand-pinned (arena failure class)" + }, + { + "a": "setPosition", + "b": "setHoverBottomRight", + "group": "notifications", + "kind": "enum", + "doc_similarity": 0.0, + "question": "where NOTIFICATION toasts appear on screen, or the overview corner that shows windows on HOVER?", + "answers": { + "toast": "setPosition", + "hover": "setHoverBottomRight" + }, + "gain": 1.0, + "evidence": "dev m08: 'show toasts in the bottom-right corner' confidently takes the overview hover-corner toggle", + "source": "hand-pinned (arena failure class)" + }, + { + "a": "setTrayRecolour", + "b": "setDockRecolourIcons", + "group": "bar", + "kind": "bool", + "doc_similarity": 0.6803, + "question": "which icons — the system TRAY icons, or the DOCK app icons?", + "answers": { + "tray": "setTrayRecolour", + "dock": "setDockRecolourIcons" + }, + "gain": 1.0, + "evidence": "dev m02: 'recolour the tray icons to match my theme' ranks the dock sibling first (sealed sr13 same class)", + "source": "hand-pinned (arena failure class)" + }, + { + "a": "setBarScale", + "b": "setPreviewScale", + "group": "bar", + "kind": "float", + "doc_similarity": 0.9132, + "question": "an ABSOLUTE value in that unit, or a SCALE multiplier on the current value?", + "answers": { + "scale multiplier": "setBarScale", + "absolute value": "setPreviewScale" + }, + "gain": 1.0, + "evidence": "mined: same-group 'bar' documents similarity 0.9132", + "source": "mined (document twins)" + }, + { + "a": "setBarShowOnHover", + "b": "setGreeterShowOnHover", + "group": "bar", + "kind": "bool", + "doc_similarity": 0.9529, + "question": "the bar setting, or the greeter setting?", + "answers": { + "bar": "setBarShowOnHover", + "greeter": "setGreeterShowOnHover" + }, + "gain": 1.0, + "evidence": "mined: same-group 'bar' documents similarity 0.9529", + "source": "mined (document twins)" + }, + { + "a": "setDesktopClockInvertColors", + "b": "setDesktopLyricsInvertColors", + "group": "wallpaper-scheme", + "kind": "bool", + "doc_similarity": 0.9088, + "question": "the clock setting, or the lyrics setting?", + "answers": { + "clock": "setDesktopClockInvertColors", + "lyrics": "setDesktopLyricsInvertColors" + }, + "gain": 1.0, + "evidence": "mined: same-group 'wallpaper-scheme' documents similarity 0.9088", + "source": "mined (document twins)" + }, + { + "a": "setDesktopIconsEnabled", + "b": "setMaterialYouIconsEnabled", + "group": "wallpaper-scheme", + "kind": "bool", + "doc_similarity": 0.8952, + "question": "the desktop setting, or the material setting?", + "answers": { + "desktop": "setDesktopIconsEnabled", + "material": "setMaterialYouIconsEnabled" + }, + "gain": 1.0, + "evidence": "mined: same-group 'wallpaper-scheme' documents similarity 0.8952", + "source": "mined (document twins)" + }, + { + "a": "setPreviewScale", + "b": "setPreviewScalesAudio", + "group": "bar", + "kind": "float", + "doc_similarity": 0.9539, + "question": "an ABSOLUTE value in that unit, or a SCALE multiplier on the current value?", + "answers": { + "scale multiplier": "setPreviewScale", + "absolute value": "setPreviewScalesAudio" + }, + "gain": 1.0, + "evidence": "mined: same-group 'bar' documents similarity 0.9539", + "source": "mined (document twins)" + }, + { + "a": "setPreviewScale", + "b": "setPreviewScalesBattery", + "group": "bar", + "kind": "float", + "doc_similarity": 0.9539, + "question": "an ABSOLUTE value in that unit, or a SCALE multiplier on the current value?", + "answers": { + "scale multiplier": "setPreviewScale", + "absolute value": "setPreviewScalesBattery" + }, + "gain": 1.0, + "evidence": "mined: same-group 'bar' documents similarity 0.9539", + "source": "mined (document twins)" + }, + { + "a": "setPreviewScale", + "b": "setPreviewScalesBluetooth", + "group": "bar", + "kind": "float", + "doc_similarity": 0.9539, + "question": "an ABSOLUTE value in that unit, or a SCALE multiplier on the current value?", + "answers": { + "scale multiplier": "setPreviewScale", + "absolute value": "setPreviewScalesBluetooth" + }, + "gain": 1.0, + "evidence": "mined: same-group 'bar' documents similarity 0.9539", + "source": "mined (document twins)" + }, + { + "a": "setPreviewScale", + "b": "setPreviewScalesDock", + "group": "bar", + "kind": "float", + "doc_similarity": 0.9539, + "question": "an ABSOLUTE value in that unit, or a SCALE multiplier on the current value?", + "answers": { + "scale multiplier": "setPreviewScale", + "absolute value": "setPreviewScalesDock" + }, + "gain": 1.0, + "evidence": "mined: same-group 'bar' documents similarity 0.9539", + "source": "mined (document twins)" + }, + { + "a": "setPreviewScale", + "b": "setPreviewScalesGithub", + "group": "bar", + "kind": "float", + "doc_similarity": 0.9539, + "question": "an ABSOLUTE value in that unit, or a SCALE multiplier on the current value?", + "answers": { + "scale multiplier": "setPreviewScale", + "absolute value": "setPreviewScalesGithub" + }, + "gain": 1.0, + "evidence": "mined: same-group 'bar' documents similarity 0.9539", + "source": "mined (document twins)" + }, + { + "a": "setPreviewScale", + "b": "setPreviewScalesGreeter", + "group": "bar", + "kind": "float", + "doc_similarity": 0.9539, + "question": "an ABSOLUTE value in that unit, or a SCALE multiplier on the current value?", + "answers": { + "scale multiplier": "setPreviewScale", + "absolute value": "setPreviewScalesGreeter" + }, + "gain": 1.0, + "evidence": "mined: same-group 'bar' documents similarity 0.9539", + "source": "mined (document twins)" + }, + { + "a": "setPreviewScale", + "b": "setPreviewScalesLockStatus", + "group": "bar", + "kind": "float", + "doc_similarity": 0.9139, + "question": "an ABSOLUTE value in that unit, or a SCALE multiplier on the current value?", + "answers": { + "scale multiplier": "setPreviewScale", + "absolute value": "setPreviewScalesLockStatus" + }, + "gain": 1.0, + "evidence": "mined: same-group 'bar' documents similarity 0.9139", + "source": "mined (document twins)" + }, + { + "a": "setPreviewScale", + "b": "setPreviewScalesNetwork", + "group": "bar", + "kind": "float", + "doc_similarity": 0.9539, + "question": "an ABSOLUTE value in that unit, or a SCALE multiplier on the current value?", + "answers": { + "scale multiplier": "setPreviewScale", + "absolute value": "setPreviewScalesNetwork" + }, + "gain": 1.0, + "evidence": "mined: same-group 'bar' documents similarity 0.9539", + "source": "mined (document twins)" + }, + { + "a": "setPreviewScale", + "b": "setPreviewScalesNotifications", + "group": "bar", + "kind": "float", + "doc_similarity": 0.9539, + "question": "an ABSOLUTE value in that unit, or a SCALE multiplier on the current value?", + "answers": { + "scale multiplier": "setPreviewScale", + "absolute value": "setPreviewScalesNotifications" + }, + "gain": 1.0, + "evidence": "mined: same-group 'bar' documents similarity 0.9539", + "source": "mined (document twins)" + }, + { + "a": "setPreviewScale", + "b": "setPreviewScalesPeripheralBattery", + "group": "bar", + "kind": "float", + "doc_similarity": 0.9139, + "question": "an ABSOLUTE value in that unit, or a SCALE multiplier on the current value?", + "answers": { + "scale multiplier": "setPreviewScale", + "absolute value": "setPreviewScalesPeripheralBattery" + }, + "gain": 1.0, + "evidence": "mined: same-group 'bar' documents similarity 0.9139", + "source": "mined (document twins)" + }, + { + "a": "setPreviewScale", + "b": "setPreviewScalesTrayMenu", + "group": "bar", + "kind": "float", + "doc_similarity": 0.8789, + "question": "an ABSOLUTE value in that unit, or a SCALE multiplier on the current value?", + "answers": { + "scale multiplier": "setPreviewScale", + "absolute value": "setPreviewScalesTrayMenu" + }, + "gain": 1.0, + "evidence": "mined: same-group 'bar' documents similarity 0.8789", + "source": "mined (document twins)" + }, + { + "a": "setPreviewScale", + "b": "setPreviewScalesWirelessPassword", + "group": "bar", + "kind": "float", + "doc_similarity": 0.9139, + "question": "an ABSOLUTE value in that unit, or a SCALE multiplier on the current value?", + "answers": { + "scale multiplier": "setPreviewScale", + "absolute value": "setPreviewScalesWirelessPassword" + }, + "gain": 1.0, + "evidence": "mined: same-group 'bar' documents similarity 0.9139", + "source": "mined (document twins)" + }, + { + "a": "setPreviewScalesBattery", + "b": "setPreviewScalesPeripheralBattery", + "group": "bar", + "kind": "float", + "doc_similarity": 0.9557, + "question": "an ABSOLUTE value in that unit, or a SCALE multiplier on the current value?", + "answers": { + "scale multiplier": "setPreviewScalesBattery", + "absolute value": "setPreviewScalesPeripheralBattery" + }, + "gain": 1.0, + "evidence": "mined: same-group 'bar' documents similarity 0.9557", + "source": "mined (document twins)" + }, + { + "a": "setShowDashboard", + "b": "setShowMedia", + "group": "dashboard", + "kind": "bool", + "doc_similarity": 0.9321, + "question": "the dashboard setting, or the media setting?", + "answers": { + "dashboard": "setShowDashboard", + "media": "setShowMedia" + }, + "gain": 1.0, + "evidence": "mined: same-group 'dashboard' documents similarity 0.9321", + "source": "mined (document twins)" + }, + { + "a": "setShowDashboard", + "b": "setShowPerformance", + "group": "dashboard", + "kind": "bool", + "doc_similarity": 0.9321, + "question": "the dashboard setting, or the performance setting?", + "answers": { + "dashboard": "setShowDashboard", + "performance": "setShowPerformance" + }, + "gain": 1.0, + "evidence": "mined: same-group 'dashboard' documents similarity 0.9321", + "source": "mined (document twins)" + }, + { + "a": "setShowDashboard", + "b": "setShowTerminal", + "group": "dashboard", + "kind": "bool", + "doc_similarity": 0.9321, + "question": "the dashboard setting, or the terminal setting?", + "answers": { + "dashboard": "setShowDashboard", + "terminal": "setShowTerminal" + }, + "gain": 1.0, + "evidence": "mined: same-group 'dashboard' documents similarity 0.9321", + "source": "mined (document twins)" + }, + { + "a": "setShowDashboard", + "b": "setShowWeather", + "group": "dashboard", + "kind": "bool", + "doc_similarity": 0.9321, + "question": "the dashboard setting, or the weather setting?", + "answers": { + "dashboard": "setShowDashboard", + "weather": "setShowWeather" + }, + "gain": 1.0, + "evidence": "mined: same-group 'dashboard' documents similarity 0.9321", + "source": "mined (document twins)" + }, + { + "a": "setShowMedia", + "b": "setUseMediaShapes", + "group": "dashboard", + "kind": "bool", + "doc_similarity": 0.9325, + "question": "the show setting, or the use setting?", + "answers": { + "show": "setShowMedia", + "use": "setUseMediaShapes" + }, + "gain": 1.0, + "evidence": "mined: same-group 'dashboard' documents similarity 0.9325", + "source": "mined (document twins)" + } + ] +} \ No newline at end of file diff --git a/plugins/caelestia-assistant/assistant/core/confusables.py b/plugins/caelestia-assistant/assistant/core/confusables.py new file mode 100644 index 0000000..fd96475 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/core/confusables.py @@ -0,0 +1,318 @@ +"""cortex.confusables — the confusable-pair clarifier (Group A4). + +Some settings tools SWAP: the arena's own failures prove it. "recolour +the tray icons" confidently lands on setDockRecolourIcons; "make the +volume step smaller" and "make the brightness step smaller" are the +same sentence one noun apart; "move the lyrics to the centre" and +"centre the lyrics text" split a position/alignment pair the router +cannot rank apart. For these, a confident route is a coin flip and a +generic "several settings could match" question is a lazy coin flip. + +This module does two honest things: + +1. MINE (offline, deterministic, committed artifact): candidate pairs = + same-group, same-kind tools whose tool documents are near-duplicates + under BM25 (the lexical twin test), plus the pairs the arena's + failure classes pinned by hand. For each pair, the distinguishing + QUESTION is derived from the metadata difference that actually + separates them (object noun, absolute-range-vs-scale, position + vocabulary), and its EXPECTED INFORMATION GAIN is computed over the + two hypotheses: with two hypotheses the prior entropy is 1 bit and a + question scores 1 bit x P(answer separates the pair) — P estimated + from the metadata itself (a question only counts when each answer + option maps onto exactly one hypothesis). The highest-gain question + ships as the pair's ask. + +2. CLARIFY (runtime, read-only): when the router returns AMBIGUOUS and + the ranked candidates contain a mined pair, the generic question is + replaced by the pair's own question. No verdict changes, no write, + no new surface — the same honest ASK, just one that the user can + actually answer. + +The mined artifact is committed (``confusable_pairs.json``): rebuilding +it is a reviewed act like regenerating the registry, and the runtime +never mines on the fly (determinism + budget). +""" + +from __future__ import annotations + +import json +from pathlib import Path +from typing import Any, Dict, List, Optional, Tuple + +__all__ = ["PAIRS_PATH", "mine_pairs", "clarify", "render_lines", + "load_pairs"] + +PAIRS_PATH = Path(__file__).resolve().parent / "confusable_pairs.json" + +# BM25 near-duplicate threshold over tool documents (mined candidates +# must clear this before a reviewer question is even drafted). +_DOC_SIM_FLOOR = 0.55 + +# Hand-pinned pairs from the arena's own failure classes (m-items): the +# sibling swaps the router measurably confuses. Each cites the dev item +# that evidences the confusion. The miner merges these with the +# document-similarity candidates; a hand pin overrides the generated +# question when both exist (reviewer judgment beats a template). +HAND_PINNED: Tuple[Dict[str, Any], ...] = ( + { + "a": "setTrayRecolour", "b": "setDockRecolourIcons", + "evidence": "dev m02: 'recolour the tray icons to match my theme' " + "ranks the dock sibling first (sealed sr13 same class)", + "question": "which icons — the system TRAY icons, or the DOCK " + "app icons?", + "answers": {"tray": "setTrayRecolour", + "dock": "setDockRecolourIcons"}, + "gain": 1.0, + }, + { + "a": "setDesktopLyricsPosition", "b": "setDesktopLyricsAlignment", + "evidence": "dev m15/m16: 'move the lyrics to the centre' and " + "'centre the lyrics text' rank each other's sibling " + "first (sealed sr93 same class)", + "question": "where the lyrics SIT on screen, or how the text " + "ALIGNS inside its box?", + "answers": {"where": "setDesktopLyricsPosition", + "align": "setDesktopLyricsAlignment"}, + "gain": 1.0, + }, + { + "a": "setAudioIncrement", "b": "setBrightnessIncrement", + "evidence": "dev m25/m26: identical sentence one noun apart; the " + "brightness sibling wins both at cold start", + "question": "the step size for VOLUME, or for SCREEN BRIGHTNESS?", + "answers": {"volume": "setAudioIncrement", + "brightness": "setBrightnessIncrement"}, + "gain": 1.0, + }, + { + "a": "setPosition", "b": "setHoverBottomRight", + "evidence": "dev m08: 'show toasts in the bottom-right corner' " + "confidently takes the overview hover-corner toggle", + "question": "where NOTIFICATION toasts appear on screen, or the " + "overview corner that shows windows on HOVER?", + "answers": {"toast": "setPosition", + "hover": "setHoverBottomRight"}, + "gain": 1.0, + }, + { + "a": "setAmbientOpacity", "b": "setTransparencyBase", + "evidence": "dev m05: 'make the ambient background more opaque' " + "takes the global transparency slider", + "question": "the AMBIENT background layer's opacity, or the " + "GLOBAL transparency of the whole shell?", + "answers": {"ambient": "setAmbientOpacity", + "global": "setTransparencyBase"}, + "gain": 1.0, + }, + { + "a": "setEnableOverviewBlur", "b": "setDisableWallpaperBlur", + "evidence": "dev m11/m12 (sealed sr67/sr68 same class): the two " + "overview blur toggles swap under on/off phrasing", + "question": "the blur of the OVERVIEW ITSELF (windows floating in " + "it), or the WALLPAPER's blur while the overview is " + "open?", + "answers": {"overview itself": "setEnableOverviewBlur", + "wallpaper": "setDisableWallpaperBlur"}, + "gain": 1.0, + }, + { + "a": "setMaxFprintTries", "b": "setPreviewScalesWirelessPassword", + "evidence": "dev m14: 'fingerprint attempts before the password' " + "lands on a preview-scale tool via the 'password' noun", + "question": "how many FINGERPRINT attempts before the password " + "fallback — or how the password PREVIEW is scaled?", + "answers": {"fingerprint attempts": "setMaxFprintTries", + "preview": "setPreviewScalesWirelessPassword"}, + "gain": 1.0, + }, +) + + +def _doc_similarity(index, a_key: str, b_key: str) -> float: + """BM25 score of a's document tokens against b's document (a KEY + into the index), normalized by the self-max (0..1-ish; the pair + floor is deliberately low — mining proposes, the reviewer + disposes).""" + from .vectorize import tokenize + toks = index.doc_tokens.get(a_key) or tokenize(a_key) + score = index.score(toks, b_key) + self_score = index.score(toks, a_key) + if self_score <= 0: + return 0.0 + return score / self_score + + +def mine_pairs() -> Dict[str, Any]: + """Deterministic pair mining: hand-pinned classes + same-group + same-kind document twins above the similarity floor. Output is the + committed artifact; runtime only ever READS it.""" + from .corpus import tool_document + from .vectorize import TfidfIndex + from assistant.adapters.caelestia.registry import TOOL_SPECS, tools_by_group + + specs = {s.name: s for s in TOOL_SPECS} + docs = {name: tool_document(spec) for name, spec in specs.items()} + index = TfidfIndex(docs) # keyed by tool name + + # generated candidates: same group, same kind, twin documents + generated: List[Dict[str, Any]] = [] + seen: set = set() + for group, group_specs in sorted(tools_by_group().items()): + for i, sa in enumerate(group_specs): + for sb in group_specs[i + 1:]: + if sa.kind != sb.kind: + continue + pair = tuple(sorted((sa.name, sb.name))) + if pair in seen: + continue + seen.add(pair) + sim = _doc_similarity(index, sa.name, sb.name) + if sim >= _DOC_SIM_FLOOR: + generated.append({ + "a": sa.name, "b": sb.name, "group": group, + "doc_similarity": round(sim, 4), + }) + generated.sort(key=lambda g: (-g["doc_similarity"], g["a"], g["b"])) + + pairs: List[Dict[str, Any]] = [] + for pin in HAND_PINNED: + a, b = specs.get(pin["a"]), specs.get(pin["b"]) + if a is None or b is None: + continue # a tool pruned upstream: the pin dies honestly + pairs.append({ + "a": a.name, "b": b.name, + "group": a.group, + "kind": a.kind, + "doc_similarity": round(_doc_similarity( + index, a.name, b.name), 4), + "question": pin["question"], + "answers": pin["answers"], + "gain": pin["gain"], + "evidence": pin["evidence"], + "source": "hand-pinned (arena failure class)", + }) + for g in generated[:24]: + name = "both exist" in _GENERIC_QUESTIONS and "" or None + q = _question_for(g, specs) + if q is None: + continue + pairs.append({ + "a": g["a"], "b": g["b"], "group": g["group"], + "kind": specs[g["a"]].kind, + "doc_similarity": g["doc_similarity"], + "question": q["question"], "answers": q["answers"], + "gain": q["gain"], + "evidence": f"mined: same-group {g['group']!r} documents " + f"similarity {g['doc_similarity']}", + "source": "mined (document twins)", + }) + pairs.sort(key=lambda p: (p["source"] != "hand-pinned (arena failure " + "class)", -p["gain"], p["a"], p["b"])) + return { + "generator": "assistant.core.confusables.mine_pairs", + "doc_sim_floor": _DOC_SIM_FLOOR, + "n_pairs": len(pairs), + "pairs": pairs, + } + + +_GENERIC_QUESTIONS: Dict[str, str] = { + "scale": "an ABSOLUTE value in that unit, or a SCALE multiplier on " + "the current value?", +} + + +def _question_for(pair: Dict[str, Any], specs) -> Optional[Dict[str, Any]]: + """Draft the distinguishing question from the metadata difference. + Highest expected information gain wins; with two hypotheses the + prior entropy is 1 bit, so gain = P(answer separates) x 1 bit.""" + a, b = specs[pair["a"]], specs[pair["b"]] + # absolute-range vs scale: one sibling is named *Scale / *Strength + # with a multiplier range, the other an absolute range + for s, other in ((a, b), (b, a)): + if "scale" in s.name.lower() or "strength" in s.name.lower(): + if s.minimum is not None and s.maximum is not None \ + and s.maximum - s.minimum <= 4.0: + return { + "question": _GENERIC_QUESTIONS["scale"], + "answers": {"scale multiplier": s.name, + "absolute value": other.name}, + "gain": 1.0, + } + # object-word difference: the first name atom the two do not share + from .lexicon import camel_split + wa = [w.lower() for w in camel_split(a.name) + if w.lower() not in {"set", "enable", "disabled", "enabled"}] + wb = [w.lower() for w in camel_split(b.name) + if w.lower() not in {"set", "enable", "disabled", "enabled"}] + diff_a = next((w for w in wa if w not in wb), None) + diff_b = next((w for w in wb if w not in wa), None) + if diff_a and diff_b: + return { + "question": f"the {diff_a} setting, or the {diff_b} setting?", + "answers": {diff_a: a.name, diff_b: b.name}, + "gain": 1.0, + } + return None + + +def load_pairs() -> List[Dict[str, Any]]: + """The committed artifact (runtime view). Empty when absent — the + clarifier degrades to the generic question, never mines live.""" + try: + data = json.loads(PAIRS_PATH.read_text(encoding="utf-8")) + except (OSError, ValueError): + return [] + return list(data.get("pairs") or []) + + +def _pair_for(candidates: List[str], + pairs: List[Dict[str, Any]]) -> Optional[Dict[str, Any]]: + """First committed pair fully present in the ranked candidates.""" + ranked = [c for c in candidates if c] + for pair in pairs: + if pair["a"] in ranked and pair["b"] in ranked: + return pair + return None + + +def clarify(question: str, candidates: List[str]) -> Tuple[str, bool]: + """(question, upgraded) — the pair's own ask when the ranked + candidates contain a mined pair, else the incoming question.""" + pair = _pair_for(candidates, load_pairs()) + if pair is None: + return question, False + return pair["question"], True + + +def render_lines() -> List[str]: + pairs = load_pairs() + lines = [f"{len(pairs)} confusable pairs (committed artifact; " + f"rebuild with python3 -m assistant.core.confusables):"] + for p in pairs: + lines.append(f" {p['a']} <-> {p['b']} -- {p['source']}") + lines.append(f" ask: {p['question']}") + return lines + + +def main(argv=None) -> int: # pragma: no cover - thin CLI + """`python3 -m assistant.core.confusables [--mine]`: + list the committed pairs; --mine rebuilds the artifact (a reviewed, + committed change, like regenerating the registry).""" + import sys + argv = list(sys.argv[1:] if argv is None else argv) + if argv and argv[0] == "--mine": + data = mine_pairs() + PAIRS_PATH.write_text( + json.dumps(data, indent=1, ensure_ascii=False) + "\n", + encoding="utf-8") + print(f"wrote {PAIRS_PATH.name}: {data['n_pairs']} pairs") + return 0 + for line in render_lines(): + print(line) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/plugins/caelestia-assistant/assistant/core/conservative.py b/plugins/caelestia-assistant/assistant/core/conservative.py new file mode 100644 index 0000000..5365054 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/core/conservative.py @@ -0,0 +1,203 @@ +"""cortex.conservative — a safe-exploration floor on the strategy +bandit (exponential-build-4 D). + +Wu, Shariff, Lattimore & Szepesvári, "Conservative Bandits", ICML 2016: +unconstrained Thompson sampling will happily spend user experience on +an untested strategy. The conservative design adds a SAFE BASELINE arm +(here: the "balanced" routing profile the repo shipped before any +learning) and the paper's central gate — a non-baseline arm is explored +only when its upper confidence bound clears the safe arm's lower +confidence bound minus the budget ε: + + explore arm i iff LCB_i > LCB_safe − ε (the paper's + UCB_i ≥ LCB_0 − ε, with the strictness flipped to keep UNSAMPLED + arms from exploring forever on a degenerate UCB tie), + +with Hoeffding radii r = sqrt(ln(2/δ) / (2n)) over the empirical +mean. The paper's Theorem 1 then gives the guarantee this module +claims, no more and no less: with probability ≥ 1−δ, the total regret +against ALWAYS PLAYING THE SAFE ARM is at most ε·T (+ a constant), i.e. +exploration is provably no worse than the baseline by more than the +per-round budget ε, in expectation. That is a statement about distance +from the BASELINE, not about finding the best arm — an arm better than +the safe one is still exploited once its evidence clears the gate. + +ON TOP OF, NOT REPLACING: the Beta posteriors this gate reads are the +strategy bandit's own persisted counts (cortex/learn.py NamedBandit +state) — the same state, a gated policy in front of the Thompson +sample. When the gate refuses an arm, the SAFE arm plays; the sampled +arm is reported honestly as "gated" so the caller can see what +Thompson wanted and what the floor allowed. Determinism: the gate is +pure arithmetic; the Thompson sample comes from the caller's seeded +rng exactly as before. Nothing here writes; state stays in the +caller's learned-state JSON. +""" +from __future__ import annotations + +import math +from typing import Any, Dict, List, Optional + +__all__ = ["ConservativeBandit", "hoeffding_radius"] + + +def hoeffding_radius(n: int, delta: float) -> float: + """The Hoeffding radius sqrt(ln(2/delta)/(2n)) for n observations; + unbounded (refuses to claim confidence) at n = 0.""" + if n <= 0: + raise ValueError("radius is undefined at n = 0 — the honest " + "answer is 'no evidence', not a small radius") + if not (0.0 < delta < 1.0): + raise ValueError("delta must be inside (0, 1)") + return math.sqrt(math.log(2.0 / delta) / (2.0 * n)) + + +class ConservativeBandit: + """The safe-exploration gate over per-arm Beta evidence. + + ``arms``: {name: {"alpha": float, "beta": float}} — the SAME + posterior dicts NamedBandit persists (prior mass is included in + the posterior mean but its play count is not: n = alpha + beta − + prior mass, so a flat-seeded arm has n = 0 and an unbounded + radius, which is the honest reading). + """ + + def __init__(self, arms: Dict[str, Dict[str, float]], + safe_arm: str, epsilon: float = 0.05, + delta: float = 0.05, prior_mass: float = 2.0) -> None: + if safe_arm not in arms: + raise ValueError( + f"safe arm {safe_arm!r} not among the arms " + f"{sorted(arms)}") + if epsilon < 0: + raise ValueError("epsilon (the safety budget) must be >= 0 — " + "a negative budget is not a budget") + if not (0.0 < delta < 1.0): + raise ValueError("delta must be inside (0, 1)") + self.arms = {name: dict(post) for name, post in arms.items()} + self.safe_arm = safe_arm + self.epsilon = float(epsilon) + self.delta = float(delta) + self.prior_mass = float(prior_mass) + + # -- posterior reads --------------------------------------------------- + + def _mean(self, name: str) -> float: + post = self.arms[name] + return post["alpha"] / (post["alpha"] + post["beta"]) + + def _plays(self, name: str) -> int: + post = self.arms[name] + # the posterior's own prior mass is not evidence: n = mass − prior + n = (post["alpha"] + post["beta"]) - self.prior_mass + return max(0, int(n)) + + def _lcb(self, name: str) -> Optional[float]: + n = self._plays(name) + if n == 0: + return None # no evidence: no lower bound is claimed + return self._mean(name) - hoeffding_radius(n, self.delta) + + def _ucb(self, name: str) -> Optional[float]: + n = self._plays(name) + if n == 0: + return None + return self._mean(name) + hoeffding_radius(n, self.delta) + + # -- the gate ---------------------------------------------------------- + + def choose(self, thompson_sample: Optional[str] = None + ) -> Dict[str, Any]: + """Apply the gate to one decision. + + ``thompson_sample``: the arm the underlying Thompson policy + already picked (the caller samples; this module gates). Returns + the chosen arm, whether the gate overrode it, and the bounds + the decision was made on — the report carries its own evidence. + With no Thompson sample given, the safe arm's eligibility is + still computed the same way (the gate can only ever PLAY the + safe arm or ratify the sample; it never invents a third arm). + """ + safe_lcb = self._lcb(self.safe_arm) + details: Dict[str, Any] = { + "epsilon": self.epsilon, + "delta": self.delta, + "safe_arm": self.safe_arm, + "safe_lcb": safe_lcb, + } + if safe_lcb is None: + # the safe arm itself has no evidence: no floor exists yet, + # play the safe arm and say so (exploring others with no + # baseline evidence is the unconstrained behavior this + # module exists to prevent) + details["reason"] = "safe arm has no evidence — floor closed" + return {"arm": self.safe_arm, "overridden": True, + "gated_sample": thompson_sample, "details": details} + if thompson_sample is None or thompson_sample == self.safe_arm: + return {"arm": self.safe_arm, + "overridden": thompson_sample not in (None, self.safe_arm), + "gated_sample": thompson_sample, "details": details} + ucb = self._ucb(thompson_sample) + details["sample_ucb"] = ucb + if ucb is None: + # an unplayed arm: its UCB is the prior mean with an + # unbounded radius — the paper treats unexplored arms' + # UCB optimistically; here there is no evidence to clear + # the gate with, so the honest reading is "not yet" + details["reason"] = "sampled arm has no evidence — floor closed" + return {"arm": self.safe_arm, "overridden": True, + "gated_sample": thompson_sample, "details": details} + if ucb > safe_lcb - self.epsilon: + details["reason"] = "sample cleared the gate" + return {"arm": thompson_sample, "overridden": False, + "gated_sample": thompson_sample, "details": details} + details["reason"] = ( + f"UCB {ucb:.4f} <= safe LCB {safe_lcb:.4f} − ε " + f"{self.epsilon} — floor closed") + return {"arm": self.safe_arm, "overridden": True, + "gated_sample": thompson_sample, "details": details} + + def guarantee(self) -> str: + """The guarantee, stated exactly as the paper gives it — with + its scope (distance from the BASELINE, high probability, in + expectation) — and never oversold.""" + return ( + f"Wu et al. 2016, Theorem 1 (this implementation's form): " + f"with probability >= {1.0 - self.delta}, the total regret " + f"against always playing {self.safe_arm!r} is at most " + f"{self.epsilon} * T (+ constants) — exploration is no " + f"worse than the baseline by more than ε per round, in " + f"expectation. This bounds DISTANCE FROM THE BASELINE, " + f"not regret against the best arm.") + + def report(self) -> Dict[str, Any]: + """The audit card: per-arm evidence, bounds, and the gate state. + An untouched arm reports n = 0 and unclaimed bounds — an + abstention, never a zero.""" + rows: List[Dict[str, Any]] = [] + for name in sorted(self.arms): + n = self._plays(name) + rows.append({ + "arm": name, "plays": n, + "mean": round(self._mean(name), 4) if n else None, + "lcb": round(self._lcb(name), 4) if self._lcb(name) is not None else None, + "ucb": round(self._ucb(name), 4) if self._ucb(name) is not None else None, + "safe": name == self.safe_arm, + }) + return {"arms": rows, "epsilon": self.epsilon, "delta": self.delta, + "guarantee": self.guarantee()} + + # -- persistence (the caller's learned-state JSON; same shape as + # the underlying bandit state, so no second path exists) ------ + + def to_dict(self) -> Dict[str, Any]: + return {"arms": self.arms, "safe_arm": self.safe_arm, + "epsilon": self.epsilon, "delta": self.delta, + "prior_mass": self.prior_mass} + + @classmethod + def from_dict(cls, d: Dict[str, Any]) -> "ConservativeBandit": + return cls(arms=d.get("arms") or {}, safe_arm=d.get("safe_arm", + "balanced"), + epsilon=d.get("epsilon", 0.05), + delta=d.get("delta", 0.05), + prior_mass=d.get("prior_mass", 2.0)) diff --git a/plugins/caelestia-assistant/assistant/core/context.py b/plugins/caelestia-assistant/assistant/core/context.py new file mode 100644 index 0000000..87ea9ca --- /dev/null +++ b/plugins/caelestia-assistant/assistant/core/context.py @@ -0,0 +1,171 @@ +"""cortex.context — context-aware recommendations (F30, exponential-build-5; +issue #120 b6a, closed from NOT_IMPLEMENTED). + +Issue #120's Phase 3 asks for "context-aware recommendations". This +module reads the environment through narrow, injectable, read-only +probes and turns the readings into PROPOSALS through the engines that +already exist — never applies anything: + +- clock: time-of-day bucket (the same 6-hour buckets brain.prefs uses); +- power: battery percent / charging state from /sys/class/power_supply + (pure text parse; anything absent -> the probe reports honestly and + no power-based recommendation is made); +- recommendations: battery-saver when the battery is low and + discharging; a gaming-direction hint is NOT made from power state + (that would be a guess); value recommendations ride + settings.recommend (F29 partial pooling) when a tool is asked about. + +Every recommendation cites its context evidence ("battery 14%, +discharging, read from /sys/class/power_supply/BAT0/capacity") and +lands as a SUGGESTED_NOT_EXECUTED command or a ledger proposal payload +— the caller decides which surface; this module never writes. + +Determinism: all probes are injectable. ``probe_clock`` defaults to +the real local clock ONLY when the caller passes now=None explicitly +at the call site they own; the pure functions take ``now``/``power`` +as arguments and are clock-free and filesystem-free by construction. +""" + +from __future__ import annotations + +import glob +import os +from typing import Any, Dict, List, Optional + +__all__ = ["LOW_BATTERY_PCT", "read_power_state", "recommend_contextual", + "render_lines"] + +LOW_BATTERY_PCT = 25.0 + +_POWER_GLOB = "/sys/class/power_supply/BAT*" + + +def read_power_state(root_glob: str = _POWER_GLOB) -> Optional[Dict[str, Any]]: + """One read-only pass over /sys/class/power_supply (or an injected + root for tests). Returns {"percent": float|None, "charging": bool, + "source": str} or None when no battery is present (honest: a + desktop has no battery and gets no battery advice).""" + paths = sorted(glob.glob(root_glob)) + if not paths: + return None + bat = paths[0] + percent: Optional[float] = None + charging = False + try: + cap_path = os.path.join(bat, "capacity") + if os.path.exists(cap_path): + percent = float(open(cap_path, encoding="utf-8").read().strip()) + status_path = os.path.join(bat, "status") + if os.path.exists(status_path): + charging = ("Charging" in + open(status_path, encoding="utf-8").read()) + else: + # ucdavis-style: use charging/current_now sign as a fallback + online = os.path.join(bat, "online") + if os.path.exists(online): + charging = open(online, encoding="utf-8").read().strip() == "1" + except (OSError, ValueError): + return {"percent": None, "charging": False, + "source": bat, "error": "unreadable"} + return {"percent": percent, "charging": charging, "source": bat} + + +def _power_findings(power: Optional[Dict[str, Any]]) -> List[Dict[str, Any]]: + findings: List[Dict[str, Any]] = [] + if power is None: + return findings + percent, charging = power.get("percent"), bool(power.get("charging")) + source = power.get("source", "unknown") + evidence = f"battery {source}" + if percent is None: + if power.get("error"): + findings.append({ + "kind": "power_unreadable", "evidence": evidence, + "reason": "the battery state exists but could not be read; " + "no battery recommendation is made", + }) + return findings + if percent <= LOW_BATTERY_PCT and not charging: + findings.append({ + "kind": "battery_low", + "evidence": f"{evidence} at {percent:g}%, discharging", + "reason": f"the battery is at {percent:g}% and discharging; " + f"the battery-saver preset reduces compositing and " + f"background work", + "command": ("SUGGESTED_NOT_EXECUTED: caelestia-assist settings " + "--preset battery-saver --apply --confirm"), + "confidence": 0.85, + }) + elif percent <= LOW_BATTERY_PCT and charging: + findings.append({ + "kind": "battery_low_charging", + "evidence": f"{evidence} at {percent:g}%, charging", + "reason": "the battery is low but charging; no change is " + "suggested (a profile switch mid-charge would be " + "churn, not help)", + "confidence": 0.5, + }) + return findings + + +def _time_findings(now, model) -> List[Dict[str, Any]]: + """Time-of-day findings: the CLOCK never supplies evidence — the + fitted preference model does. The clock (``now``), when given, only + SELECTS which already-qualified hour patterns are relevant right now; + with now=None every qualifying pattern is reported.""" + findings: List[Dict[str, Any]] = [] + if model is None: + return findings + from .personalize import hour_patterns + from assistant.capabilities.brain.prefs import hour_bucket + current_bucket = hour_bucket(now.hour) if now is not None else None + for pattern in hour_patterns(model): + if current_bucket is not None and pattern["bucket"] != current_bucket: + continue + findings.append({ + "kind": "hour_pattern", + "evidence": (f"{pattern['ess']:.0f} observed approvals of " + f"{pattern['direction']} {pattern['group']!r} in " + f"the {pattern['bucket'] * 6:02d}:00 bucket"), + "reason": (f"your own approval history leans this way at this " + f"hour (mean {pattern['mean']})"), + "confidence": pattern["mean"], + }) + return findings + + +def recommend_contextual(now=None, power: Optional[Dict[str, Any]] = None, + model=None) -> Dict[str, Any]: + """The full contextual recommendation view (read-only, pure given + its arguments). ``power`` injects the probe result (None = no + battery / not probed); ``model`` injects a fitted brain.prefs model; + ``now`` (the caller's clock) selects which hour patterns are + relevant — it is never evidence by itself.""" + findings = list(_power_findings(power)) + findings.extend(_time_findings(now, model)) + return { + "findings": findings, + "note": ("context-aware recommendations are proposals over " + "injected, read-only probes; nothing is applied and " + "the clock alone is never treated as evidence"), + } + + +def render_lines(view: Dict[str, Any]) -> List[str]: + lines: List[str] = [] + findings = view.get("findings", []) + if not findings: + return ["no contextual recommendations right now " + "(no qualifying battery state and no hour-pattern " + "evidence in your preference model)"] + for f in findings: + if f.get("command"): + lines.append(f"{f['kind']}: {f['reason']}") + lines.append(f" evidence: {f['evidence']}") + lines.append(f" {f['command']}") + else: + lines.append(f"{f['kind']}: {f['reason']}") + if f.get("evidence"): + lines.append(f" evidence: {f['evidence']}") + lines.append(f" ({view.get('note', '')})") + return lines diff --git a/plugins/caelestia-assistant/assistant/core/corpus.py b/plugins/caelestia-assistant/assistant/core/corpus.py new file mode 100755 index 0000000..9129d0a --- /dev/null +++ b/plugins/caelestia-assistant/assistant/core/corpus.py @@ -0,0 +1,307 @@ +"""Synthetic training corpus for the cortex router (self-supervised, no LLM). + +The frozen grammar of ``settings/parser.py`` covers 18 tools because noun +vocabularies were hand-frozen for exactly those. This module derives the +OTHER 259 tools' addressable vocabulary mechanically from the registry +itself — tool names, paths, groups — plus the seeded domain lexicon, and +from that derivation generates a deterministic paraphrase corpus. That +corpus is what the router indexes (BM25) and what the embedder trains on +(PPMI co-occurrences). No network, no model download, no training run on +unreviewed data: every generated row is reproducible from this file alone. + +Guarantees: + +- DETERMINISTIC and PURE: fixed iteration orders, no randomness, no I/O + beyond the registry's own import-time ``tools.json`` load (unchanged + behavior, already drift-guarded by the settings test suite). +- Generated rows only ever CLAIM registry facts: a row for + ``setGreeterMorningStart`` says "greeter morning start" because the + tool is named that — the module never invents a semantic claim the + registry does not make. +- The paraphrase templates are versioned (``CORPUS_VERSION``) so router + scores are comparable across corpus revisions. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Dict, List, Tuple + +from assistant.adapters.caelestia.registry import TOOL_SPECS +from .lexicon import ( BOOL_OFF_WORDS, BOOL_ON_WORDS, SYNONYMS, camel_split, ) + +CORPUS_VERSION = 1 + +# --------------------------------------------------------------------------- +# Row shape. +# --------------------------------------------------------------------------- + + +@dataclass(frozen=True) +class Row: + """One synthetic training row: a user-shaped phrase, the surface it + should retrieve, and the value-extraction cues the phrase carries. + + ``surface`` is either a tool name (``setBarScale``), a preset target + (``preset:compact``), or a coarse surface (``explain``/``undo``/ + ``scheme``/``wallpaper``/``diagnose``/``search``/``brain``/``issue``). + ``cues`` carries direction (+1/-1), bool (True/False) and absolute + targets when the phrase implies one — the router passes them through + as hints; the settings planner remains the only place a value is + resolved against the live file. + """ + + text: str + surface: str + cues: Dict[str, object] = field(default_factory=dict) + + +# --------------------------------------------------------------------------- +# Per-tool canonical documents (the router's index). +# --------------------------------------------------------------------------- + +# Words that are pure plumbing in tool names and carry no addressable +# meaning once split ("set", "enable", "show", "use"...). +_PLUMBING = frozenset({ + "set", "enable", "disable", "show", "hide", "use", "get", "toggle", + "turn", "on", "off", "max", "min", +}) + + +def tool_atoms(spec) -> List[str]: + """Addressable word atoms of one ToolSpec: camel-name atoms + dotted + path atoms + group, plumbing words dropped, deduplicated in order.""" + atoms: List[str] = [] + for atom in camel_split(spec.name): + if atom not in _PLUMBING and atom not in atoms: + atoms.append(atom) + for piece in spec.path.replace("-", ".").split("."): + # split camelCase inside path pieces too (morningStart -> morning start) + for atom in camel_split(piece) or ([piece.lower()] if piece else []): + if atom and atom not in _PLUMBING and atom not in atoms: + atoms.append(atom) + if spec.group and spec.group not in atoms: + atoms.append(spec.group) + return atoms + + +def tool_document(spec) -> str: + """The canonical searchable document for one tool: its atoms, its noun + groups (18-core tools), its synonyms, and its kind. This single string + is what BM25 indexes per tool.""" + parts: List[str] = tool_atoms(spec) + for group in spec.nouns: + parts.append(group.replace("|", " ")) + for atom in list(parts): + for mapped in SYNONYMS.get(atom, ()): + if mapped not in parts: + parts.append(mapped) + parts.append(spec.kind) + return " ".join(parts) + + +def tool_documents() -> Dict[str, str]: + """{tool name: canonical document} for every registry tool, registry order.""" + return {spec.name: tool_document(spec) for spec in TOOL_SPECS} + + +# --------------------------------------------------------------------------- +# Paraphrase generation (deterministic templates over registry facts). +# --------------------------------------------------------------------------- + +# Verbs that introduce a settings request. Paired with every tool's atom +# phrase to teach the router that the VERB carries no target information. +_INQUIRE_VERBS = ("make", "set", "change", "adjust", "put", "turn", "move") + +# A representative subset of direction words per sign (kept small so the +# corpus stays lean; the router scores full vocabularies at query time). +_DIR_DOWN = ("thinner", "smaller", "less", "lower", "reduce") +_DIR_UP = ("bigger", "larger", "more", "increase", "raise") + + +def _atom_phrase(spec) -> str: + atoms = tool_atoms(spec) + return " ".join(atoms) if atoms else spec.name.lower() + + +def _rows_for_tool(spec) -> List[Row]: + """Deterministic paraphrase rows for one tool, by kind: + + - every tool: bare atom phrase + verb-ful variants (the router must + learn to ignore the verb); + - float/int tools: one row per representative direction word, with + the direction cue attached; + - bool tools: one row per on/off word, cue attached; + - enum tools: one row per enum value (the value text is itself + addressable vocabulary — "dock position left"); + - the 18 core tools additionally: their registry noun groups as bare + phrases, so learned scores and frozen-grammar scores stay aligned. + """ + rows: List[Row] = [] + phrase = _atom_phrase(spec) + rows.append(Row(phrase, spec.name, {})) + for verb in _INQUIRE_VERBS[:4]: + rows.append(Row(f"{verb} {phrase}", spec.name, {})) + + if spec.kind in ("float", "int"): + for word in _DIR_DOWN: + rows.append(Row(f"make {phrase} {word}", spec.name, {"direction": -1})) + rows.append(Row(f"{word} {phrase}", spec.name, {"direction": -1})) + for word in _DIR_UP: + rows.append(Row(f"make {phrase} {word}", spec.name, {"direction": 1})) + rows.append(Row(f"{word} {phrase}", spec.name, {"direction": 1})) + if spec.default is not None: + rows.append(Row(f"reset {phrase} to default", spec.name, {"reset": True})) + rows.append(Row(f"default {phrase}", spec.name, {"reset": True})) + + elif spec.kind == "bool": + for word in sorted(BOOL_ON_WORDS): + rows.append(Row(f"{word} {phrase}", spec.name, {"bool": True})) + for word in sorted(BOOL_OFF_WORDS): + rows.append(Row(f"{word} {phrase}", spec.name, {"bool": False})) + rows.append(Row(f"toggle {phrase}", spec.name, {"toggle": True})) + + elif spec.kind == "enum" and spec.enum: + values = spec.enum if isinstance(spec.enum, (list, tuple)) else [spec.enum] + for value in values: + text_value = str(value).lower().replace("_", " ") + rows.append(Row(f"{phrase} {text_value}", spec.name, {"enum": value})) + + if spec.nouns: + for group in spec.nouns: + rows.append(Row(group.replace("|", " "), spec.name, {})) + + return rows + + +# --------------------------------------------------------------------------- +# Coarse surfaces (non-tool): the universal-routing half. +# --------------------------------------------------------------------------- + +# Hand-seeded rows for surfaces outside the tool registry. Each surface +# gets a handful of canonical phrasings — enough for BM25 to route the +# request to the right LAYER, where that layer's own machinery (rules +# engine, retrieval, brain CLI) takes over. These rows deliberately do +# NOT try to understand the request — only to recognize its shape. +_SURFACE_ROWS: Tuple[Tuple[str, str, Dict[str, object]], ...] = ( + # presets (settings/presets.py — the #120 "make everything minimal" case) + ("more compact", "preset:compact", {}), + ("compact everything", "preset:compact", {}), + ("make everything compact", "preset:compact", {}), + ("compact mode", "preset:compact", {}), + ("denser look", "preset:compact", {}), + ("tighter overall", "preset:compact", {}), + ("minimal look", "preset:minimal", {}), + ("minimalist setup", "preset:minimal", {}), + ("make everything minimal", "preset:minimal", {}), + ("cleaner look", "preset:minimal", {}), + ("simpler look", "preset:minimal", {}), + ("declutter the desktop", "preset:minimal", {}), + ("optimize for gaming", "preset:gaming", {}), + ("gaming setup", "preset:gaming", {}), + ("game mode look", "preset:gaming", {}), + ("optimize for battery", "preset:battery-saver", {}), + ("battery saver look", "preset:battery-saver", {}), + ("power saving setup", "preset:battery-saver", {}), + ("make it look like macos", "preset:macos-like", {}), + ("macos look", "preset:macos-like", {}), + ("macos-like", "preset:macos-like", {}), + ("apple style desktop", "preset:macos-like", {}), + # explain (settings/explain.py — #120 "why is my dock blurry") + ("why is", "explain", {}), + ("why does", "explain", {}), + ("why is my", "explain", {}), + ("explain why", "explain", {}), + ("what controls", "explain", {}), + ("what setting controls", "explain", {}), + ("where does", "explain", {}), + ("explain the", "explain", {}), + # undo / history (settings/history.py + cortex/nlhistory.py) + ("undo the last change", "undo", {}), + ("undo that", "undo", {}), + ("revert my last change", "undo", {}), + ("undo", "undo", {}), + ("revert", "undo", {}), + ("rollback", "undo", {}), + ("restore yesterday", "undo", {}), + ("restore yesterday's theme", "undo", {}), + ("what did i change", "history", {}), + ("show my change history", "history", {}), + ("recent changes", "history", {}), + ("change history", "history", {}), + ("what changed", "history", {}), + # scheme (inert suggestions — parser.py §3.3 step 3) + ("change the accent color", "scheme", {}), + ("change color scheme", "scheme", {}), + ("new theme colors", "scheme", {}), + ("different palette", "scheme", {}), + ("set the accent", "scheme", {}), + # wallpaper (inert suggestions) + ("change my wallpaper", "wallpaper", {}), + ("new background image", "wallpaper", {}), + ("set wallpaper", "wallpaper", {}), + ("random wallpaper", "wallpaper", {}), + # diagnostics (Layer 1) + ("something is broken", "diagnose", {}), + ("it crashed", "diagnose", {}), + ("error message", "diagnose", {}), + ("not working", "diagnose", {}), + ("fails to start", "diagnose", {}), + ("troubleshoot", "diagnose", {}), + ("shell will not start", "diagnose", {}), + ("bar disappeared", "diagnose", {}), + # retrieval (Layer 2) + ("how do i", "search", {}), + ("where is the docs", "search", {}), + ("documentation for", "search", {}), + ("find in docs", "search", {}), + ("look up", "search", {}), + # brain (lean intelligence layer) + ("plan my day", "brain", {}), + ("what should i do first", "brain", {}), + ("plan my tasks", "brain", {}), + ("how long will it take", "brain", {}), + ("remind me later", "brain", {}), + ("my focus", "brain", {}), + ("organize my notes", "brain", {}), + # issue drafting (Layer 4) + ("file an issue", "issue", {}), + ("draft a bug report", "issue", {}), + ("report a bug", "issue", {}), + ("open an issue", "issue", {}), +) + + +def surface_rows() -> List[Row]: + return [Row(text, surface, cues) for text, surface, cues in _SURFACE_ROWS] + + +def all_rows() -> List[Row]: + """Every synthetic row: tool rows (registry order) then surface rows. + Deterministic order is part of the contract — row order feeds + co-occurrence window construction in vectorize.py.""" + rows: List[Row] = [] + for spec in TOOL_SPECS: + rows.extend(_rows_for_tool(spec)) + rows.extend(surface_rows()) + return rows + + +def surface_labels() -> List[str]: + """All routable surfaces in deterministic order (for logging/reporting).""" + labels: List[str] = [spec.name for spec in TOOL_SPECS] + labels.extend([ + "preset:compact", "preset:minimal", "preset:gaming", + "preset:battery-saver", "preset:macos-like", + "explain", "undo", "history", "scheme", "wallpaper", + "diagnose", "search", "brain", "issue", + ]) + return labels + + +def rows_by_surface() -> Dict[str, List[Row]]: + """{surface: rows} grouping (the router's supervised signal).""" + out: Dict[str, List[Row]] = {} + for row in all_rows(): + out.setdefault(row.surface, []).append(row) + return out diff --git a/plugins/caelestia-assistant/assistant/core/crf_tagger.py b/plugins/caelestia-assistant/assistant/core/crf_tagger.py new file mode 100644 index 0000000..b8e43bd --- /dev/null +++ b/plugins/caelestia-assistant/assistant/core/crf_tagger.py @@ -0,0 +1,374 @@ +"""cortex.crf_tagger — a linear-chain CRF slot tagger, the +calibrated-probability ALTERNATIVE to the averaged perceptron +(exponential-build-4 F). + +Lafferty, McCallum & Pereira 2001, "Conditional Random Fields: +Probabilistic Models for Segmenting and Labeling Sequence Data", +ICML — the linear-chain CRF: one log-linear distribution over whole +tag sequences conditioned on the tokens, + + P(y | x) ∝ exp( Σ_i w[y_i]·f(x, i) + Σ_i T[y_{i-1}, y_i] ), + +with the same feature style and tag set as cortex/slot_tagger.py's +perceptron (the tagger is distilled from the same grammar-supervision +contract; this module shares its tokenizer, shape feature, char +n-grams and TAGS — nothing about the existing tagger is modified). + +Training is the paper's: maximum conditional likelihood via +forward-backward — the gradient is (empirical feature counts) minus +(expectation of feature counts under P(y|x)), the expectations coming +from the forward-backward recursions in log space (log-sum-exp; no +underflow, no scaling tricks to explain away). Decoding is Viterbi +over the same potentials. + +WHY AN ALTERNATIVE AND NOT A REPLACEMENT: the perceptron's confidence +is a margin pushed through a pinned sigmoid — an invented calibration +the module itself documents. A CRF's marginals are probabilities by +construction (they come from a normalized conditional distribution), +which is the right shape for the conformal gate that sits downstream. +Whether that shape is ACTUALLY better on this repo's small supervised +history is an empirical claim this build MEASURES, not asserts — +``calibration_comparison`` trains both on the same rows and reports +held-out Brier and log-loss side by side, winner and all. Ship it +selectable (`tag_gated_crf`), conformal-gated exactly like the +existing tagger, grammar-fallback identical. + +Deterministic: no RNG anywhere (batch gradient, fixed iterations, +sorted feature order). Pure stdlib; state is plain dicts. +""" +from __future__ import annotations + +import math +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple + +from .conformal import ConformalCalibrator +from .slot_tagger import (TAGS, SlotTagger, _shape, + _spans_of, _tokenize_with_offsets, + char_ngrams) + +__all__ = ["CRFTagger", "tag_gated_crf", "calibration_comparison"] + +_EPOCHS = 8 +_RATE = 0.5 +_UNK_TRANS = "" + + +class CRFTagger: + """The linear-chain CRF over the slot tags.""" + + def __init__(self, data: Optional[Dict[str, Any]] = None) -> None: + data = data if isinstance(data, dict) else {} + self.weights: Dict[str, Dict[str, float]] = { + tag: {} for tag in TAGS} + self.transitions: Dict[str, Dict[str, float]] = { + prev: {tag: 0.0 for tag in TAGS} for prev in [_UNK_TRANS] + list(TAGS)} + self.trained_examples = int(data.get("trained_examples", 0)) + + # -- features (shared with the perceptron) ---------------------------- + + @staticmethod + def _features(tokens: List[str], i: int) -> List[str]: + w = tokens[i].lower() + feats = [ + f"w={w}", + f"shape={_shape(tokens[i])}", + f"p1={w[:2]}", f"p2={w[:3]}", + f"s1={w[-2:]}", f"s2={w[-3:]}", + f"prev={tokens[i - 1].lower() if i else ''}", + f"next={tokens[i + 1].lower() if i + 1 < len(tokens) else ''}", + ] + for g in char_ngrams(w, 3): + feats.append(f"ng={g}") + return feats + + # -- potentials --------------------------------------------------------- + + def _emit(self, tag: str, feats: Sequence[str]) -> float: + table = self.weights[tag] + return sum(table.get(f, 0.0) for f in feats) + + def _trans(self, prev: str, tag: str) -> float: + return self.transitions.get(prev, {}).get(tag, 0.0) + + @staticmethod + def _lse(values: Sequence[float]) -> float: + if not values: + return float("-inf") + m = max(values) + if m == float("-inf"): + return m + return m + math.log(sum(math.exp(v - m) for v in values)) + + # -- forward-backward (log space) --------------------------------------- + + def _forward(self, token_feats: List[List[str]]) -> List[Dict[str, float]]: + n = len(token_feats) + alpha: List[Dict[str, float]] = [] + first = {tag: self._trans(_UNK_TRANS, tag) + + self._emit(tag, token_feats[0]) for tag in TAGS} + alpha.append(first) + for i in range(1, n): + row = {} + for tag in TAGS: + emit = self._emit(tag, token_feats[i]) + row[tag] = self._lse( + [alpha[i - 1][prev] + self._trans(prev, tag) + for prev in TAGS]) + emit + alpha.append(row) + return alpha + + def _backward(self, token_feats: List[List[str]]) -> List[Dict[str, float]]: + n = len(token_feats) + beta: List[Dict[str, float]] = [dict() for _ in range(n)] + for tag in TAGS: + beta[n - 1][tag] = 0.0 + for i in range(n - 2, -1, -1): + for prev in TAGS: + beta[i][prev] = self._lse( + [self._trans(prev, tag) + + self._emit(tag, token_feats[i + 1]) + + beta[i + 1][tag] for tag in TAGS]) + return beta + + def _log_z(self, alpha: List[Dict[str, float]]) -> float: + return self._lse(list(alpha[-1].values())) + + # -- training ------------------------------------------------------------- + + def train(self, rows: Sequence[Tuple[str, List[str]]], + epochs: int = _EPOCHS) -> Dict[str, Any]: + """Batch conditional-likelihood training (forward-backward + expectations vs empirical counts), fixed epochs, fixed rate. + Rows are (text, gold BIO tags) — the same supervision shape + the perceptron trains from.""" + prepared: List[Tuple[List[List[str]], List[str]]] = [] + for text, tags in rows: + tokens = [t for t, _s, _e in _tokenize_with_offsets(text)] + if len(tokens) != len(tags) or not tokens: + continue + prepared.append(([self._features(tokens, i) + for i in range(len(tokens))], list(tags))) + if not prepared: + raise ValueError("no usable rows: supervision matches no " + "tokenized text (nothing is faked)") + for _epoch in range(epochs): + grad_w: Dict[str, Dict[str, float]] = { + tag: {} for tag in TAGS} + grad_t: Dict[str, Dict[str, float]] = { + prev: {tag: 0.0 for tag in TAGS} + for prev in [_UNK_TRANS] + list(TAGS)} + for token_feats, tags in prepared: + n = len(token_feats) + alpha = self._forward(token_feats) + beta = self._backward(token_feats) + log_z = self._log_z(alpha) + # gradient step: empirical minus expected, per position + for i in range(n): + y = tags[i] + prev_tag = _UNK_TRANS if i == 0 else tags[i - 1] + denom = self._lse([alpha[i][t] + beta[i][t] + for t in TAGS]) + for tag in TAGS: + marginal = math.exp(alpha[i][tag] + beta[i][tag] + - denom) + # emission: empirical (y == tag) minus marginal + coef = (1.0 if tag == y else 0.0) - marginal + if coef == 0.0: + continue + table = grad_w[tag] + for f in token_feats[i]: + table[f] = table.get(f, 0.0) + coef + # transition: P(y_{i-1} = prev, y_i = tag) + if i > 0: + prev_y = tags[i - 1] + tcoef = ((1.0 if tag == y and prev_tag == prev_y + else 0.0) + - math.exp(alpha[i - 1][prev_tag] + + self._trans(prev_tag, tag) + + self._emit(tag, token_feats[i]) + + beta[i][tag] + - log_z)) + grad_t[prev_tag][tag] += tcoef + else: + tcoef = ((1.0 if tag == y else 0.0) + - math.exp(self._trans(_UNK_TRANS, tag) + + self._emit(tag, token_feats[i]) + + beta[i][tag] - log_z)) + grad_t[_UNK_TRANS][tag] += tcoef + # apply + for tag in TAGS: + table = self.weights[tag] + for f, g in grad_w[tag].items(): + table[f] = table.get(f, 0.0) + _RATE * g / len(prepared) + for prev in grad_t: + for tag, g in grad_t[prev].items(): + if g: + self.transitions[prev][tag] += \ + _RATE * g / len(prepared) + self.trained_examples += len(prepared) + return {"rows": len(prepared), "epochs": epochs} + + # -- persistence --------------------------------------------------------- + + def to_dict(self) -> Dict[str, Any]: + return {"weights": {t: dict(table) for t, table in self.weights.items()}, + "transitions": {p: dict(row) for p, row in + self.transitions.items()}, + "trained_examples": self.trained_examples} + + @classmethod + def from_dict(cls, data: Optional[Dict[str, Any]]) -> "CRFTagger": + tagger = cls(data) + return tagger + + # -- decoding + marginals ----------------------------------------------- + + def tag(self, text: str) -> Dict[str, Any]: + """Viterbi decode + per-token marginals from forward-backward. + The confidence is the mean marginal of the decoded tags — a + probability by construction (normalized conditional), which is + the point of the CRF over the perceptron's margin heuristic.""" + tokens = [t for t, _s, _e in _tokenize_with_offsets(text)] + if not tokens: + return {"spans": {}, "tokens": [], "confidence": None, + "marginals": []} + token_feats = [self._features(tokens, i) for i in range(len(tokens))] + # Viterbi + n = len(tokens) + chart: List[Dict[str, Tuple[float, Optional[str]]]] = [] + first = {tag: (self._trans(_UNK_TRANS, tag) + + self._emit(tag, token_feats[0]), None) + for tag in TAGS} + chart.append(first) + for i in range(1, n): + row = {} + for tag in TAGS: + emit = self._emit(tag, token_feats[i]) + best_prev = max( + TAGS, + key=lambda prev: (chart[i - 1][prev][0] + + self._trans(prev, tag), prev)) + score = (chart[i - 1][best_prev][0] + + self._trans(best_prev, tag) + emit) + row[tag] = (score, best_prev) + chart.append(row) + final = max(TAGS, key=lambda t: (chart[n - 1][t][0], t)) + tags: List[str] = [final] + for i in range(n - 1, 0, -1): + tags.append(chart[i][tags[-1]][1] or _UNK_TRANS) + tags.reverse() + # marginals + alpha = self._forward(token_feats) + beta = self._backward(token_feats) + log_z = self._log_z(alpha) + marginals = [] + for i in range(n): + denom = self._lse([alpha[i][t] + beta[i][t] for t in TAGS]) + marginals.append({tag: math.exp(alpha[i][tag] + beta[i][tag] + - denom) for tag in TAGS}) + confidence = sum(marginals[i][tags[i]] for i in range(n)) / n + spans = _spans_of(tags, tokens) + return {"tokens": tokens, "tags": tags, "spans": spans, + "confidence": round(confidence, 4), + "marginals": [[round(m[tag], 4) for tag in TAGS] + for m in marginals], + "model": "linear-chain CRF (Lafferty et al. 2001)"} + + +def tag_gated_crf(text: str, tagger: CRFTagger, + calibrator: Optional[ConformalCalibrator] = None, + noun_matcher: Optional[Callable[ + [str], Sequence[str]]] = None) -> Dict[str, Any]: + """The CRF twin of slot_tagger.tag_gated: identical gate shape + (untrained -> grammar fallback; conformal verdict; else answer), + identical grammar fallback, so the two taggers are SELECTABLE with + the same contract and neither bypasses the conformal gate.""" + if tagger.trained_examples == 0 or not any( + tagger.weights[t] for t in TAGS): + return _grammar_fallback(text, "CRF tagger untrained", + calibrator=calibrator, + noun_matcher=noun_matcher) + result = tagger.tag(text) + confidence = result.get("confidence") + if confidence is None or not result["spans"]: + return _grammar_fallback(text, "CRF tagger found no slot structure", + calibrator=calibrator, + noun_matcher=noun_matcher) + verdict = (calibrator.verdict(confidence) + if calibrator is not None and calibrator.scores + else {"covered": None, + "reason": ("insufficient calibration data — no " + "distribution-free claim available")}) + if verdict.get("covered") is not True: + return _grammar_fallback(text, str(verdict.get("reason")), + calibrator=calibrator, + noun_matcher=noun_matcher) + result.update({"used": "crf-tagger", "conformal": verdict.get("reason")}) + return result + + +def _grammar_fallback(text: str, reason: str, + calibrator: Optional[ConformalCalibrator] = None, + noun_matcher: Optional[Callable[ + [str], Sequence[str]]] = None) -> Dict[str, Any]: + from assistant.capabilities.settings import slots as _slots + slots = _slots.extract(text) + targets = list(noun_matcher(text) or []) if noun_matcher else [] + return {"used": "grammar-fallback", "reason": reason, + "slots": slots, "targets": targets} + + +def calibration_comparison(rows: Sequence[Tuple[str, List[str]]], + holdout: int = 4) -> Dict[str, Any]: + """The empirical claim the selectable contract demands: SAME + supervision, BOTH taggers trained, held-out rows scored by Brier + and log-loss of each model's confidence against the binary + 'decoded BIO tags == gold tags' outcome. Reports both and names + the measured winner — or says the data is too thin to claim + anything (fewer than 2*holdout rows). Deterministic split: last + ``holdout`` rows are held out.""" + if len(rows) < 2 * holdout: + return {"n": len(rows), "crf": None, "perceptron": None, + "note": "too few labeled rows to compare calibration " + "honestly — bring more supervised history"} + train = list(rows[:-holdout]) + test = list(rows[-holdout:]) + crf = CRFTagger() + crf.train(train) + perceptron = SlotTagger() + perceptron.train(train) + + def brier_nll(model_confidences: Sequence[float]) -> Tuple[float, float]: + errors = [(c - 1.0) ** 2 for c in model_confidences] + nlls = [] + for c in model_confidences: + c = min(max(c, 1e-6), 1.0 - 1e-6) + nlls.append(-math.log(1.0 - c)) # outcome 0 (exact match) + return round(sum(errors) / len(errors), 4), round( + sum(nlls) / len(nlls), 4) + + crf_conf: List[float] = [] + per_conf: List[float] = [] + outcomes: List[int] = [] + for text, gold in test: + crf_result = crf.tag(text) + per_result = perceptron.tag(text) + crf_correct = 1 if crf_result.get("tags") == gold else 0 + per_correct = 1 if per_result.get("tags") == gold else 0 + outcomes.extend([crf_correct, per_correct]) + crf_conf.append(crf_result.get("confidence") or 0.0) + per_conf.append(per_result.get("confidence") or 0.0) + crf_brier, crf_nll = brier_nll(crf_conf) + per_brier, per_nll = brier_nll(per_conf) + winner = ("crf" if crf_brier < per_brier else + "perceptron" if per_brier < crf_brier else "tie") + return { + "n_train": len(train), "n_holdout": len(test), + "crf": {"brier": crf_brier, "logloss_vs_exact_match": crf_nll}, + "perceptron": {"brier": per_brier, + "logloss_vs_exact_match": per_nll}, + "winner": winner, + "note": "held-out calibration comparison on THIS supervision — " + "the winner is measured, not asserted, and may flip as " + "history grows; both remain selectable", + } diff --git a/plugins/caelestia-assistant/assistant/core/dp.py b/plugins/caelestia-assistant/assistant/core/dp.py new file mode 100644 index 0000000..5b16d5f --- /dev/null +++ b/plugins/caelestia-assistant/assistant/core/dp.py @@ -0,0 +1,328 @@ +"""cortex.dp — Laplace-mechanism differential privacy for the +lexicon-diff export path (exponential-build 3, item B4). + +The community lexicon-diff export (cortex/lexicon_diff.py) shares a +plain-text, reviewable list of ``phrase -> tool`` mappings with exact +per-phrase evidence (``n=4, p=0.86`` occurrence counts and mean route +probabilities). A community aggregator collecting many users' diffs +could reconstruct one contributor's raw behavior from those exact +counts. This module is the noising pass over the export artifact: an +OPT-IN transformation applied between export_rows() and sharing. + +Mechanism: the Laplace mechanism — Dwork, McSherry, Nissim & Smith +2006, "Calibrating Noise to Sensitivity in Private Data Analysis", +TCC 2006 (the mechanism and the sensitivity calibration), composed +per Dwork & Roth 2014, "The Algorithmic Foundations of Differential +Privacy" (the composition property cited below). Each noised value is +value + Laplace(0, b) with scale b = sensitivity / epsilon, sampled +EXACTLY by the inverse CDF from one uniform draw of the injected rng: + + u = rng.random() # one uniform in [0, 1) + noise = -b * sign(u - 0.5) * ln(1 - 2*|u - 0.5|) + +which is the standard inverse of the Laplace CDF (F(x) = 0.5*exp(x/b) +for x <= 0, 1 - 0.5*exp(-x/b) for x > 0). Deterministic given the rng; +one uniform draw per call. The tail u = 0.0 exactly (possible, measure +~2^-53) would make ln(0) undefined; the tail is floored at 1e-15 so +the noise is finite (~ -34.5b) — a documented tail treatment of the +mechanism's own sampling edge, never a clamp of user data. + +DEFAULT EPSILON = 1.0, PER EXPORT. Why: the noised quantities are the +per-row evidence values (n and p), and per single release one user's +phrase-level contributions are bounded by the export path's own cap — +lexicon_diff.MAX_PAIRS = 200 phrase rows per export (the newest-200 +cap in export_rows), drawn from a learner example log that is itself +capped (cortex/learn.py MAX_EXAMPLES = 500). Against the phrase-event +neighboring relation (the contributor's log differing by one routed +example), a single event changes exactly one row's n by 1 and its p by +at most 1 (worst case n=1: one event swings a [0,1] mean end to end), +so the per-row sensitivities are N_SENSITIVITY = 1 and +P_SENSITIVITY = 1 (the p bound is loose and the price is visible: at +epsilon=1 the noised p is clipped often — every clip is counted and +reported, never silent). The 200-row export cap is what bounds how +much phrase evidence one release can carry at all, which is why +"epsilon per export" is the unit a contributor reasons about: you +share one diff, you spend one epsilon. + +COMPOSITION (Dwork & Roth 2014, the composition property): k +sequential exports compose to roughly k * epsilon total. The export +path is user-initiated and manual — ``cortex lexicon export --dp`` — +so the practical bound is simply how often YOU export. Say it plainly: +export once a month at epsilon=1 and a year of sharing is ~12 epsilon; +share hourly and the guarantee is gone. Nothing here enforces a +budget; the number is stated for the human who owns the decision. + +HONEST BOUNDARY — this is NOISED-EVIDENCE DP, not full row-level DP: +pure epsilon-DP for a row's PRESENCE would require randomized +subsampling of rows, which is NOT the default — presence is exact; +only the counts and rates are noised. A phrase you typed appears in +the export exactly as often as before; what changes is that its n and +p are inexact. The opt-in ``presence_keep`` parameter adds honest +randomized row subsampling (each row independently kept with the given +probability, dropped rows counted): that AMPLIFIES the value-level +guarantee, but a KEPT row is still exactly present, so it is not by +itself a row-presence epsilon-DP claim and is not labeled as one. + +REPRODUCIBLE-NOISE TRADEOFF: by default the seed is derived +deterministically from the diff's content id (lexicon_diff.diff_id), +so noising the same diff twice yields byte-identical output — the +artifact is reviewable and re-derivable. The cost, stated plainly: +reproducible noise is NOT independent across exports. Two releases of +the SAME diff at epsilon each are not two independent epsilon-DP +releases (the noise repeats, so the second release adds no fresh +leakage but also no fresh randomness); the composition accounting +above assumes DIFFERENT exports. Pass an explicit seed when you want +fresh, independent noise. + +The module is PURE: it writes nothing (the CLI prints), takes rows or +the rendered diff text, and returns the noised artifact plus a report +of every floor and clip. Re-noising an already-noised diff (one +carrying the provenance marker) is REJECTED — composing Laplace noise +at the same stated epsilon would misreport the total. Deterministic: +same (diff, epsilon, seed) -> byte-identical output. +""" +from __future__ import annotations + +import math +import random +from typing import Any, Dict, List, Optional, Sequence, Tuple, Union + +from . import lexicon_diff +from .lexicon_diff import _DATE_RE, _ROW_RE + +__all__ = ["DEFAULT_EPSILON", "N_SENSITIVITY", "P_SENSITIVITY", + "laplace_noise", "noise_diff"] + +DEFAULT_EPSILON = 1.0 +# per-row sensitivities under the phrase-event neighboring relation +# (see the module docstring's epsilon rationale) +N_SENSITIVITY = 1.0 +P_SENSITIVITY = 1.0 + +# the inverse-CDF tail floor: u == 0.0 exactly (measure ~2^-53) would +# make ln(1 - 2|u - 0.5|) = ln(0) undefined; floor the argument so the +# draw stays finite (~ -34.5b) instead of -inf +_TAIL_FLOOR = 1e-15 + +GUARANTEE = ("noised-evidence DP: per-row n/p are Laplace-noised " + "(Dwork et al. 2006); row PRESENCE is exact unless " + "presence_keep is set — not full row-level DP") + + +def laplace_noise(value: float, sensitivity: float, epsilon: float, + rng: random.Random) -> float: + """value + Laplace(0, b) noise with b = sensitivity / epsilon, + sampled exactly by the inverse CDF from ONE uniform draw of + ``rng`` (formula in the module docstring). Deterministic given the + rng. sensitivity <= 0 and epsilon <= 0 are REJECTED (a noise scale + is not definable from them — refused, never guessed).""" + sensitivity = float(sensitivity) + epsilon = float(epsilon) + if sensitivity <= 0.0: + raise ValueError(f"sensitivity must be > 0 (got {sensitivity})") + if epsilon <= 0.0: + raise ValueError(f"epsilon must be > 0 (got {epsilon})") + b = sensitivity / epsilon + u = float(rng.random()) + offset = u - 0.5 + if offset > 0.0: + sign = 1.0 + elif offset < 0.0: + sign = -1.0 + else: + sign = 0.0 # u == 0.5 exactly: the median, noise exactly 0 + magnitude = 1.0 - 2.0 * abs(offset) + if magnitude < _TAIL_FLOOR: + magnitude = _TAIL_FLOOR + return float(value) - b * sign * math.log(magnitude) + + +def _rows_from_text(text: str) -> Tuple[List[Dict[str, Any]], str]: + """Parse the rendered diff back into rows using lexicon_diff's own + row regex (the ONE row-format implementation — reused, not + duplicated). No registry validation here: the input is the + exporter's own artifact and this pass only transforms values; the + importer's parse() still validates tools at import time. Returns + (rows, date). Unparseable non-comment lines are REJECTED (the + repo rule: out-of-range is refused, never guessed).""" + rows: List[Dict[str, Any]] = [] + date = "" + for lineno, line in enumerate(text.splitlines(), start=1): + stripped = line.strip() + if not stripped or stripped.startswith("#"): + continue + if stripped == lexicon_diff.DIFF_HEADER \ + or stripped.startswith(lexicon_diff.DIFF_HEADER): + m = _DATE_RE.match(stripped[len(lexicon_diff.DIFF_HEADER):].strip()) + if m and not date: + date = m.group(1) + continue + m = _ROW_RE.match(stripped) + if not m: + raise ValueError(f"line {lineno}: unparseable diff row, " + f"refused: {stripped[:60]!r}") + rows.append({ + "text": m.group("text").strip(), + "surface": m.group("surface").strip(), + "n": int(m.group("n") or 1), + "p": min(1.0, max(0.0, float(m.group("p") or 0.0))), + "label": 1 if m.group("sign") == "+" else 0, + "dp_epsilon": float(m.group("dp")) if m.group("dp") else None, + }) + return rows, date + + +def _marker(epsilon: float) -> str: + return f"(dp: epsilon={float(epsilon)})" + + +def noise_diff(diff: Union[str, Sequence[Dict[str, Any]]], + epsilon: float = DEFAULT_EPSILON, + seed: Optional[int] = None, + min_count_floor: bool = True, + date: str = "", + presence_keep: Optional[float] = None) -> Dict[str, Any]: + """Noise one lexicon-diff export artifact (Laplace mechanism). + + ``diff``: the rendered diff TEXT or the export row dicts. An + input already carrying a dp provenance marker is REJECTED — + re-noising would compose epsilon while claiming one epsilon. + ``epsilon``: the per-export privacy budget (> 0, else ValueError). + ``seed``: None (default) derives the seed deterministically from + the diff's content id (diff_id) — reproducible noise, tradeoff + stated in the module docstring; an int gives fresh independent + noise. ``min_count_floor`` (default True): negative noised counts + are floored at zero AND counted in the report; False keeps the raw + negative value (mechanism-audit mode — the artifact it renders + will not re-parse, which lexicon_diff.parse reports as warnings, + the existing honest-degradation path). ``presence_keep``: None + (default) keeps every row (presence exact); a float in (0, 1] + keeps each row independently with that probability (randomized + row subsampling — amplification, not a row-presence epsilon-DP + claim; dropped rows counted). + + Per row, in input order, the rng draws are fixed-order: the + presence draw first (when enabled), then n, then p. Same (diff, + epsilon, seed) -> byte-identical output. Returns the noised + artifact {"text", "rows", counts, guarantee label, notes}; writes + nothing — the caller prints.""" + epsilon = float(epsilon) + if epsilon <= 0.0: + raise ValueError(f"epsilon must be > 0 (got {epsilon})") + if presence_keep is not None: + presence_keep = float(presence_keep) + if not 0.0 < presence_keep <= 1.0: + raise ValueError("presence_keep must be within (0, 1] " + f"(got {presence_keep})") + + # normalize input to rows (reusing the ONE row-format regex) + if isinstance(diff, str): + rows, parsed_date = _rows_from_text(diff) + if not date: + date = parsed_date + else: + rows = [dict(r) for r in diff] + if not rows: + raise ValueError("no rows to noise — the export is empty") + for row in rows: + if row.get("dp_epsilon") is not None: + raise ValueError( + "this diff is already noised (a dp provenance marker is " + "present) — re-noising would compose epsilon while " + "claiming one epsilon; export the exact diff and noise once") + + # the seed: derived from the content id (reproducible) or explicit + if seed is None: + seed = int(lexicon_diff.diff_id(rows), 16) + else: + try: + seed = int(seed) + except (TypeError, ValueError): + raise ValueError(f"seed must be an integer or None (got {seed!r})") + rng = random.Random(seed) + + marker = _marker(epsilon) + out_rows: List[Dict[str, Any]] = [] + n_floored = n_negative_raw = 0 + p_clip_lo = p_clip_hi = 0 + dropped = 0 + for row in rows: + if presence_keep is not None and rng.random() >= presence_keep: + dropped += 1 + continue + # n: Laplace noise, nearest integer (halves up), floored at + # zero when min_count_floor — every floor COUNTED, never silent + noised_n = laplace_noise(int(row.get("n", 1)), N_SENSITIVITY, + epsilon, rng) + n_int = int(math.floor(noised_n + 0.5)) + if n_int < 0: + if min_count_floor: + n_int = 0 + n_floored += 1 + else: + n_negative_raw += 1 + # p: Laplace noise, clipped to the valid [0, 1] RANGE and the + # clip COUNTED and reported (the DP-output convention: the + # noise is honest about its own postprocessing) + noised_p = laplace_noise(float(row.get("p", 0.0)), P_SENSITIVITY, + epsilon, rng) + if noised_p < 0.0: + noised_p = 0.0 + p_clip_lo += 1 + elif noised_p > 1.0: + noised_p = 1.0 + p_clip_hi += 1 + out_rows.append({ + "text": str(row.get("text", "")), + "surface": str(row.get("surface", "")), + "n": n_int, + "p": round(noised_p, 2), + "label": 1 if int(row.get("label", 1)) == 1 else 0, + "dp_epsilon": epsilon, + }) + + # the artifact: same canonical header, one provenance comment, and + # every row carrying its marker — a reviewer can never mistake a + # noised diff for an exact one + lines = [f"{lexicon_diff.DIFF_HEADER} ({date})" if date + else lexicon_diff.DIFF_HEADER] + lines.append(f"# {marker.strip()} — counts and rates are Laplace-" + "noised (Dwork et al. 2006); presence is exact; " + "see cortex/dp.py") + for row in out_rows: + sign = "+" if row["label"] == 1 else "-" + lines.append(f"{sign}{row['text']} -> {row['surface']} " + f"(n={row['n']}, p={row['p']:.2f}) {marker}") + + return { + "text": "\n".join(lines) + "\n", + "rows": out_rows, + "epsilon": epsilon, + "seed": seed, + "rows_in": len(rows), + "rows_out": len(out_rows), + "rows_dropped": dropped, + "n_floored_at_zero": n_floored, + "n_negative_raw": n_negative_raw, + "p_clipped": p_clip_lo + p_clip_hi, + "p_clipped_low": p_clip_lo, + "p_clipped_high": p_clip_hi, + "guarantee": GUARANTEE, + "method": (f"Laplace mechanism (Dwork, McSherry, Nissim & Smith " + f"2006): n and p noised at sensitivity " + f"n={N_SENSITIVITY:g}, p={P_SENSITIVITY:g}, " + f"epsilon={epsilon:g} per export; composition: k " + "sequential exports ~ k*epsilon"), + "notes": [ + GUARANTEE, + "composition: k sequential exports compose to roughly " + "k*epsilon (Dwork & Roth 2014); the export path is " + "user-initiated and manual, so the practical bound is how " + "often you export", + f"seed {seed} " + + ("derived from the diff's content id — reproducible noise, " + "NOT independent across exports of the same content" + if seed == int(lexicon_diff.diff_id(rows), 16) else + "explicitly supplied"), + ], + } diff --git a/plugins/caelestia-assistant/assistant/core/features.py b/plugins/caelestia-assistant/assistant/core/features.py new file mode 100644 index 0000000..729d690 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/core/features.py @@ -0,0 +1,184 @@ +"""assistant.core.features — the per-install capability manifest. + +A static, user-editable config that lists which goal archetypes / surfaces +are enabled on THIS install, so a community deployment can turn off +package-auditing or the DBus surface without a code change. Every new +capability added in this codebase registers itself here. + +Posture (the generative layer's own pattern, applied system-wide): +a capability defaults to ON only when it is read-only and zero-risk — +no process spawning, no write path, no new import surface. Everything +that shells out, writes, or reaches beyond the offline core defaults +OFF and must be flipped by editing this file (never by a natural +language request — the kill-switch stays a file edit, exactly like the +DBus proposal's settings.dbus.enabled rule). + +File: $CAELESTIA_ASSIST_CAPABILITIES if set, else +~/.config/caelestia-assistant/capabilities.json — a JSON object mapping +capability name -> true/false. Unknown keys are ignored (forward +compat); a broken file degrades to defaults with a note, never a crash. + +Read-only module: nothing here writes the manifest; the user owns it. +""" + +from __future__ import annotations + +import json +import os +from pathlib import Path +from typing import Any, Dict + +__all__ = ["DEFAULTS", "capabilities_path", "manifest", "enabled", "render"] + +# The shipped posture. ON = read-only, zero-risk, offline. +# OFF = any new import surface, any process, any write. +DEFAULTS: Dict[str, bool] = { + # -- read-only, zero-risk: on by default ------------------------------ + "fsbrain": True, # filesystem analyses (genius/fsbrain) + "config_hygiene": True, # lint + drift report + consented reconcile + "log_triage": True, # sysintel template mining -> issue drafts + "screenshot_diff": True, # pixel-region hashing between two files + "notification_triage": True, # PURE classification of event records + "lexicon_sharing": True, # cortex lexicon export/import/forget (CLI, + # offline, no network; import is an explicit + # user command with rollback — phase 2.6) + "eval_arena": True, # the measurement arena incl. the + # metamorphic suite (read-only, in-process, + # dev sets only unless --sealed is asked for) + "confusable_clarifier": True, # upgrades the generic ambiguity ask to + # the mined pair's own question (read-only + # text swap over the committed artifact) + "label_fusion": True, # Dawid-Skene vote fusion may demote a + # contested confident route to an ask + # (never promotes; read-only) + "shell_cli_grammar": True, # shellkb: the shell CLIs' typed option + # grammar, induced from upstream file text + # (read-only; nothing executed) + "shell_explain": True, # shellkb: token-by-token command-line + # explanation, read-only glob previews + # (os.scandir), destructive-pattern flags; + # the verdict is always + # SUGGESTED_NOT_EXECUTED + "shell_howto": True, # shellkb: offline how-to answers over a + # self-authored CC0 corpus (BM25 + the + # existing time-expression parser); every + # step SUGGESTED_NOT_EXECUTED + "shell_json_merge": True, # shellkb: structured diff (Myers paths + + # ordered tree-edit distance) and + # three-way merge PROPOSALS for config + # JSON; pure math over caller-supplied + # documents, never a write + "shell_conflicts": True, # shellkb: PubGrub-style dependency + # explanations over a bounded DPLL-style + # search; any installed-version facts + # still come only from the read-only + # package_audit probe (or the caller) + "engine_telemetry": True, # cortex engine coverage/accuracy report + + # opt-in Laplace-DP export (read-only, + # stdout only — exponential-build-3 F3) + "seasonal_patterns": True, # brain: matrix profile + SAX motifs/ + # discords, PELT changepoints, Holt- + # Winters seasonality over caller-passed + # series (pure math, read-only) + "burst_detection": True, # brain: Hawkes self-excitation fit and + # burst detection over caller-passed event + # times; reports correlation, never + # causation (pure math, read-only) + "gp_preferences": True, # brain: Gaussian-process preference + # learning over pairwise answers (Cholesky, + # bounded at 50 items); emits ONE + # registry-validated setter proposal, + # SUGGESTED_NOT_EXECUTED + "user_rules": True, # brain: user-authored event-condition- + # action rules on a Rete network; the + # rules FILE is the opt-in and every + # fired action is a ledger proposal, + # never an applied change + "size_sketches": True, # brain: Space-Saving heavy hitters and + # t-digest quantiles over caller-passed + # sizes; counts are labeled estimates + # with reported max error (pure math) + "nlg_templates": True, # brain: template NLG with discourse + # planning and aggregation over plan + # changes (deterministic; no model) + "extractive_qa": True, # brain: extractive QA over the repo docs + # and caller-supplied notes — BM25 passage + # retrieval, answer-type detection, VERBATIM + # spans with doc/section/line provenance; + # thin evidence says THIN, none says + # NOT_FOUND (no generation, ever) + # -- optional model tier (Group E): OFF, and never on the offline core + "model_reranker": False, # generative: sub-1B loopback reranker over + # the router's OWN candidate list; output + # constrained to candidate names, marked + # MODEL_SUGGESTED, plan/apply gates untouched + # -- surfaces that shell out or extend the import surface: OFF ------ + "package_audit": False, # read-only package-manager query (quarantined) + "dbus_surface": False, # kwriteconfig6/kscreen/powerdevil/KWin scripts + "notification_observation": False, # live DBus notification listening +} + + +def capabilities_path() -> Path: + env = os.environ.get("CAELESTIA_ASSIST_CAPABILITIES") + if env: + return Path(env) + config_home = os.environ.get("XDG_CONFIG_HOME") or \ + str(Path.home() / ".config") + return Path(config_home) / "caelestia-assistant" / "capabilities.json" + + +def manifest() -> Dict[str, Any]: + """The effective manifest: defaults, overridden by the user's file.""" + out: Dict[str, Any] = dict(DEFAULTS) + out["_path"] = str(capabilities_path()) + out["_source"] = "defaults" + try: + user = json.loads(capabilities_path().read_text(encoding="utf-8")) + except (OSError, ValueError): + return out # missing or broken file: defaults, honestly + if not isinstance(user, dict): + out["_note"] = "user manifest is not an object; defaults stand" + return out + for key, value in user.items(): + if key.startswith("_"): + continue + if isinstance(value, bool): + out[key] = value + out["_source"] = "defaults+user" + return out + + +def enabled(name: str) -> bool: + """Is this capability enabled on this install? (Default posture when + the user has said nothing — the safe direction.)""" + return bool(manifest().get(name, DEFAULTS.get(name, False))) + + +def render() -> str: + """The `caelestia-assist capabilities` card.""" + current = manifest() + lines = [ + "caelestia-assist — capability manifest", + f" file: {current['_path']} (edit it to flip a switch; NL requests " + "cannot)", + "", + ] + for name in sorted(DEFAULTS): + state = "on " if current.get(name) else "off" + lines.append(f" [{state}] {name}") + # The DBus surface's command catalog: the reviewable one-line-per- + # command listing, shown when the capability is on (the operator + # can see exactly what can spawn without reading the module). + if current.get("dbus_surface"): + try: + from assistant.capabilities.settings.dbus_surface import catalog_lines + lines.append("") + lines.extend(" " + line for line in catalog_lines()) + except Exception: + pass # the catalog listing is best-effort, never fatal + if current.get("_source") != "defaults+user": + lines.append("") + lines.append(" (defaults in effect — the user file has not " + "overridden anything)") + return "\n".join(lines) diff --git a/plugins/caelestia-assistant/assistant/core/fts_store.py b/plugins/caelestia-assistant/assistant/core/fts_store.py new file mode 100644 index 0000000..bc44c1f --- /dev/null +++ b/plugins/caelestia-assistant/assistant/core/fts_store.py @@ -0,0 +1,74 @@ +"""FTS5-backed index with an honest unavailability result. + +sqlite3 ships in stdlib; the FTS5 COMPILE-TIME FEATURE may be absent +from some builds. available() probes it once. WAL journaling is set on +every connection. This is the storage seam for the find-anything index +(Phase 4.8): nothing in the hot path depends on it, so the pure-Python +BM25 remains the default and this stays an optional accelerator. +""" +from __future__ import annotations + +import sqlite3 +from pathlib import Path +from typing import Dict, Iterable, List, Tuple + +__all__ = ["fts5_available", "connect_wal", "FTS5Index"] + + +def fts5_available() -> bool: + try: + conn = sqlite3.connect(":memory:") + try: + conn.execute("CREATE VIRTUAL TABLE t USING fts5(x)") + return True + finally: + conn.close() + except (sqlite3.Error, AttributeError): + return False + + +def connect_wal(path: Path) -> sqlite3.Connection: + """sqlite connection with WAL journaling (write-tolerant readers).""" + conn = sqlite3.connect(str(path)) + conn.execute("PRAGMA journal_mode=WAL") + return conn + + +class FTS5Index: + """Document index over FTS5. Every method returns an honest dict; + when FTS5 is unavailable the index reports it instead of failing.""" + + def __init__(self, path=None): + self.path = str(path) if path else ":memory:" + self.ok = fts5_available() + self.conn = connect_wal(self.path) if self.ok else None + if self.ok: + self.conn.execute( + "CREATE VIRTUAL TABLE IF NOT EXISTS docs USING fts5(" + "doc_id UNINDEXED, title, body)") + + def index(self, docs: Iterable[Tuple[str, str, str]]) -> Dict: + """docs: (doc_id, title, body) triples.""" + if not self.ok: + return {"ok": False, "reason": "FTS5 unavailable in this sqlite build"} + self.conn.executemany( + "INSERT INTO docs(doc_id, title, body) VALUES (?,?,?)", list(docs)) + self.conn.commit() + return {"ok": True} + + def search(self, query: str, limit: int = 10) -> List[Dict]: + if not self.ok: + return [] + # the FTS5 syntax guard: a malformed query is an empty result, + # never a crash + try: + rows = self.conn.execute( + "SELECT doc_id, title, bm25(docs) FROM docs WHERE docs " + "MATCH ? ORDER BY bm25(docs) LIMIT ?", (query, limit)).fetchall() + except sqlite3.Error: + return [] + return [{"doc_id": r[0], "title": r[1], "score": r[2]} for r in rows] + + def close(self): + if self.conn is not None: + self.conn.close() diff --git a/plugins/caelestia-assistant/assistant/core/guard.py b/plugins/caelestia-assistant/assistant/core/guard.py new file mode 100644 index 0000000..f804b85 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/core/guard.py @@ -0,0 +1,183 @@ +"""cortex.guard — the post-ranking evidence guard (F3, exponential-build-5). + +The router's four signals (lexical, semantic, fuzzy, noun) are blended +into one score, and the F2 type gate constrains candidate KINDS. Both +are score-level mechanisms. This module adds the two STRUCTURAL checks +that a blended score cannot express, each citing its evidence and each +leaving a note on the routed candidate. Pure functions, no I/O, fully +deterministic — the same ranking in, the same ranking out. + +G1 — specific addressing displaces a non-tool top. + + Full name-atom coverage (every atom of a tool's own name present in + the request) is SPECIFIC addressing by the router's own definition; + the coverage floor comment already states it "outranks any generic + lexical overlap a sibling tool can muster". When the top candidate + is a PRESET or a coarse SURFACE (kinds whose documents legitimately + collect many topics) and a tool with full coverage sits just below + it, the blended score has let generic document overlap outrank the + request's own explicit naming — "show the battery in the performance + panel" names setPerformanceShowBattery; the battery-saver preset + merely contains the word "battery". G1 swaps them. Margin-bound: + the tool must be within ``g1_margin`` of the top, so a preset the + user clearly invoked (a much larger gap) is never displaced. + +G2 — a coarse surface matched only as a prepositional object yields to +a tool matching the rest of the request. + + "keep more notifications in history" is a request ABOUT + notifications; "history" appears only inside the prepositional + phrase "in history". The coarse history surface wins on that single + token. When EVERY occurrence of the top surface's own name token(s) + sits immediately after a preposition, the surface's evidence is + syntactically incidental, and the best tool that matches the REST + of the request (within ``g2_margin``) is promoted. Preference among + qualifying tools is by (matched distinct content tokens, score) — + the tool that actually addresses more of the request wins, score + breaks ties. A surface named outside a prepositional phrase ("show + history") is never touched. + +Both rules only REORDER the already-scored candidate list; they never +invent scores, never touch candidates below the promoted one, and never +fire together (G1 wins; G2 refuses to stack on a G1 swap). +""" + +from __future__ import annotations + +import re +from typing import FrozenSet, List, Mapping, Sequence, Tuple + +__all__ = ["apply", "PREPOSITIONS", "STOPWORD_FLOOR"] + +# The prepositions that mark an incidental (object) mention. Deliberately +# small: a preposition is only evidence when it RELATES two things, and +# these are the relating prepositions of customization requests +# ("notifications in history", "battery in the panel"). +PREPOSITIONS: FrozenSet[str] = frozenset( + {"in", "inside", "within", "on", "at", "from"} +) + +# Content tokens shorter than this are not evidence of addressing +# ("in", "on", "up" are noise; a 2-char atom like "id" is already +# handled upstream by the atom/stopword machinery). +STOPWORD_FLOOR = 3 + +_WORD_RE = re.compile(r"[a-z0-9]+") + + +def _surface_name_tokens(surface: str) -> List[str]: + return [w for w in _WORD_RE.findall(surface.lower()) if w] + + +def _pp_only( + token: str, words: Sequence[str] +) -> bool: + """True when EVERY occurrence of ``token`` in ``words`` is preceded + by a preposition. A token that does not appear at all is NOT + pp-only (the surface matched some other way; G2 refuses to guess).""" + hits = [i for i, w in enumerate(words) if w == token] + if not hits: + return False + return all(i > 0 and words[i - 1] in PREPOSITIONS for i in hits) + + +def _content_stems( + words: Sequence[str], stems: Mapping[str, str], exclude: FrozenSet[str] +) -> FrozenSet[str]: + out = set() + for w in words: + if len(w) < STOPWORD_FLOOR or w in exclude: + continue + s = stems.get(w, w) + if len(s) >= STOPWORD_FLOOR: + out.add(s) + return frozenset(out) + + +def _doc_overlap(key: str, query_stems: FrozenSet[str], doc_stems: Mapping[str, FrozenSet[str]]) -> int: + return len(query_stems & doc_stems.get(key, frozenset())) + + +def apply( + scored: List[Tuple[float, str]], + *, + documents: Mapping[str, Tuple[str, str]], + coverage: Mapping[str, float], + raw_words: Sequence[str], + stems: Mapping[str, str], + doc_stems: Mapping[str, FrozenSet[str]], + min_margin: float = 0.06, + g1_margin: float = 0.10, + g2_margin: float = 0.20, +) -> Tuple[List[Tuple[float, str]], List[str]]: + """Adjust a sorted (score desc) candidate list. Returns the (new + list, evidence notes). Never raises on odd input; an unfiresable + context returns the list unchanged. + + A promoted candidate's score is floored to ``top + min_margin`` — + the same discipline as the router's noun/coverage floors: the + structural rule asserts the winner, and the score list must stay + descending (rank 1 = max score) for the margin/softmax verdicts to + stay coherent. The note on the top candidate records that a guard, + not the blended score, produced the ordering.""" + notes: List[str] = [] + if not scored: + return scored, notes + top_score, top_key = scored[0] + top_kind = documents.get(top_key, ("", ""))[1] + + def _promote(order: List[Tuple[float, str]], key: str) -> List[Tuple[float, str]]: + pair = next(p for p in order if p[1] == key) + rest = [p for p in order if p[1] != key] + # +1e-4: one display-ulp of headroom — scores are stored rounded + # to 4 decimals, so an exact min_margin bump can land a hair + # BELOW the threshold after rounding (0.86 - 0.8 = 0.05999...). + bumped = (round(order[0][0] + min_margin, 4) + 1e-4, pair[1]) + return [bumped] + rest + + # G1 — specific addressing displaces a non-tool top. + if top_kind != "tool": + best: Tuple[float, str] | None = None + for score, key in scored[1:6]: + if documents.get(key, ("", ""))[1] != "tool": + continue + if coverage.get(key, 0.0) >= 0.999: + if best is None or score > best[0]: + best = (score, key) + if best is not None and top_score - best[0] <= g1_margin: + scored = _promote(scored, best[1]) + notes.append( + f"guard G1: '{best[1]}' is specifically addressed (full " + f"name-atom coverage); displaces the {top_kind} top " + f"'{top_key}', which matched only by document overlap" + ) + top_key, top_score, top_kind = scored[0][1], scored[0][0], "tool" + + # G2 — a coarse surface matched only as a prepositional object. + if top_kind == "surface" and not notes: + name_toks = _surface_name_tokens(top_key) + if name_toks and all(_pp_only(t, raw_words) for t in name_toks): + pp_tokens = frozenset(t for t in name_toks if t in raw_words) + q_stems = _content_stems(raw_words, stems, pp_tokens) + best: Tuple[Tuple[int, float, str], str] | None = None + for score, key in scored[1:]: + if documents.get(key, ("", ""))[1] != "tool": + continue + if top_score - score > g2_margin: + continue + overlap = _doc_overlap(key, q_stems, doc_stems) + if overlap == 0: + continue + rank_key = (overlap, score, key) + if best is None or rank_key > best[0]: + best = (rank_key, key) + if best is not None: + promoted = best[1] + scored = _promote(scored, promoted) + notes.append( + f"guard G2: '{top_key}' matched only as the object of " + f"a preposition ({', '.join(sorted(pp_tokens))}); " + f"promoted '{promoted}', which matches the rest of " + f"the request" + ) + return scored, notes diff --git a/plugins/caelestia-assistant/assistant/core/label_fusion.json b/plugins/caelestia-assistant/assistant/core/label_fusion.json new file mode 100644 index 0000000..7cec709 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/core/label_fusion.json @@ -0,0 +1,34 @@ +{ + "voters": [ + "bigram", + "bm25", + "coverage", + "cue", + "fuzz", + "ppmi" + ], + "sensitivity": { + "bigram": 0.3208, + "bm25": 0.8463, + "coverage": 0.9622, + "cue": 0.8787, + "fuzz": 0.707, + "ppmi": 0.6779 + }, + "false_mass": { + "bigram": 0.0054, + "bm25": 0.021, + "coverage": 0.0042, + "cue": 0.0163, + "fuzz": 0.0413, + "ppmi": 0.0455 + }, + "iters_run": 14, + "n_items": 107, + "thresholds": { + "posterior_demote": 0.05, + "agreement_floor": 0.17 + }, + "tuning": "grid over posterior_demote x agreement_floor on the dev arena; chosen point maximizes (confident-wrongs demoted - correct routes demoted); frozen with the artifact. The LSA voter was cut (measured no-op, costly cold build) before this fit.", + "note": "Dawid-Skene EM over the dev routing set's per-signal votes (unsupervised \u2014 accept sets never read). The runtime action is demote-only: a confident ROUTED verdict the voters contradict becomes an honest ask." +} \ No newline at end of file diff --git a/plugins/caelestia-assistant/assistant/core/label_fusion.py b/plugins/caelestia-assistant/assistant/core/label_fusion.py new file mode 100644 index 0000000..a249074 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/core/label_fusion.py @@ -0,0 +1,292 @@ +"""cortex.label_fusion — Dawid-Skene label fusion over the router's own +signals (Group A2). + +The router already computes several INDEPENDENT-ish per-candidate +signals (lexical BM25, PPMI cosine, LSA/SVD cosine, char-ngram fuzz, +name-atom coverage, name-bigram addressing, cue-kind agreement). Today +their blend is one weight vector: a candidate wins when the blended +score clears the bar. But a blend can hide a LIE — one signal can drag +a wrong tool over the bar while every other signal prefers something +else (that is exactly what the arena's confident-wrong rows look like). + +Dawid-Skene (Dawid & Skene 1979, "A maximum likelihood approach to +extracting information from duplicate records") treats each signal as a +NOISY VOTER over the true surface and fuses their votes with +per-voter reliabilities estimated by unsupervised EM — no labels. The +artefact shipped here is the EM result over the dev routing set: + +- voters vote for their per-signal ARGMAX among the router's top-k + (deterministic tie-break: candidate order, i.e. router rank); +- EM estimates, per voter, sensitivity P(vote = true) and false-vote + mass P(vote = any specific wrong surface); initialization is the + majority-agreement posterior (deterministic, no RNG); +- the fused posterior combines with the router's own ranking, and the + ONLY runtime action is honesty-preserving: a confident ROUTED verdict + whose top candidate's fused posterior collapses below a threshold + while other candidates' posteriors rise — i.e. the voters DISAGREE + with the blend — is DEMOTED to AMBIGUOUS (an honest ask). The + clarifier (A4) then asks its question. Nothing is ever promoted or + re-ranked; no verdict becomes MORE confident from fusion. + +Why demote-only: the merge gate pays for capability, not risk. A +demotion turns a possible confident-wrong into an honest ask — bounded +downside, zero new write surface, verdicts stay honest. Promotion (ask +-> confident) is exactly the behavior that can manufacture confident +wrongs, so it does not exist here. + +CRF/perceptron slot taggers and the CART tree join the vote pool the +moment a trained model exists in user state (``vote()`` accepts any +voter dict); at cold start — the only state the arena can assume — +they abstain and are counted as absent, never as votes. +""" + +from __future__ import annotations + +import json +from pathlib import Path +from typing import Any, Dict, List, Optional, Sequence, Tuple + +__all__ = ["ARTIFACT_PATH", "fit", "vote_router_signals", "refine", + "load_model", "render_lines"] + +ARTIFACT_PATH = Path(__file__).resolve().parent / "label_fusion.json" + +# EM controls (deterministic; no RNG anywhere). +EM_ITERS = 50 +EM_TOL = 1e-7 + +# Fusion behavior thresholds (grid-searched on the dev arena only; +# the chosen point is the score-maximizing one: demote 1 +# confident-wrong, demote 0 correct routes — measured, then frozen). +POSTERIOR_DEMOTE = 0.05 # top candidate's fused posterior under this ... +AGREEMENT_FLOOR = 0.17 # ... with voter-agreement on top1 under this -> ask + +# The LSA/SVD voter was fitted first and CUT per the merge gate: on the +# dev arena its ballots changed nothing (fused confident-wrong 8/83 with +# or without it) while its SVD build cost 1-2s per cold process — enough +# to double the golden regen wall-clock. The vote pool accepts any +# voter; a future build may re-add it if it ever pays its way. +VOTER_KEYS = ("bm25", "ppmi", "fuzz", "coverage", "bigram", "cue") + + +# --------------------------------------------------------------------------- +# Voting. +# --------------------------------------------------------------------------- + + +def vote_router_signals(router, text: str, state) -> Dict[str, Any]: + """One query's voter ballots from the router's own signals, plus the + LSA/SVD embedder as an independent semantic voter. + + Returns {"candidates": [surface, ...] (router rank order), + "votes": {voter: surface-or-None}}. + """ + from .lexicon import stem + from .vectorize import tokenize + + res = router.route(text, state=state, k=8) + cands = [c.surface for c in res.candidates] + if not cands: + return {"candidates": [], "votes": {}} + feats = res.features + + def _argmax(key: str) -> Optional[str]: + best, best_val = None, -1.0 + for surface in cands: + val = feats.get(surface, {}).get(key, 0.0) + if val > best_val + 1e-12: + best, best_val = surface, val + return best + + votes: Dict[str, Optional[str]] = { + "bm25": _argmax("lex"), + "ppmi": _argmax("sem"), + "fuzz": _argmax("fuzz"), + "coverage": _argmax("coverage"), + "bigram": None, + "cue": _argmax("cue"), + } + + # bigram voter: a tool name-bigram appearing adjacently in the query + expanded, _ev = router._expand_query(text.lower().strip()) \ + if hasattr(router, "_expand_query") else (text, None) + stems = [stem(w) for w in tokenize(expanded)] + bigrams = {(stems[i], stems[i + 1]) for i in range(len(stems) - 1)} + best, best_n = None, 0 + for surface in cands: + n = sum(1 for bg in router.name_bigrams.get(surface, ()) + if bg in bigrams) + if n > best_n: + best, best_n = surface, n + votes["bigram"] = best + + return {"candidates": cands, "votes": votes} + + +# --------------------------------------------------------------------------- +# Dawid-Skene EM (unsupervised; deterministic). +# --------------------------------------------------------------------------- + + +def fit(vote_rows: Sequence[Dict[str, Any]]) -> Dict[str, Any]: + """Estimate per-voter reliabilities by EM over vote rows + ({candidates, votes}); the latent true surface is never observed. + + Model: per item, the latent surface s*; voter v votes v_i. + P(v_i = s | s*) = sensitivity_v if s = s*, else false_v spread + uniformly over the other candidates. Prior: uniform over candidates. + Initialization: majority-agreement posterior (deterministic). + """ + voters = sorted({v for row in vote_rows for v in row["votes"]}) + sens = {v: 0.75 for v in voters} + false_mass = {v: 0.05 for v in voters} + posteriors: List[Dict[str, float]] = [] + + def _e_step() -> List[Dict[str, float]]: + posts = [] + for row in vote_rows: + cands = row["candidates"] + if not cands: + posts.append({}) + continue + logp = {c: 0.0 for c in cands} + for v in voters: + vote = row["votes"].get(v) + if vote is None or vote not in logp: + continue + for c in cands: + p = sens[v] if c == vote else \ + false_mass[v] / max(1, len(cands) - 1) + import math + logp[c] += math.log(max(p, 1e-12)) + m = max(logp.values()) + z = sum(pow(2.718281828459045, lp - m) for lp in logp.values()) + posts.append({c: pow(2.718281828459045, lp - m) / z + for c, lp in logp.items()}) + return posts + + def _m_step(posts: List[Dict[str, float]]) -> None: + n_items = max(1, len(posts)) + for v in voters: + hit = 0.0 + false_total = 0.0 + for row, post in zip(vote_rows, posts): + vote = row["votes"].get(v) + if vote is None or not post: + continue + hit += post.get(vote, 0.0) + wrong = sum(p for c, p in post.items() if c != vote) + false_total += wrong / max(1, len(row["candidates"]) - 1) + sens[v] = min(0.98, (hit + 1.0) / (n_items + 2.0)) # Laplace + false_mass[v] = max(1e-4, min(0.9, false_total / n_items)) + + prev_ll = None + for _ in range(EM_ITERS): + posteriors = _e_step() + _m_step(posteriors) + # log-likelihood proxy for the convergence check + ll = 0.0 + import math + for row, post in zip(vote_rows, posteriors): + if not post: + continue + vote_products = 0.0 + for v in voters: + vote = row["votes"].get(v) + if vote is None: + continue + spread = false_mass[v] / max(1, len(row["candidates"]) - 1) + vote_products += math.log(max( + sum(post.get(c, 0.0) * + (sens[v] if c == vote else spread) + for c in row["candidates"]) or 1e-12, 1e-12)) + ll += vote_products + if prev_ll is not None and abs(ll - prev_ll) < EM_TOL: + break + prev_ll = ll + + return {"voters": voters, + "sensitivity": {v: round(sens[v], 4) for v in voters}, + "false_mass": {v: round(false_mass[v], 4) for v in voters}, + "iters_run": _ + 1, + "n_items": len(vote_rows)} + + +# --------------------------------------------------------------------------- +# Artifact + runtime fusion. +# --------------------------------------------------------------------------- + + +def load_model() -> Dict[str, Any]: + try: + return json.loads(ARTIFACT_PATH.read_text(encoding="utf-8")) + except (OSError, ValueError): + return {} + + +def refine(route_result, votes: Dict[str, Optional[str]], + model: Dict[str, Any], state) -> Tuple[str, Optional[str], float]: + """(verdict, question_note, top_posterior): the demote-only honesty + action. Returns the (possibly demoted) verdict and the fused + posterior of the router's top candidate.""" + from .router import RouterState # typing only + + cands = [c.surface for c in route_result.candidates] + if route_result.verdict != "ROUTED" or len(cands) < 2: + return route_result.verdict, None, 1.0 + + sens = model.get("sensitivity") or {} + fmass = model.get("false_mass") or {} + if not sens: + return route_result.verdict, None, 1.0 + + import math + logp = {c: 0.0 for c in cands} + n_votes = 0 + for v, vote in votes.items(): + if vote is None or vote not in logp: + continue + n_votes += 1 + s_v = float(sens.get(v, 0.5)) + f_v = float(fmass.get(v, 0.1)) + for c in cands: + p = s_v if c == vote else f_v / max(1, len(cands) - 1) + logp[c] += math.log(max(p, 1e-12)) + m = max(logp.values()) if logp else 0.0 + z = sum(pow(2.718281828459045, lp - m) for lp in logp.values()) or 1.0 + post = {c: pow(2.718281828459045, lp - m) / z for c, lp in logp.items()} + top = cands[0] + agreement = sum(1 for v, vote in votes.items() + if vote == top and vote is not None) / max(1, n_votes) + + if post.get(top, 1.0) < POSTERIOR_DEMOTE and agreement < AGREEMENT_FLOOR: + names = ", ".join(f"'{c}'" for c in cands[:3]) + note = (f"several settings could match: {names} — which one? " + f"(the router's signals disagree: only {agreement:.0%} of " + f"{n_votes} voters back the blend's winner)") + return "AMBIGUOUS", note, post.get(top, 0.0) + return route_result.verdict, None, post.get(top, 1.0) + + +def render_lines() -> List[str]: + model = load_model() + if not model: + return ["no label-fusion model committed " + "(python3 -m assistant.core.label_fusion)"] + lines = [f"Dawid-Skene voter reliabilities ({model.get('n_items')} dev " + f"items, {model.get('iters_run')} EM iters):"] + for v in model.get("voters", []): + lines.append(f" {v:9s} sensitivity {model['sensitivity'][v]:.2f} " + f"false-mass {model['false_mass'][v]:.2f}") + return lines + + +def main(argv=None) -> int: # pragma: no cover - thin CLI + import sys + for line in render_lines(): + print(line) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/plugins/caelestia-assistant/assistant/core/lexicon.py b/plugins/caelestia-assistant/assistant/core/lexicon.py new file mode 100755 index 0000000..b213e2a --- /dev/null +++ b/plugins/caelestia-assistant/assistant/core/lexicon.py @@ -0,0 +1,492 @@ +"""Lexical knowledge for the cortex layer: morphology, fuzzy matching, +and the desktop-customization synonym/antonym lexicon. + +Guarantees (same spine as ``settings/parser.py``): + +- PURE module: no I/O, no environment, no clock, no randomness. Every + function is a pure mapping from strings to strings/lists/numbers. +- stdlib ``re``/``difflib`` only; covered by the behavioral no-shell/no-network tests. +- Deterministic: identical input yields identical output, always. + +What lives here and why (each is a real, named, citable algorithm): + +- ``stem()`` — a Porter-style suffix-stripping stemmer, reduced to the + longest-match suffix rules that matter for this domain (plurals, -ing, + -ed, -er, -ly, -ness). Full Porter is ~60 rules; this implements the + subset with measurable effect on desktop-customization vocabulary and + skips the measure/``m > 0`` conditions that need vowel-cluster scoring, + because the domain has no minimal-pair stems that would need them. +- ``levenshtein()`` — the classic DP edit distance, O(len_a * len_b) + with the two-row memory optimization. +- ``jaro_winkler()`` — Jaro similarity with Winkler's prefix boost, the + standard lean typo-similarity for short strings (tool names, nouns). +- ``char_ngrams()`` + ``ngram_similarity()`` — character 3-gram cosine + overlap, the robust "sounds like" signal for compound tool names + (``setGreeterMorningStart`` vs "greeting morning"). +- ``SYNONYMS`` / ``DIRECTION_WORDS`` / ``ABSOLUTE_WORDS`` — the domain + lexicon: hand-seeded, reviewable, versioned. Synonyms map user words + onto the registry's own noun vocabulary; direction words carry the + numeric polarity they imply (``thinner -> -1``) so the router can + attach a value-extraction cue without any language model. + +The lexicon is deliberately small and honest: it claims nothing about +words it does not know. Unknown words fall through to stem/ngram +matching only — no silent invention of meaning. +""" + +from __future__ import annotations + +import re +from collections import Counter +from difflib import SequenceMatcher +from typing import Dict, List, Optional, Tuple + +# --------------------------------------------------------------------------- +# Morphology: domain-reduced Porter stemmer. +# --------------------------------------------------------------------------- + +# Longest-match suffix rules, ordered. Each rule: (suffix, replacement, +# min_stem_len). Applied once, longest match first. The rule set is +# IDEMPOTENT by construction: no rule's replacement may leave a suffix +# that a later-pass rule would strip again (that is why -er/-ers/-es/-ate +# transformations are absent: "corners"->"corner"->"corn" chains are +# exactly the kind of instability that breaks query/document stemming +# agreement — both sides must land on the SAME stem, always). +_SUFFIX_RULES: List[Tuple[str, str, int]] = [ + ("ations", "ation", 4), + ("ities", "ity", 3), + ("iveness", "ive", 3), + ("fulness", "ful", 3), + ("ousness", "ous", 3), + ("ization", "ize", 3), + ("tional", "tion", 3), + ("bilities", "ble", 3), + ("ies", "y", 3), + ("ings", "", 4), + ("ing", "", 4), + ("edly", "", 4), + ("ness", "", 4), + ("ment", "", 4), + ("ally", "", 4), + ("ed", "", 3), + ("ly", "", 3), + ("s", "", 3), +] + +_WORD_RE = re.compile(r"[a-z]+") + + +def stem(word: str) -> str: + """Domain-reduced Porter stem of one lowercase word. + + Idempotent (``stem(stem(w)) == stem(w)``) because each rule is applied + at most once and no rule's output feeds another rule (see the rule + table's comment). Comparatives keep their -er ("thinner" stays + "thinner" on BOTH sides of every comparison, which is what makes + cue-vocabulary agreement reliable). Words shorter than any rule's + ``min_stem_len`` are returned unchanged (``"ss"`` never loses its s). + """ + w = word.lower() + if w.endswith("ss"): # glass/class/loss keep their double-s: stripping + return w # one s breaks idempotence (glass->glas->gla) + for suffix, replacement, min_len in _SUFFIX_RULES: + if w.endswith(suffix) and len(w) - len(suffix) >= min_len: + return w[: len(w) - len(suffix)] + replacement + return w + + +# --------------------------------------------------------------------------- +# Fuzzy string similarity (all pure, all deterministic). +# --------------------------------------------------------------------------- + + +def levenshtein(a: str, b: str, cap: Optional[int] = None) -> int: + """Two-row edit distance. ``cap`` stops early once the distance provably + exceeds it (returns ``cap + 1``) — a bounded Levenshtein automaton in + spirit, useful for cheap rejection in the router hot loop.""" + if a == b: + return 0 + if cap is not None and abs(len(a) - len(b)) > cap: + return cap + 1 + prev = list(range(len(b) + 1)) + for i, ca in enumerate(a, start=1): + cur = [i] + [0] * len(b) + best = cur[0] + for j, cb in enumerate(b, start=1): + cost = 0 if ca == cb else 1 + cur[j] = min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + cost) + if cur[j] < best: + best = cur[j] + if cap is not None and best > cap: + return cap + 1 + prev = cur + return prev[-1] + + +def jaro(a: str, b: str) -> float: + """Jaro similarity (0..1). Standard definition: match window, ordered + transposition count, ``(m/|a| + m/|b| + (m-t)/m) / 3``.""" + if a == b: + return 1.0 + if not a or not b: + return 0.0 + window = max(len(a), len(b)) // 2 - 1 + if window < 0: + window = 0 + a_match = [False] * len(a) + b_match = [False] * len(b) + matches = 0 + for i in range(len(a)): + lo = max(0, i - window) + hi = min(i + window + 1, len(b)) + for j in range(lo, hi): + if not b_match[j] and a[i] == b[j]: + a_match[i] = b_match[j] = True + matches += 1 + break + if matches == 0: + return 0.0 + transpositions = 0 + k = 0 + for i in range(len(a)): + if a_match[i]: + while not b_match[k]: + k += 1 + if a[i] != b[k]: + transpositions += 1 + k += 1 + transpositions //= 2 + return (matches / len(a) + matches / len(b) + (matches - transpositions) / matches) / 3.0 + + +def jaro_winkler(a: str, b: str, prefix_scale: float = 0.1) -> float: + """Jaro-Winkler: Jaro + prefix boost (max 4 chars, scale capped at + the standard 0.1 so the score can never exceed 1).""" + j = jaro(a, b) + prefix = 0 + for ca, cb in zip(a, b): + if ca != cb or prefix == 4: + break + prefix += 1 + return j + prefix * prefix_scale * (1.0 - j) + + +def char_ngrams(text: str, n: int = 3) -> List[str]: + """Character n-grams with word boundaries marked (``|`` pads), so + word-start shape information survives the n-gram collapse.""" + padded = "|" + text.lower() + "|" + return [padded[i : i + n] for i in range(len(padded) - n + 1)] + + +def ngram_similarity(a: str, b: str, n: int = 3) -> float: + """Cosine overlap of character n-gram multisets — the "sounds like" + signal for compound tool names vs user phrases.""" + ga, gb = Counter(char_ngrams(a, n)), Counter(char_ngrams(b, n)) + if not ga or not gb: + return 0.0 + dot = sum(count * gb[gram] for gram, count in ga.items()) + norm = (sum(v * v for v in ga.values()) ** 0.5) * (sum(v * v for v in gb.values()) ** 0.5) + return dot / norm if norm else 0.0 + + +# --------------------------------------------------------------------------- +# The domain lexicon (hand-seeded, reviewable, versioned). +# --------------------------------------------------------------------------- + +LEXICON_VERSION = 1 + +# User words -> registry noun vocabulary. Keys are matched on RAW words and +# STEMS in the router; values are the canonical words the registry nouns use. +SYNONYMS: Dict[str, Tuple[str, ...]] = { + # compound joins (hyphenated keys are never tool atoms, so these map + # query-side only and cannot change the indexed corpus / fingerprints) + "time-out": ("timeout", "expire"), + # bar / panel + "bar": ("bar", "taskbar", "panel"), + "panel": ("bar", "panel", "taskbar"), + "taskbar": ("taskbar", "bar", "panel"), + "toolbar": ("bar", "taskbar"), + "strip": ("bar",), + "ribbon": ("bar",), + # dock + "dock": ("dock",), + "app-dock": ("dock",), + # transparency / blur + "glass": ("blur", "glass"), + "glassy": ("blur", "glass"), + "frost": ("blur",), + "frosted": ("blur",), + "blurry": ("blur",), + "hazy": ("blur",), + "see-through": ("transparency",), + "translucent": ("transparency",), + "transparent": ("transparency",), + "opaque": ("transparency",), + # radius / corners + "corner": ("rounding", "corner"), + "corners": ("rounding", "corner"), + "rounded": ("rounding",), + "rounding": ("rounding",), + "curvature": ("rounding",), + "sharp": ("rounding",), + "squarish": ("rounding",), + # spacing / padding + "spacing": ("spacing",), + "gaps": ("spacing", "gap"), + "gap": ("gap", "spacing"), + "roomy": ("spacing",), + "cramped": ("spacing",), + "airy": ("spacing",), + "padding": ("padding",), + "margin": ("padding",), + "margins": ("padding",), + # fonts + "font": ("font",), + "fonts": ("font",), + "text": ("font", "label"), + "letters": ("font",), + "typeface": ("font",), + "typography": ("font",), + # animations + "animation": ("animation",), + "animations": ("animation",), + "motion": ("animation",), + "transition": ("animation",), + "transitions": ("animation",), + # notifications + "notification": ("notification",), + "notifications": ("notifications",), + "notifs": ("notifications",), + "toast": ("notification",), + "toasts": ("notification",), + "popup": ("notification", "popup"), + "popups": ("notification", "popup"), + "banner": ("notification",), + # launcher + "launcher": ("launcher",), + "app-launcher": ("launcher",), + "menu": ("launcher",), + "start-menu": ("launcher",), + # greeter / clock + "greeter": ("greeter",), + "greeting": ("greeter",), + "clock": ("clock",), + # workspaces + "workspace": ("workspace",), + "workspaces": ("workspaces",), + "desktops": ("workspaces",), + "virtual-desktop": ("workspaces",), + # overview + "overview": ("overview",), + "mission-control": ("overview",), + # border + "border": ("border",), + "outline": ("border",), + "stroke": ("border",), + "bezel": ("border", "pitch-black"), + # wallpaper + "wallpaper": ("wallpaper",), + "wallpapers": ("wallpaper",), + "background": ("wallpaper", "background"), + # scheme / colors + "scheme": ("scheme", "color"), + "color": ("color", "scheme"), + "colors": ("color", "scheme"), + "colour": ("color", "scheme"), + "colours": ("color", "scheme"), + "palette": ("scheme", "palette"), + "theme": ("scheme", "theme"), + "accent": ("accent", "scheme"), + # preview + "preview": ("preview",), + "previews": ("preview",), + "thumbnail": ("preview",), + "thumbnails": ("preview",), + "peek": ("preview",), + # tray + "tray": ("tray",), + "system-tray": ("tray",), + "systray": ("tray",), + # status / icons + "status": ("status",), + "indicators": ("status",), + "icons": ("icon",), + "icon": ("icon",), + # battery/perf + "battery": ("battery",), + "cpu": ("cpu",), + "memory": ("memory",), + "performance": ("performance",), + "perf": ("performance",), + # osd + "osd": ("osd",), + "overlay": ("osd",), + # volume / brightness + "volume": ("volume",), + "brightness": ("brightness",), + # sidebar / dashboard + "sidebar": ("sidebar",), + "dashboard": ("dashboard",), + "utilities": ("utilities",), + # lock + "lock": ("lock",), + "lockscreen": ("lock",), + "login": ("lock",), + # session + "session": ("session",), + "power-menu": ("session",), + # game mode + "game-mode": ("game",), + "gamemode": ("game",), + "gaming": ("game",), + # F3 (2026-09-28): the overview's animation timing is the OVERVIEW + # config's baseDuration — upstream declares it in + # shell/plugin/src/Caelestia/Config/overviewconfig.hpp + # ("overview.baseDuration", cited on the tool itself). Without this + # the phrase "overview animation" lexicalizes as the generic + # animation-speed tool, which is the confident-wrong the arena + # measures. Hyphenated key: query-side only, never re-indexed. + "overview-animation": ("base", "duration"), + # F3 (2026-09-28): Nexus's "performance panel" IS the dashboard + # surface (shell/modules/nexus/pages/panels/DashboardPanel.qml — the + # panel that renders performance.* tools). Query-side only. + "performance-panel": ("dashboard",), + # sound / audio + "sound": ("sound",), + "sounds": ("sound",), + "audio": ("audio",), +} + +# Antonym/direction pairs: word -> numeric direction on the matched tool's +# axis (+1 = up/more, -1 = down/less). These are the polarity cues the +# router attaches as value-extraction hints; the settings planner still +# resolves the actual value against the live file (never this module). +DIRECTION_WORDS: Dict[str, int] = { + # NOTE: bare "up"/"down" are deliberately NOT direction words here — + # they are phrasal-verb particles far too often ("piling up", + # "show up", "clean up") and a false direction cue silently corrupts + # cue-kind agreement. parser.py's own grammar applies them inside + # constrained value phrases; the router's cue extractor does not have + # that context, so it abstains on them. + "thinner": -1, "smaller": -1, "slimmer": -1, "shrink": -1, + "reduce": -1, "decrease": -1, "less": -1, "lower": -1, + "tighter": -1, "minimize": -1, + "fewer": -1, "few": -1, "shorten": -1, "trim": -1, "cut": -1, + "transparent": -1, "translucent": -1, "see-through": -1, + "thicker": 1, "bigger": 1, "larger": 1, "wider": 1, "grow": 1, + "increase": 1, "more": 1, "raise": 1, "roomier": 1, + "spacious": 1, "expand": 1, "enlarge": 1, "maximize": 1, + "lengthen": 1, "extend": 1, "add": 1, + "opaque": 1, "solid": 1, + "rounder": 1, "squarer": -1, "sharper": -1, + "faster": -1, "quicker": -1, "snappier": -1, "slower": 1, + "smoother": 1, "softer": 1, "harder": -1, + "later": 1, "earlier": -1, "sooner": -1, "delay": 1, + "brighter": 1, "darker": -1, "lighter": -1, "heavier": 1, +} + +# Words that imply absolute-zero or absolute-maximum targets (the +# "borderless" trick from parser.py §3.4, generalized). +ABSOLUTE_WORDS: Dict[str, float] = { + "borderless": 0.0, + "zero": 0.0, + "none": 0.0, + "maximum": 1.0, + "max": 1.0, + "full": 1.0, + "pitch-black": 1.0, +} + +# On/off vocabulary (mirrors parser.py §3.5 so both surfaces agree). +BOOL_ON_WORDS = frozenset({"on", "enable", "enabled", "activate", "show", "display", "reveal"}) +BOOL_OFF_WORDS = frozenset({"off", "disable", "disabled", "deactivate", "hide", "conceal"}) + + +# PMI-mined hints (capability 1): loaded once from data/mined_synonyms.json +# when present. These are HINTS on the expanded (0.3-weight) channel — +# never replacements — and the file is regenerated by a dev script, so +# shipping code never mutates them. +_MINED_HINTS: Dict[str, tuple] = {} + + +def _load_mined_hints() -> None: + import json as _json + from pathlib import Path as _Path + path = _Path(__file__).resolve().parents[1] / "data" / "mined_synonyms.json" + try: + raw = _json.loads(path.read_text(encoding="utf-8")).get("mined", {}) + except (OSError, ValueError): + return + for tool, words in raw.items(): + for w in words: + _MINED_HINTS.setdefault(w, tuple()) + # word -> the words mined alongside the same tool atoms + _atom_words = {} + for tool, words in raw.items(): + for w in words: + _atom_words.setdefault(w, set()).update( + x for x in words if x != w) + for w, xs in _atom_words.items(): + _MINED_HINTS[w] = tuple(sorted(xs)) + + +_load_mined_hints() + + +def expand_synonyms(text: str) -> List[str]: + """Every canonical noun word that any word of ``text`` maps to, plus the + original words, plus (last, as hints) any PMI-mined co-occurring + vocabulary words. Pure union — no scoring here (the router scores).""" + out: List[str] = [] + for raw in _WORD_RE.findall(text.lower()): + if raw not in out: + out.append(raw) + for key in (raw, stem(raw)): + for mapped in SYNONYMS.get(key, ()): + if mapped not in out: + out.append(mapped) + for hint in _MINED_HINTS.get(raw, ()): + if hint not in out: + out.append(hint) + return out + + +def direction_of(text: str) -> int: + """Net direction cue of ``text``: sum of DIRECTION_WORDS hits, sign() + collapsed to -1/0/+1. Mixed signals cancel to 0 (honest abstain).""" + total = 0 + for raw in _WORD_RE.findall(text.lower()): + total += DIRECTION_WORDS.get(raw, DIRECTION_WORDS.get(stem(raw), 0)) + if total > 0: + return 1 + if total < 0: + return -1 + return 0 + + +def camel_split(name: str) -> List[str]: + """Split a camelCase tool name into its word atoms: + ``setGreeterMorningStart`` -> ``["set", "greeter", "morning", "start"]``. + This is the trick that turns 259 noun-silent tool NAMES into + addressable vocabulary without inventing any semantics.""" + return [w.lower() for w in re.findall(r"[A-Z]?[a-z]+|[A-Z]+(?![a-z])", name) if w] + + +def distributional_neighbors(embedder, word: str, k: int = 5) -> List[str]: + """A2 — the distributional view of this lexicon: the top-k words the + embedder's co-occurrence space places nearest to ``word``, formatted + as reviewable ``"word (cosine)"`` rows. + + This is the honest complement to the hand-seeded SYNONYMS table: the + seeded lexicon says what a maintainer believes; the distributional + view says what the corpus's own co-occurrences imply. It CLAIMS + nothing about words absent from the corpus (unknown -> empty list) + and adds no semantics to the router by itself — a maintainer reading + these rows and promoting a genuine synonym into SYNONYMS is the + intended workflow (the reviewed-diff discipline the package rationale (see module docstrings) §5 + applies to lexicon changes too). + + ``embedder`` is any PpmiEmbedder/PpmiSvdEmbedder (both expose + ``neighbors``); the function is pure given the embedder.""" + found = embedder.neighbors(word, k=k) if hasattr(embedder, "neighbors") else [] + return [f"{w} ({score:+.4f})" for w, score in found] diff --git a/plugins/caelestia-assistant/assistant/core/lexicon_diff.py b/plugins/caelestia-assistant/assistant/core/lexicon_diff.py new file mode 100644 index 0000000..d68c74b --- /dev/null +++ b/plugins/caelestia-assistant/assistant/core/lexicon_diff.py @@ -0,0 +1,485 @@ +"""cortex.lexicon_diff — federated, opt-in, signed lexicon-diff sharing +(phase 2.6; the former proposals/2026-09-26-c-lexicon-diff- +sharing.md, pruned in exponential-build-3 Phase 2 once +implemented). + +The shareable artifact is a plain-text, reviewable list of +``phrase -> tool`` mappings a user's cortex has learned (reroute +corrections + approved routes), capped at the newest 200, PII-stripped +to the undo log's standard: no timestamps, no file paths, no values — +phrases are the only content, and phrases are what the user chose to +type at the assistant. + +Federation means reviewable text over the channels the community +already uses (issue threads, matrix, fork PRs) — NO server, NO +network code, NO crypto code in the assistant (the import allow-list +is untouched). "Signed" happens OUTSIDE: an Ed25519 detached signature +over the canonical diff text produced and verified by a tool the user +already trusts (minisign / sq / GPG); the assistant only states whose +corpus a diff claims to be — trust in that identity stays a human +decision. + +The module is PURE (no I/O): the caller loads/saves the brain state. +State shape (new key, forward-compatible): + + state["lexicon_imports"] = { + "": { + "rows": [{"text", "surface", "n", "p", "label"}], + "at": "2026-09-26T..." # import time, local metadata only + }, ... + } + +The diff-id is sha256[:12] of the canonical row text — `forget` drops +the set by id, restoring the pre-import pair list (and therefore the +corpus-only embedder build on the next process). + +Import safety (the proposal's own mitigations, all pinned by test): +- import caps (200 rows); +- per-phrase length cap (120 chars, the learner's own bound); +- rows naming NON-EXISTENT tools import as no-ops with warnings, + never exceptions (injection fuzz); +- the import report lists every tool the diff would boost; +- imports land as SUPERVISED PAIRS in the embedder seam (A2's + ``labeled_pairs`` — never into the hand-seeded SYNONYMS, which stay + a reviewed diff) and as review-bucket candidates for the learner's + batch-review flow. + +Embedder wiring (the one runtime consequence): PpmiEmbedder's shared +singleton (vectorize.embedder) reads the persisted pairs at its lazy +first build — an ABSENT import keeps the corpus-only build byte-for- +byte (the A2-measured default), which is why the fingerprint test in +test_svd_embedder pins the no-pairs build. +""" + +from __future__ import annotations + +import hashlib +import re +from datetime import datetime +from typing import Any, Dict, List, Optional, Tuple + +__all__ = [ + "DIFF_HEADER", "MAX_PAIRS", "PHRASE_MAX", "IMPORTS_KEY", "TRUST_KEY", + "MAX_TRUST_EVENTS", "export_rows", "render", "parse", "diff_id", + "import_diff", "forget", "persisted_pairs", "imported_ids", + "signer_trust", "render_advisory", +] + +DIFF_HEADER = "CAELESTIA LEXICON DIFF v1" +MAX_PAIRS = 200 +PHRASE_MAX = 120 +IMPORTS_KEY = "lexicon_imports" +TRUST_KEY = "lexicon_trust" +MAX_TRUST_EVENTS = 500 + +_ROW_RE = re.compile( + r"^\s*(?P[+-])(?P.*?\S)\s*->\s*(?P\S+)" + r"(?:\s*\(n=(?P\d+),\s*p=(?P

[0-9.]+)\))?" + # optional dp provenance marker (cortex/dp.py, exponential-build 3 + # B4): additive — an absent marker leaves the match unchanged, so + # the exact export format is byte-identical to before + r"(?:\s*\(dp:\s*epsilon=(?P[0-9.]+)\))?\s*$") +_DATE_RE = re.compile(r"^\((.+)\)\s*$") + + +# --------------------------------------------------------------------------- +# Export (the learner's examples -> reviewable rows). +# --------------------------------------------------------------------------- + + +def export_rows(state: Dict[str, Any], learn_key: str = "cortex_learn", + max_pairs: int = MAX_PAIRS) -> List[Dict[str, Any]]: + """Derive the shareable rows from the learner's bounded example log: + group by (text, surface); n = occurrences; p = the mean ROUTE + probability the user saw; the sign is the majority outcome + (+ approved/applied, - corrected/rejected). Newest ``max_pairs`` + groups by last-seen position. PII-safe: only text/surface/n/p.""" + examples = [] + learn = state.get(learn_key) + if isinstance(learn, dict): + raw = learn.get("examples") or [] + examples = [dict(r) for r in raw if isinstance(r, dict)] + order: Dict[Tuple[str, str], int] = {} + agg: Dict[Tuple[str, str], Dict[str, Any]] = {} + for pos, row in enumerate(examples): + text = str(row.get("text", ""))[:PHRASE_MAX].strip() + surface = str(row.get("surface", "")).strip() + if not text or not surface: + continue + key = (text, surface) + if key not in agg: + agg[key] = {"text": text, "surface": surface, + "n": 0, "p_sum": 0.0, "plus": 0, "minus": 0} + order[key] = pos + a = agg[key] + a["n"] += 1 + try: + a["p_sum"] += float(row.get("p", 0.0)) + except (TypeError, ValueError): + pass + if int(row.get("label", 0)) == 1: + a["plus"] += 1 + else: + a["minus"] += 1 + # newest groups last-seen first, cap, then deterministic order by text + newest = sorted(order, key=lambda k: -order[k])[:max_pairs] + rows = [] + for key in sorted(newest): + a = agg[key] + rows.append({ + "text": a["text"], + "surface": a["surface"], + "n": a["n"], + "p": round(a["p_sum"] / a["n"], 2) if a["n"] else 0.0, + "label": 1 if a["plus"] >= a["minus"] else 0, + }) + return rows + + +def render(rows: List[Dict[str, Any]], date: str = "") -> str: + """The canonical diff text — deterministic for the same rows (and + the same date string; the CLI stamps today, tests pin a fixed one). + Sorted by text; one row per line; nothing else in the artifact.""" + lines = [f"{DIFF_HEADER} ({date})" if date else DIFF_HEADER] + for row in sorted(rows, key=lambda r: (r.get("text", ""), + r.get("surface", ""))): + sign = "+" if int(row.get("label", 1)) == 1 else "-" + n = int(row.get("n", 1)) + p = float(row.get("p", 0.0)) + lines.append(f"{sign}{row.get('text', '')} -> " + f"{row.get('surface', '')} (n={n}, p={p:.2f})") + return "\n".join(lines) + "\n" + + +# --------------------------------------------------------------------------- +# Parse + validate (never raises; malformed input is a warning). +# --------------------------------------------------------------------------- + + +def parse(text: str) -> Tuple[List[Dict[str, Any]], List[str]]: + """Parse a diff back into rows. Returns (rows, warnings). Malformed + lines, over-long phrases, unknown tools, and over-cap rows become + WARNINGS, never exceptions (the injection-fuzz contract).""" + warnings: List[str] = [] + rows: List[Dict[str, Any]] = [] + known_tools: Optional[Dict[str, bool]] = None + + def _tool_exists(name: str) -> bool: + nonlocal known_tools + if known_tools is None: + from assistant.adapters.caelestia.registry import TOOL_SPECS + known_tools = {spec.name: True for spec in TOOL_SPECS} + return name in known_tools + + for lineno, line in enumerate(text.splitlines(), start=1): + stripped = line.strip() + if not stripped or stripped == DIFF_HEADER \ + or stripped.startswith(DIFF_HEADER) \ + or stripped.startswith("#"): + continue # header (with or without date) / blank / comment: + # no-ops + m = _ROW_RE.match(stripped) + if not m: + warnings.append(f"line {lineno}: unparseable, skipped: " + f"{stripped[:60]!r}") + continue + phrase = m.group("text").strip() + surface = m.group("surface").strip() + if len(phrase) > PHRASE_MAX: + warnings.append(f"line {lineno}: phrase over {PHRASE_MAX} chars, " + "skipped (the learner's own bound)") + continue + if not _tool_exists(surface): + warnings.append(f"line {lineno}: {surface!r} is not a registry " + "tool, skipped (unknown tools never import)") + continue + if any(r["text"] == phrase and r["surface"] == surface for r in rows): + warnings.append(f"line {lineno}: duplicate row, skipped") + continue + rows.append({ + "text": phrase, + "surface": surface, + "n": max(1, int(m.group("n") or 1)), + "p": min(1.0, max(0.0, float(m.group("p") or 0.0))), + "label": 1 if m.group("sign") == "+" else 0, + # the dp noising provenance (cortex/dp.py), when present: + # rides along as row metadata so a reviewer of an IMPORTED + # state can still see which rows carry noised evidence + "dp_epsilon": float(m.group("dp")) if m.group("dp") else None, + }) + if len(rows) > MAX_PAIRS: + warnings.append(f"line {lineno}: over the {MAX_PAIRS}-row import " + "cap, skipped") + rows.pop() + return rows, warnings + + +def diff_id(rows: List[Dict[str, Any]]) -> str: + """Stable id for one imported set: sha256[:12] of the canonical rows + (id → same set; any row change → different id).""" + canonical = render(sorted(rows, key=lambda r: (r.get("text", ""), + r.get("surface", ""))), + date="canonical") + return hashlib.sha256(canonical.encode("utf-8")).hexdigest()[:12] + + +# --------------------------------------------------------------------------- +# Import / forget (state-transforming, still pure — caller persists). +# --------------------------------------------------------------------------- + + +def import_diff(state: Dict[str, Any], text: str, + signer: Optional[str] = None) -> Dict[str, Any]: + """Apply one diff into the state: parse + validate, persist the rows + under their diff-id, and REPORT (boosted tools, parity measurement, + rollback command). Never touches SYNONYMS; never raises on + malformed input. + + ``signer`` (optional, phase 2.3): the identity the user verified with + THEIR external tool (minisign/sq/gpg) — recorded as local metadata + so a rollback history can exist, and feeding the ADVISORY + EigenTrust-style trust score in the report. It changes nothing about + the import's safety behavior: review candidates are added exactly as + before, and no trust level ever auto-skips the explicit review.""" + rows, warnings = parse(text) + if not rows: + return {"error": "nothing importable in this diff " + f"({len(warnings)} warning(s))", + "warnings": warnings} + did = diff_id(rows) + imports = state.get(IMPORTS_KEY) + if not isinstance(imports, dict): + imports = {} + imports[did] = {"rows": rows, "n": len(rows)} + if signer: + imports[did]["signer"] = str(signer) + state[IMPORTS_KEY] = imports + # review-bucket candidates (the proposal's second landing): each row + # becomes one candidate the learner's batch-review flow can label — + # imports are absorbed through the supervised path, never silently + try: + from . import learn as cortex_learn + bucket = [dict(c) for c in state.get(cortex_learn.REVIEW_KEY, []) + if isinstance(c, dict)] + known = {c.get("text") for c in bucket} + from datetime import datetime + stamped = datetime.now().isoformat() + for row in rows: + if row["text"] in known: + continue # already parked for review + bucket.append({"text": row["text"], "verdict": "IMPORTED", + "surface": row["surface"], "p": row.get("p"), + "at": stamped}) + state[cortex_learn.REVIEW_KEY] = bucket[:cortex_learn.MAX_CANDIDATES] + except Exception: + pass # the review-bucket landing is best-effort, never fatal + # the boosted-tools warning (the injection surface made visible) + boosted = sorted({row["surface"] for row in rows}) + if signer: + _append_trust_event(state, { + "signer": str(signer), "action": "imported", + "diff_id": did, "tools": boosted, + "at": datetime.now().isoformat(timespec="seconds")}) + report = { + "diff_id": did, + "imported": len(rows), + "boosted_tools": boosted, + "warnings": warnings, + "note": "the pairs weight the shared embedder at its next build " + "(supervision, weight above the corpus prior — never the " + "hand-seeded SYNONYMS); review candidates were added for " + "the learner's batch flow", + "rollback": f"cortex lexicon forget {did}", + "verify": "verify the signature with YOUR external tool " + "(minisign/sq/gpg) before trusting the source — the " + "assistant states the content, the human owns the trust", + } + if signer: + report["signer_trust"] = render_advisory(signer_trust(state), + str(signer)) + return report + + +def forget(state: Dict[str, Any], the_id: str) -> Dict[str, Any]: + """Drop one imported set by diff-id. The pre-import pair list is + restored by construction (the remaining imports stand); the next + embedder build drops the forgotten pairs. A set that carried signer + metadata records a ROLLBACK event for the trust propagation (phase + 2.3) — the one negative signal a signer can earn here.""" + imports = state.get(IMPORTS_KEY) + if not isinstance(imports, dict) or the_id not in imports: + known = sorted(k for k in imports if isinstance(k, str)) \ + if isinstance(imports, dict) else [] + return {"error": f"no imported diff {the_id!r} " + + (f"(have: {', '.join(known)})" if known else + "(nothing imported)")} + dropped = imports.pop(the_id) + signer = (dropped.get("signer") if isinstance(dropped, dict) + else None) + if signer: + _append_trust_event(state, { + "signer": str(signer), "action": "rolled_back", + "diff_id": the_id, + "tools": sorted({row.get("surface", "") + for row in (dropped.get("rows") or []) + if isinstance(row, dict)}), + "at": datetime.now().isoformat(timespec="seconds")}) + if not imports: + state.pop(IMPORTS_KEY, None) + else: + state[IMPORTS_KEY] = imports + result = {"forgot": the_id, + "rows_dropped": len(dropped.get("rows", [])), + "note": "the next embedder build drops these pairs " + "(corpus-only again for this set)"} + if signer: + result["note"] += ("; rollback recorded against signer " + f"{signer!r} (advisory trust signal)") + return result + + +def imported_ids(state: Dict[str, Any]) -> List[str]: + imports = state.get(IMPORTS_KEY) + if not isinstance(imports, dict): + return [] + return sorted(str(k) for k in imports) + + +def persisted_pairs(state: Dict[str, Any]) -> List[Tuple[str, str]]: + """Flatten the imported sets into supervised (text, surface) pairs + for the embedder seam — the A2 ``labeled_pairs`` parameter.""" + pairs: List[Tuple[str, str]] = [] + imports = state.get(IMPORTS_KEY) + if not isinstance(imports, dict): + return pairs + for rows in (v.get("rows") or [] for v in imports.values() + if isinstance(v, dict)): + for row in rows: + if isinstance(row, dict) and row.get("text") and row.get("surface"): + pairs.append((str(row["text"]), str(row["surface"]))) + return pairs[:MAX_PAIRS] + + +# --------------------------------------------------------------------------- +# Signer trust (phase 2.3) — ADVISORY ONLY, never an auto-decision. +# +# EigenTrust (Kamvar, Schlosser & Garcia-Molina 2003, "The Eigentrust +# algorithm for reputation management in P2P networks", WWW) computes +# reputation as the fixed point of t = a*p + (1-a)*C^T t: direct evidence +# (the pretrust p) blended with what the graph propagates through +# normalized trust edges (C), iterated to convergence. This module has +# no peer-to-peer opinions — what it HAS locally is: +# - direct evidence per signer: their diffs the user KEPT vs the diffs +# the user ROLLED BACK (import/forget events above); +# - edges worth propagating along: signers whose diffs boost the SAME +# tools are correlated — a Jaccard overlap edge, so a rollback of one +# diff also dents the signers whose diffs boost the same tools, and +# a well-received diff lifts its correlated signers a little. +# The fixed point is computed by the same power iteration; the result is +# an ADVISORY score rendered next to the import report. It MUST NOT and +# DOES NOT auto-decide anything: every diff still lands as supervised +# pairs + review candidates, and the explicit review requirement is +# unchanged for every diff at every trust level (pinned by test). +# --------------------------------------------------------------------------- + + +def _append_trust_event(state: Dict[str, Any], event: Dict[str, Any]) -> None: + """Bounded newest-appended event log (pure; the caller persists).""" + trust = state.get(TRUST_KEY) + if not isinstance(trust, dict): + trust = {} + events = [e for e in (trust.get("events") or []) if isinstance(e, dict)] + events.append(event) + trust["events"] = events[-MAX_TRUST_EVENTS:] + state[TRUST_KEY] = trust + + +def signer_trust(state: Dict[str, Any], a: float = 0.15, + iterations: int = 25) -> Dict[str, Dict[str, Any]]: + """The EigenTrust-style fixed point over the recorded signer events. + + Returns {signer: {"trust", "kept", "rolled_back", "tools"}} sorted + by trust desc, name asc (deterministic). ``a`` is the blend toward + direct evidence (the pretrust), the rest propagates through the + Jaccard tool-overlap edges. No events -> {} (no invented opinions).""" + events = [] + trust = state.get(TRUST_KEY) + if isinstance(trust, dict): + events = [e for e in (trust.get("events") or []) + if isinstance(e, dict) and e.get("signer")] + if not events: + return {} + + kept: Dict[str, int] = {} + rolled: Dict[str, int] = {} + tools: Dict[str, set] = {} + for e in events: + name = str(e.get("signer", "")) + if not name: + continue + if e.get("action") == "rolled_back": + rolled[name] = rolled.get(name, 0) + 1 + else: + kept[name] = kept.get(name, 0) + 1 + tools.setdefault(name, set()).update( + str(t) for t in (e.get("tools") or []) if t) + names = sorted(set(kept) | set(rolled)) + + # pretrust: the user's own Beta-smoothed keep rate (the bandit's + # Beta(1,1) prior shape — no history means 0.5, never 1.0) + pretrust = {} + for name in names: + pretrust[name] = (kept.get(name, 0) + 1.0) / \ + (kept.get(name, 0) + rolled.get(name, 0) + 2.0) + total = sum(pretrust.values()) or 1.0 + p = {n: pretrust[n] / total for n in names} + + # edges: Jaccard overlap of boosted tool sets, row-normalized + def jaccard(x: set, y: set) -> float: + if not x or not y: + return 0.0 + inter = len(x & y) + union = len(x | y) + return inter / union if union else 0.0 + + t = {n: p[n] for n in names} + for _ in range(max(1, iterations)): + nxt = {} + for i in names: + propagated = 0.0 + for j in names: + if i == j: + continue + w = jaccard(tools.get(j, set()), tools.get(i, set())) + if w > 0.0: + propagated += w * t[j] + nxt[i] = a * p[i] + (1.0 - a) * propagated + t = nxt + return { + name: { + "trust": round(t[name], 4), + "kept": kept.get(name, 0), + "rolled_back": rolled.get(name, 0), + "tools": len(tools.get(name, ())), + } + for name in sorted(names, key=lambda n: (-t[n], n)) + } + + +def render_advisory(scores: Dict[str, Dict[str, Any]], + signer: Optional[str] = None) -> str: + """The human-facing ADVISORY sentence for the import report. Every + rendering carries the explicit warning that review is NOT skipped — + the trust score never decides anything.""" + if not scores: + return ("advisory: no signer history yet — trust starts at the " + "flat prior; review this diff explicitly (trust never " + "auto-skips review)") + rows = [] + for name, s in scores.items(): + marker = " (this diff)" if signer and name == signer else "" + rows.append(f"{name}{marker}: trust {s['trust']} " + f"({s['kept']} kept, {s['rolled_back']} rolled back)") + return ("advisory signer trust (EigenTrust-style over keep/rollback " + "history and tool overlap — ADVISORY ONLY, review is never " + "auto-skipped): " + "; ".join(rows[:6])) diff --git a/plugins/caelestia-assistant/assistant/core/memory.py b/plugins/caelestia-assistant/assistant/core/memory.py new file mode 100755 index 0000000..9474afa --- /dev/null +++ b/plugins/caelestia-assistant/assistant/core/memory.py @@ -0,0 +1,241 @@ +"""Episodic interaction memory — the cortex's recall layer. + +Every routed request, clarification, and outcome is an EPISODE. Episodes +power three capabilities none of the one-shot layers have: + +1. RECALL — "what did i change last week?", "what do i keep asking + about?" — answered from real interaction history, ranked by an + exponential forgetting curve (Ebbinghaus-style decay; recall weight + ``w = 0.5 ** (age_days / halflife)``) so recent behavior dominates + and old habits fade instead of poisoning the statistics forever. +2. ASSOCIATION — co-change counts: which settings get changed together. + This is market-basket analysis (lift = P(a and b) / (P(a) P(b))) + over the user's own applied episodes. It powers the proactive + follow-up suggestion: after applying ``setBarScale``, the most-lifted + co-occurring setting becomes a LEDGER PROPOSAL (never auto-applied), + e.g. "you usually also tighten spacing when you shrink the bar — + propose setSpacingScale 0.9?" +3. HABITS — surface frequency by hour-of-day and by day-of-week + (plain histograms; ``notable`` deviations reuse the rhythm idea). + +Persistence: the caller passes a plain dict (loaded/saved by the brain +state machinery — same atomic-write path as every other learned model); +this module does no file I/O itself. Bounded: ``MAX_EPISODES`` newest +episodes retained (recall beyond that horizon is honestly refused). +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Dict, List, Optional, Sequence, Tuple + +MAX_EPISODES = 500 +HALFLIFE_DAYS = 14.0 + +# The user-editable override lives in the brain state (key +# MEMORY_HALFLIFE_KEY) — per-user, because usage cadences differ; a +# multi-user/community install each carries its own decay. The shipped +# default is 14 days; `caelestia-assist cortex halflife [DAYS]` reads or +# sets it. This is a correctness fix, not a knob: the default was a +# fixed constant while different users demonstrably need different +# forgetting rates. +MEMORY_HALFLIFE_KEY = "cortex_memory_halflife_days" +HALFLIFE_BOUNDS = (0.5, 365.0) + +OUTCOMES = ("routed", "ambiguous", "abstain", "applied", "approved", "rejected", "clarified", "undone") + + +# --------------------------------------------------------------------------- +# Episode shape (plain dicts in the persistent state, kept in order). +# --------------------------------------------------------------------------- + + +def new_episode(text: str, resolved: str, surfaces: Sequence[str], verdict: str, + outcome: str, at: Optional[datetime] = None) -> Dict[str, object]: + """One recorded interaction. ``at`` defaults to a fixed epoch for + determinism in tests; the service layer stamps the real clock.""" + return { + "text": text, + "resolved": resolved, + "surfaces": list(surfaces), + "verdict": verdict, + "outcome": outcome, + "at": (at or datetime(2026, 1, 1, 12, 0, 0)).isoformat(), + } + + +def _episode_time(episode: Dict[str, object]) -> datetime: + raw = episode.get("at") + try: + return datetime.fromisoformat(str(raw)) + except (TypeError, ValueError): + return datetime(2026, 1, 1, 12, 0, 0) + + +# --------------------------------------------------------------------------- +# Store operations (pure functions over the episode list). +# --------------------------------------------------------------------------- + + +def record(episodes: List[Dict[str, object]], episode: Dict[str, object], + cap: int = MAX_EPISODES) -> List[Dict[str, object]]: + """Append and bound. Returns the new list (caller persists it).""" + out = list(episodes) + out.append(episode) + if len(out) > cap: + out = out[-cap:] + return out + + +def _decay_weight(episode: Dict[str, object], now: datetime, + halflife_days: float = HALFLIFE_DAYS) -> float: + age_days = max(0.0, (now - _episode_time(episode)).total_seconds() / 86400.0) + return 0.5 ** (age_days / max(1e-9, halflife_days)) + + +def resolve_halflife(state: Optional[Dict[str, object]] = None) -> float: + """The effective half-life: the state's user setting when present and + in bounds, else the shipped default. Garbage values degrade to the + default (never a crash, never a negative decay).""" + raw = (state or {}).get(MEMORY_HALFLIFE_KEY) + try: + value = float(raw) + except (TypeError, ValueError): + return HALFLIFE_DAYS + lo, hi = HALFLIFE_BOUNDS + if not (lo <= value <= hi): + return HALFLIFE_DAYS + return value + + +def recall(episodes: Sequence[Dict[str, object]], query: str = "", + now: Optional[datetime] = None, k: int = 10, + halflife_days: float = HALFLIFE_DAYS) -> List[Dict[str, object]]: + """Decay-weighted recall of episodes matching ``query`` (surface-name + or text-substring match; empty query = recent-everything).""" + now = now or datetime(2026, 1, 1, 12, 0, 0) + lowered = query.lower().strip() + scored: List[Tuple[float, Dict[str, object]]] = [] + for episode in episodes: + if lowered: + surfaces = " ".join(str(s) for s in episode.get("surfaces", [])) + text = str(episode.get("text", "")) + " " + str(episode.get("resolved", "")) + if lowered not in surfaces.lower() and lowered not in text.lower(): + continue + scored.append((_decay_weight(episode, now, halflife_days), episode)) + scored.sort(key=lambda pair: (-pair[0], str(pair[1].get("at", "")))) + return [episode for _w, episode in scored[:k]] + + +def cooccurrence(episodes: Sequence[Dict[str, object]], + outcome_filter: Sequence[str] = ("applied", "approved"), + min_count: int = 2) -> Dict[Tuple[str, str], int]: + """Co-change counts between surfaces within single applied episodes.""" + counts: Dict[Tuple[str, str], int] = {} + for episode in episodes: + if episode.get("outcome") not in outcome_filter: + continue + surfaces = sorted(set(str(s) for s in episode.get("surfaces", []))) + for i in range(len(surfaces)): + for j in range(i + 1, len(surfaces)): + pair = (surfaces[i], surfaces[j]) + counts[pair] = counts.get(pair, 0) + 1 + return {pair: n for pair, n in counts.items() if n >= min_count} + + +def lift(coocc: Dict[Tuple[str, str], int], + surface_counts: Dict[str, int], total: int) -> List[Dict[str, object]]: + """Market-basket lift over co-change counts: for each pair, + ``lift = P(a,b) / (P(a) * P(b))`` — pairs lifted above 1 co-occur + more than independence predicts. Sorted descending, top pairs only.""" + out: List[Dict[str, object]] = [] + if total <= 0: + return out + for (a, b), count in coocc.items(): + pa = surface_counts.get(a, 0) / total + pb = surface_counts.get(b, 0) / total + if pa <= 0 or pb <= 0: + continue + pab = count / total + value = pab / (pa * pb) + out.append({"a": a, "b": b, "count": count, "lift": round(value, 3)}) + out.sort(key=lambda row: (-row["lift"], row["a"], row["b"])) + return out + + +def followup_suggestion(episodes: Sequence[Dict[str, object]], just_applied: str, + now: Optional[datetime] = None, min_count: int = 2, + top: int = 3, + halflife_days: float = HALFLIFE_DAYS + ) -> List[Dict[str, object]]: + """The proactive second-brain suggestion: after ``just_applied``, + which settings historically co-changed with it? Decay-weighted, + lift-ranked, and returned as SUGGESTION DATA ONLY — the caller turns + them into ledger proposals (never auto-applies).""" + now = now or datetime(2026, 1, 1, 12, 0, 0) + weighted: Dict[str, float] = {} + counts: Dict[str, int] = {} + for episode in episodes: + if episode.get("outcome") not in ("applied", "approved"): + continue + surfaces = set(str(s) for s in episode.get("surfaces", [])) + if just_applied not in surfaces: + continue + weight = _decay_weight(episode, now, halflife_days) + for surface in surfaces: + if surface == just_applied: + continue + weighted[surface] = weighted.get(surface, 0.0) + weight + counts[surface] = counts.get(surface, 0) + 1 + ranked = [ + {"surface": surface, "weight": round(weighted[surface], 3), "count": counts[surface]} + for surface in weighted if counts[surface] >= min_count + ] + ranked.sort(key=lambda row: (-row["weight"], row["surface"])) + return ranked[:top] + + +def habits(episodes: Sequence[Dict[str, object]]) -> Dict[str, object]: + """Hour-of-day and day-of-week histograms of applied episodes — + when this user actually customizes their shell.""" + hours = [0] * 24 + weekdays = [0] * 7 + for episode in episodes: + if episode.get("outcome") not in ("applied", "approved"): + continue + when = _episode_time(episode) + hours[when.hour] += 1 + weekdays[when.weekday()] += 1 + return {"hours": hours, "weekdays": weekdays, "episodes": len(episodes)} + + +def surface_counts(episodes: Sequence[Dict[str, object]], + outcome_filter: Sequence[str] = ("applied", "approved")) -> Dict[str, int]: + """Frequency count of each surface across applied episodes.""" + counts: Dict[str, int] = {} + for episode in episodes: + if episode.get("outcome") not in outcome_filter: + continue + for surface in set(str(s) for s in episode.get("surfaces", [])): + counts[surface] = counts.get(surface, 0) + 1 + return counts + + +def summarize(episodes: Sequence[Dict[str, object]], now: Optional[datetime] = None) -> Dict[str, object]: + """One-line memory report for the CLI/bridge: totals, top surfaces, + top co-changes, habit peaks.""" + now = now or datetime(2026, 1, 1, 12, 0, 0) + counts = surface_counts(episodes) + top_surfaces = sorted(counts.items(), key=lambda kv: (-kv[1], kv[0]))[:8] + total_applied = sum(counts.values()) + co = cooccurrence(episodes) + lifted = lift(co, counts, max(1, len([e for e in episodes if e.get("outcome") in ("applied", "approved")]))) + habit = habits(episodes) + peak_hour = max(range(24), key=lambda h: habit["hours"][h]) if any(habit["hours"]) else None + return { + "episodes": len(episodes), + "applied_episodes": total_applied, + "top_surfaces": [{"surface": s, "count": n} for s, n in top_surfaces], + "top_cochanges": lifted[:5], + "peak_hour": peak_hour, + } diff --git a/plugins/caelestia-assistant/assistant/core/numpy_accel.py b/plugins/caelestia-assistant/assistant/core/numpy_accel.py new file mode 100644 index 0000000..08858b7 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/core/numpy_accel.py @@ -0,0 +1,81 @@ +"""core.numpy_accel — optional numpy accelerator with a pure-Python +fallback. THE CONTRACT: both paths return IDENTICAL results on the +same inputs (pinned by tests/test_numpy_accel.py). numpy is never +imported at module scope by callers unless they opt in via +have_numpy(); the pure path is always available. +""" +from __future__ import annotations + +import math +from typing import List, Optional, Sequence, Tuple + +__all__ = ["have_numpy", "cosine_topk", "mean_pool"] + +_np = None +_checked = False + + +def have_numpy() -> bool: + """Feature-detect numpy once; safe to call repeatedly.""" + global _np, _checked + if not _checked: + try: + import numpy as _candidate # optional extra, never required + _np = _candidate + except ImportError: + _np = None + _checked = True + return _np is not None + + +def cosine_topk( + query: Sequence[float], + matrix: Sequence[Sequence[float]], + k: int, +) -> List[Tuple[int, float]]: + """Top-k (index, cosine) pairs, descending. Identical results on + both paths: same tie-breaking (stable by index), same float values + for the pure path; the numpy path matches to 1e-9 and the test + pins exact equality of the returned ORDER and (rounded) scores.""" + n = len(matrix) + if n == 0: + return [] + qnorm = math.sqrt(sum(x * x for x in query)) or 1.0 + if have_numpy() and k < n: + q = _np.asarray(query, dtype=_np.float64) + m = _np.asarray(matrix, dtype=_np.float64) + qn = _np.linalg.norm(q) or 1.0 + mn = _np.linalg.norm(m, axis=1) + mn[mn == 0] = 1.0 + sims = (m @ q) / (mn * qn) + k_eff = min(k, n) + idx = _np.argpartition(-sims, k_eff - 1)[:k_eff] + idx = idx[_np.argsort(-sims[idx], kind="stable")] + return [(int(i), float(sims[i])) for i in idx] + scored = [] + for i, row in enumerate(matrix): + rnorm = math.sqrt(sum(x * x for x in row)) or 1.0 + num = sum(a * b for a, b in zip(query, row)) + scored.append((i, num / (rnorm * qnorm))) + scored.sort(key=lambda t: -t[1]) + return scored[:k] + + +def mean_pool(rows: Sequence[Sequence[float]], + weights: Optional[Sequence[float]] = None) -> List[float]: + """Weighted mean pooling. Identical semantics on both paths.""" + if not rows: + return [] + dim = len(rows[0]) + if weights is None: + weights = [1.0] * len(rows) + total = sum(weights) or 1.0 + if have_numpy(): + m = _np.asarray(rows, dtype=_np.float64) + w = _np.asarray(weights, dtype=_np.float64) + return [float(x) for x in (m * w[:, None]).sum(axis=0) / total] + out = [0.0] * dim + for row, w in zip(rows, weights): + for j, x in enumerate(row): + out[j] += x * w + return [x / total for x in out] diff --git a/plugins/caelestia-assistant/assistant/core/phonetics.py b/plugins/caelestia-assistant/assistant/core/phonetics.py new file mode 100644 index 0000000..97c2093 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/core/phonetics.py @@ -0,0 +1,67 @@ +"""core.phonetics — deterministic soundex-style keys + char-ngram sets. + +Capability-1 (sealed-gap) feature: phonetic matching lets "kwin +activewindow bridge"-style mishearings and typo'd tool atoms +("transparancy") still reach the right tool WITHOUT widening the +lexical channel for everything else. Pure functions, stdlib only. +""" +from __future__ import annotations + +import re +from typing import Dict, Set + +__all__ = ["soundex", "char_ngrams", "phonetic_hit_rate"] + +_LETTER_CODE = { + **{c: "1" for c in "BFPV"}, + **{c: "2" for c in "CGJKQSXZ"}, + **{c: "3" for c in "DT"}, + "L": "4", + **{c: "5" for c in "MN"}, + "R": "6", +} +_NON_CODE = re.compile(r"[AEIOUYHW]", re.I) + + +def soundex(word: str) -> str: + """Classic soundex, bounded to 4 chars. Deterministic; empty for + strings with no letters (digits/punct never produce keys).""" + word = re.sub(r"[^A-Za-z]", "", word).upper() + if not word: + return "" + first = word[0] + coded = [] + prev = _LETTER_CODE.get(first, "") + for ch in word[1:]: + code = _LETTER_CODE.get(ch, "") + if ch in "HW": + continue # H/W do not reset the previous code + if code and code != prev: + coded.append(code) + prev = code + return (first + "".join(coded) + "000")[:4] + + +def char_ngrams(text: str, n: int = 3) -> Set[str]: + """Lowercased padded character n-grams (the same normalization the + fuzz channel uses, exposed for the mining scripts and tests).""" + text = re.sub(r"\s+", " ", text.lower()).strip() + if len(text) < n: + return {text} if text else set() + padded = f" {text} " + return {padded[i:i + n] for i in range(len(padded) - n + 1)} + + +def phonetic_hit_rate(query_tokens, atom_tokens) -> float: + """Fraction of the query's content tokens whose soundex key matches + ANY atom token's key. 0.0 when the query has no phonetic content — + digits and one/two-letter tokens never match, so pure-value requests + ('bar 34') keep their honest 0.0.""" + q_keys = [soundex(t) for t in query_tokens + if len(t) > 2 and re.search(r"[A-Za-z]", t)] + q_keys = [k for k in q_keys if k] + a_keys = {soundex(a) for a in atom_tokens} - {""} + if not q_keys or not a_keys: + return 0.0 + hits = sum(1 for k in q_keys if k in a_keys) + return hits / len(q_keys) diff --git a/plugins/caelestia-assistant/assistant/core/slot_tagger.py b/plugins/caelestia-assistant/assistant/core/slot_tagger.py new file mode 100644 index 0000000..08ba99f --- /dev/null +++ b/plugins/caelestia-assistant/assistant/core/slot_tagger.py @@ -0,0 +1,452 @@ +"""cortex.slot_tagger — a LEARNED slot tagger layered on the existing +grammar, never replacing it. + +What exists already (grep-first, none of it replaced): +- ``settings/slots.py`` — the compositional slot grammar + ``{intensifier, target, direction, dimension}`` (regex-compositional, + pure, honest declines); +- ``cortex/lexicon.py::char_ngrams`` — the char 3-gram features the + router already uses for unknown words; +- ``cortex/conformal.py::ConformalCalibrator`` — the split-conformal + gate over scores ("routes at or above t were accepted >= 1-alpha of + the time"), the repo's one uncertainty mechanism. + +The gap this closes: the grammar matches PHRASE LISTS; a phrasing it +never saw ("bar a smidge shorter, please") falls through. This module +trains a structured perceptron (Collins 2002, "Discriminative Training +Methods for Hidden Markov Models: Theory and Experiments with +Perceptron Algorithms", EMNLP) with Viterbi decoding and averaged +weights to tag token-level BIO slots, using ONLY local approve/reject +history — the same source cortex/learn.py trains from. No external +corpus exists anywhere in this module: + +- APPROVED requests supervise: the gold BIO sequence is read off the + EXISTING grammar's own output (slots.extract()'s matched raws; an + optional caller-supplied noun matcher supplies TARGET spans) — the + tagger distills the grammar the user actually accepted; +- REJECTED requests supervise NOTHING here (a request the user refused + is not evidence of correct slot structure; it is skipped, never + fabricated into a negative sequence). + +The gate (the safety property): a 2-best Viterbi margin (the standard +N-best extension, Forney 1973) becomes the tagger's confidence, and the +conformal calibrator decides whether that confidence is covered. Not +covered — or NO calibration data at all — and the request falls back to +the existing grammar/char-ngram path with the calibrator's own reason +string attached. The tagger adds coverage; it never guesses. + +Pure: no I/O, no clock, no randomness (fixed update order, averaged +weights); identical input bytes -> identical output. Persistence is a +plain dict for the caller to store in learned-state JSON (an existing +write path); this module writes nothing. +""" +from __future__ import annotations + +import math +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple + +from .conformal import ConformalCalibrator +from .lexicon import char_ngrams + +__all__ = ["TAGS", "SlotTagger", "supervision_from_history", "MAX_TOKENS"] + +# BIO tag set over the slots the existing grammar reports raw spans for +# (the intensifier kind has no raw span in slots.extract()'s output, so +# it stays outside the tag set rather than being guessed). +_TAGS = ["O"] +for _kind in ("CUE", "GENERIC", "TARGET"): + _TAGS.append(f"B-{_kind}") + _TAGS.append(f"I-{_kind}") +TAGS: Tuple[str, ...] = tuple(_TAGS) + +MAX_TOKENS = 64 # a settings request is a sentence, not a paragraph + +_WORD_RE = re.compile(r"[^\s]+") + + +def _tokenize_with_offsets(text: str) -> List[Tuple[str, int, int]]: + out: List[Tuple[str, int, int]] = [] + for m in _WORD_RE.finditer(text): + raw = m.group(0) + out.append((raw.strip(".,!?:;()\"'"), m.start(), m.end())) + return [(w, a, b) for (w, a, b) in out if w] + + +def _shape(word: str) -> str: + if word.isdigit(): + return "" + if any(c.isupper() for c in word): + return "" + return "" + + +# --------------------------------------------------------------------------- +# The structured perceptron (Collins 2002; 2-best Viterbi, Forney 1973). +# --------------------------------------------------------------------------- + +class SlotTagger: + """Averaged structured perceptron over BIO slot tags. + + Features per position i: the word (lowercased), its shape, 2 + prefixes/2 suffixes, its char 3-grams (lexicon.char_ngrams — the + router's own unknown-word feature), the previous and next words, and + the (previous tag, tag) transition. Deterministic end to end.""" + + def __init__(self, data: Optional[Dict[str, Any]] = None): + data = data if isinstance(data, dict) else {} + self.weights: Dict[str, Dict[str, float]] = { + tag: {} for tag in TAGS} + self._totals: Dict[str, Dict[str, float]] = { + tag: {} for tag in TAGS} + self._steps = 0 + self.updates = int(data.get("updates", 0)) + self.trained_examples = int(data.get("trained_examples", 0)) + saved = data.get("weights") or {} + for tag, feats in saved.items(): + if tag in self.weights and isinstance(feats, dict): + self.weights[tag] = {str(k): float(v) + for k, v in feats.items()} + self._averaged_cache: Optional[Dict[str, Dict[str, float]]] = None + + # -- features ------------------------------------------------------------- + + def _features(self, tokens: List[str], i: int, + prev_tag: str) -> List[str]: + w = tokens[i].lower() + feats = [ + f"w={w}", + f"shape={_shape(tokens[i])}", + f"p1={w[:2]}", f"p2={w[:3]}", + f"s1={w[-2:]}", f"s2={w[-3:]}", + f"prev={tokens[i - 1].lower() if i else ''}", + f"next={tokens[i + 1].lower() if i + 1 < len(tokens) else ''}", + f"pt={prev_tag}", + ] + for g in char_ngrams(w, 3): + feats.append(f"ng={g}") + return feats + + def _score_tag(self, feats: List[str], tag: str, + use_averaged: bool) -> float: + table = (self._averaged() if use_averaged else self.weights)[tag] + return sum(table.get(f, 0.0) for f in feats) + + # -- decoding (2-best Viterbi) -------------------------------------------- + + def _viterbi_2best(self, tokens: List[str], use_averaged: bool = True + ) -> Tuple[float, List[str], float, List[str]]: + """Return (best score, best tags, second-best score, + second-best tags). Standard 2-best Viterbi with a deterministic + tie-break (tag order in TAGS).""" + n = len(tokens) + # chart[node] = list of (score, tags, tag_at_node) best-first + chart: List[Dict[str, List[Tuple[float, List[str], str]]]] = [ + {} for _ in range(n)] + for tag in TAGS: + feats = self._features(tokens, 0, "O") + score = self._score_tag(feats, tag, use_averaged=use_averaged) + chart[0][tag] = [(score, [tag], tag)] + for i in range(1, n): + for tag in TAGS: + scored: List[Tuple[float, List[str], str]] = [] + for prev in TAGS: + feats = self._features(tokens, i, prev) + base = self._score_tag(feats, tag, + use_averaged=use_averaged) + for (pscore, ptags, _p) in chart[i - 1][prev]: + scored.append((pscore + base, ptags + [tag], tag)) + scored.sort(key=lambda t: (-t[0], t[1])) + chart[i][tag] = scored[:2] + finals: List[Tuple[float, List[str], str]] = [] + for tag in TAGS: + finals.extend(chart[n - 1][tag]) + finals.sort(key=lambda t: (-t[0], t[1])) + # merge duplicate tag sequences (2-best per node can collide) + seen = set() + uniq: List[Tuple[float, List[str], str]] = [] + for score, tags, _ in finals: + key = tuple(tags) + if key not in seen: + seen.add(key) + uniq.append((score, tags, tags[-1] if tags else "O")) + if len(uniq) == 2: + break + while len(uniq) < 2: + uniq.append((-math.inf, ["O"] * n, "O")) + s1, t1, _ = uniq[0] + s2, t2, _ = uniq[1] + return s1, t1, s2, t2 + + # -- public API ----------------------------------------------------------- + + def tag(self, text: str, use_averaged: bool = True) -> Dict[str, Any]: + """Tag one request; returns tags, spans and the 2-best margin. + Inference decodes with the AVERAGED weights; training updates + decode with the current weights (Collins 2002's own split).""" + tokens = [w for w, _a, _b in _tokenize_with_offsets(text)] + if not tokens: + return {"tags": [], "spans": {}, "confidence": None, + "margin": None} + if len(tokens) > MAX_TOKENS: + raise ValueError( + f"request has {len(tokens)} tokens; the tagger accepts at " + f"most {MAX_TOKENS} (rejected, never truncated)") + s1, best, s2, _second = self._viterbi_2best(tokens, use_averaged) + margin = s1 - s2 + confidence = _margin_confidence(margin, len(tokens)) + return {"tags": best, "spans": _spans_of(best, tokens), + "confidence": confidence, "margin": round(margin, 4)} + + def update(self, text: str, gold_tags: List[str]) -> bool: + """One perceptron update against a gold sequence (Collins 2002: + w += phi(x, gold) - phi(x, predicted)). Returns True when the + prediction was wrong (the update changed something).""" + tokens = [w for w, _a, _b in _tokenize_with_offsets(text)] + if len(tokens) != len(gold_tags): + raise ValueError("gold tag sequence must align with tokens") + if any(t not in TAGS for t in gold_tags): + raise ValueError(f"unknown tag in {gold_tags!r}") + pred = self.tag(text, use_averaged=False)["tags"] + wrong = pred != gold_tags + self._steps += 1 + prev_g = prev_p = "O" + for i in range(len(tokens)): + fg = self._features(tokens, i, prev_g) + fp = self._features(tokens, i, prev_p) + if gold_tags[i] != pred[i] or fg != fp: + for f in fg: + self._bump(gold_tags[i], f, +1.0) + for f in fp: + self._bump(pred[i], f, -1.0) + prev_g, prev_p = gold_tags[i], pred[i] + self.updates += 1 + self.trained_examples += 1 + self._averaged_cache = None + return wrong + + def train(self, rows: Sequence[Tuple[str, List[str]]], + epochs: int = 12) -> int: + """Deterministic multi-epoch training over (text, gold) rows: + fixed row order, full pass each epoch, early stop when an epoch + makes no mistakes (the perceptron convergence guarantee — the + data is separable by construction, being the grammar's own + labels). Returns the number of epochs actually run.""" + rows = list(rows) + if not rows: + return 0 + for epoch in range(1, max(1, epochs) + 1): + mistakes = sum(1 for text, gold in rows if self.update(text, gold)) + if mistakes == 0: + return epoch + return max(1, epochs) + + def _bump(self, tag: str, feature: str, delta: float) -> None: + w = self.weights[tag].get(feature, 0.0) + delta + self.weights[tag][feature] = w + t = self._totals[tag].get(feature, 0.0) + self._steps * delta + self._totals[tag][feature] = t + + def _averaged(self) -> Dict[str, Dict[str, float]]: + """Averaged weights (Collins 2002 section 3.3): w_avg = w_total/t. + Cached because decoding reads every feature.""" + if self._averaged_cache is not None: + return self._averaged_cache + if self._steps == 0: + self._averaged_cache = self.weights + return self._averaged_cache + avg: Dict[str, Dict[str, float]] = {} + for tag in TAGS: + table = dict(self.weights[tag]) + for f, total in self._totals[tag].items(): + table[f] = total / self._steps + avg[tag] = table + self._averaged_cache = avg + return self._averaged_cache + + # -- persistence (learned-state JSON; the caller writes it) --------------- + + def to_dict(self) -> Dict[str, Any]: + return {"weights": {t: dict(self.weights[t]) for t in self.weights}, + "totals": {t: dict(self._totals[t]) for t in self._totals}, + "steps": self._steps, + "updates": self.updates, + "trained_examples": self.trained_examples} + + @classmethod + def from_dict(cls, data: Optional[Dict[str, Any]]) -> "SlotTagger": + tagger = cls() + data = data if isinstance(data, dict) else {} + saved = data.get("weights") or {} + for tag, feats in saved.items(): + if tag in tagger.weights and isinstance(feats, dict): + tagger.weights[tag] = {str(k): float(v) + for k, v in feats.items()} + saved_totals = data.get("totals") or {} + for tag, feats in saved_totals.items(): + if tag in tagger._totals and isinstance(feats, dict): + tagger._totals[tag] = {str(k): float(v) + for k, v in feats.items()} + tagger._steps = int(data.get("steps", 0)) + tagger.updates = int(data.get("updates", 0)) + tagger.trained_examples = int(data.get("trained_examples", 0)) + tagger._averaged_cache = None + return tagger + + +def _margin_confidence(margin: float, n_tokens: int) -> float: + """2-best margin -> (0, 1) confidence through a fixed-scale logistic: + monotone, deterministic, never claims certainty (the same transform + class fusion.py documents; gamma pinned so a per-token gap of ~1.0 + is already confident).""" + gamma = 2.0 + scaled = gamma * margin / max(1, n_tokens) + return _sigmoid(scaled) + + +def _sigmoid(x: float) -> float: + return 1.0 / (1.0 + math.exp(-x)) + + +def _spans_of(tags: List[str], tokens: List[str]) -> Dict[str, Any]: + spans: Dict[str, List[Dict[str, Any]]] = {} + i = 0 + while i < len(tags): + tag = tags[i] + if tag == "O": + i += 1 + continue + kind = tag.split("-", 1)[1] + j = i + while (j + 1 < len(tags) + and tags[j + 1] == f"I-{kind}"): + j += 1 + spans.setdefault(kind, []).append({ + "tokens": [i, j], "raw": " ".join(tokens[i:j + 1])}) + i = j + 1 + return spans + + +# --------------------------------------------------------------------------- +# Supervision from LOCAL history only (the cortex/learn.py data source). +# --------------------------------------------------------------------------- + +def supervision_from_history(examples: Sequence[Dict[str, Any]], + noun_matcher: Optional[Callable[ + [str], Sequence[str]]] = None, + grammar_extract=None) -> List[Dict[str, Any]]: + """Turn approved history rows into gold BIO sequences. + + ``examples``: cortex/learn.py's own example rows ({text, label, + outcome, ...}). ONLY approved rows (label 1 / outcome applied or + approved) supervise; rejected or undecided rows are skipped — a + refused request says nothing about slot structure. Gold spans are + read off the EXISTING grammar: settings/slots.extract()'s own + matched raws (cue + generic), plus TARGET spans when the caller + supplies a noun matcher (e.g. the parser's noun matching). Requests + the grammar cannot label at all produce no supervision — nothing is + guessed to fill the gap.""" + if grammar_extract is None: + from assistant.capabilities.settings import slots as _slots + grammar_extract = _slots.extract + + out: List[Dict[str, Any]] = [] + for row in examples: + if not isinstance(row, dict): + continue + approved = (row.get("label") == 1 + or row.get("outcome") in ("applied", "approved")) + if not approved: + continue + text = str(row.get("text", "")) + tokens = _tokenize_with_offsets(text) + if not tokens: + continue + slots = grammar_extract(text) + tags = ["O"] * len(tokens) + tagged = False + for slot_key, kind in (("cue", "CUE"), ("generic", "GENERIC")): + raw = (slots.get(slot_key) or {}).get("raw") + if raw: + if _tag_raw(raw, text, tokens, tags, kind): + tagged = True + if noun_matcher is not None: + for noun in (noun_matcher(text) or []): + if _tag_raw(str(noun), text, tokens, tags, "TARGET"): + tagged = True + if tagged: + out.append({"text": text, + "tokens": [w for w, _a, _b in tokens], + "tags": tags}) + return out + + +def _tag_raw(raw: str, text: str, tokens, tags: List[str], kind: str + ) -> bool: + """Span one grammar raw string onto the token index list (first + match). Returns True when something was tagged.""" + needle = raw.lower() + words = [w.lower() for w, _a, _b in tokens] + n = len(needle.split()) + for start in range(len(words) - n + 1): + if " ".join(words[start:start + n]) == needle: + tags[start] = f"B-{kind}" + for k in range(start + 1, start + n): + tags[k] = f"I-{kind}" + return True + return False + + +# --------------------------------------------------------------------------- +# The gated entry point: tagger first, grammar fallback on low confidence. +# --------------------------------------------------------------------------- + +def tag_gated(text: str, + tagger: SlotTagger, + calibrator: Optional[ConformalCalibrator] = None, + noun_matcher: Optional[Callable[[str], Sequence[str]]] = None + ) -> Dict[str, Any]: + """One request, one answer, one honest path label. + + - the tagger answers when it is trained AND the conformal calibrator + (with actual calibration data) covers its confidence; + - everything else — untrained tagger, confidence below the conformal + threshold, or NO calibration data at all — falls back to the + EXISTING grammar path (settings/slots.extract, the char-ngram + layer's own machinery), carrying the calibrator's own reason. + """ + if tagger.trained_examples == 0 or not any(tagger.weights[t] + for t in TAGS): + return _grammar_fallback(text, "tagger untrained", + calibrator=calibrator, + noun_matcher=noun_matcher) + result = tagger.tag(text) + confidence = result.get("confidence") + if confidence is None or not result["spans"]: + return _grammar_fallback(text, "tagger found no slot structure", + calibrator=calibrator, + noun_matcher=noun_matcher) + verdict = (calibrator.verdict(confidence) + if calibrator is not None and calibrator.scores + else {"covered": None, + "reason": ("insufficient calibration data — no " + "distribution-free claim available")}) + if verdict.get("covered") is not True: + return _grammar_fallback(text, str(verdict.get("reason")), + calibrator=calibrator, + noun_matcher=noun_matcher) + result.update({"used": "tagger", "conformal": verdict.get("reason")}) + return result + + +def _grammar_fallback(text: str, reason: str, + calibrator: Optional[ConformalCalibrator] = None, + noun_matcher: Optional[Callable[ + [str], Sequence[str]]] = None) -> Dict[str, Any]: + """The EXISTING grammar/char-ngram path, unchanged and verbatim.""" + from assistant.capabilities.settings import slots as _slots + + slots = _slots.extract(text) + targets = list(noun_matcher(text) or []) if noun_matcher else [] + return {"used": "grammar-fallback", "reason": reason, + "slots": slots, "targets": targets} diff --git a/plugins/caelestia-assistant/assistant/core/tree.py b/plugins/caelestia-assistant/assistant/core/tree.py new file mode 100644 index 0000000..208ae49 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/core/tree.py @@ -0,0 +1,220 @@ +"""cortex.tree — a CART decision tree beside the logistic router (§6.3). + +The learner's online logistic regression (learn.py) is accurate but its +verdict is a weight vector: "why did it route here" is five signed numbers. +This module grows the SAME decision on the SAME five features +(lex / sem / fuzz / noun / cue-kind agreement) as a CART classification +tree (Breiman, Friedman, Olshen & Stone 1984, "Classification and +Regression Trees", Wadsworth: binary recursive partitioning, Gini +impurity, midpoint thresholds) — a verdict path you can READ: + + lex >= 0.45 + noun < 0.20 -> reject (0.92 impure, n=41) + noun >= 0.20 -> accept (0.05, n=118) + +Placement — complement, not replacement: the tree never replaces the +logistic router anywhere in the pipeline. It trains from the learner's +own bounded example log (the audit trail the learner already keeps), +answers the same accept/reject question, and reports its agreement with +the fitted logistic model BEFORE anyone decides whether to promote it to +a real verdict path (``agreement_report`` below; the numbers it produced +on the shipped corpus are in the CHANGELOG entry, not in a promise). + +Deterministic: ties broken by feature order then threshold value, no +randomness anywhere. Bounded: depth and leaf-size caps are hard stops. +""" + +from __future__ import annotations + +from typing import Any, Dict, List, Optional, Sequence, Tuple + +from .learn import _FEATURES + +__all__ = ["gini", "build_tree", "tree_classify", "tree_from_examples", + "tree_to_rules", "agreement_report", "MAX_DEPTH", "MIN_LEAF"] + +# Readability-first caps: a tree deeper than this stops being an +# explanation and starts being a model. +MAX_DEPTH = 3 +MIN_LEAF = 5 + + +def gini(labels: Sequence[int]) -> float: + """Gini impurity of a label multiset: 1 - sum(p_k^2).""" + n = len(labels) + if n == 0: + return 0.0 + counts: Dict[int, int] = {} + for label in labels: + counts[label] = counts.get(label, 0) + 1 + return 1.0 - sum((c / n) ** 2 for c in counts.values()) + + +def _best_split(rows: List[Sequence[float]], labels: List[int] + ) -> Optional[Tuple[int, float, float]]: + """The (feature index, threshold, weighted impurity) minimizing the + children's impurity, or None when no split helps. Candidate thresholds + are midpoints between consecutive distinct sorted values — CART's own + convention; ties break on feature order then threshold.""" + n = len(labels) + parent = gini(labels) + n_features = len(rows[0]) if rows else 0 + best: Optional[Tuple[int, float, float]] = None + for feature in range(n_features): + pairs = sorted(set(row[feature] for row in rows)) + for a, b in zip(pairs, pairs[1:]): + threshold = (a + b) / 2.0 + left = [labels[i] for i in range(n) if rows[i][feature] < threshold] + right = [labels[i] for i in range(n) if rows[i][feature] >= threshold] + if not left or not right: + continue + weighted = (len(left) * gini(left) + len(right) * gini(right)) / n + if best is None or weighted < best[2] - 1e-12: + best = (feature, threshold, weighted) + if best is not None and best[2] >= parent - 1e-12: + return None # no split improves impurity + return best + + +def build_tree(rows: List[Sequence[float]], labels: List[int], + depth: int = 0, max_depth: int = MAX_DEPTH, + min_leaf: int = MIN_LEAF) -> Dict[str, Any]: + """Grow the CART tree over (features, labels); returns a nested dict + {leaf: True, prediction, distribution, n} or + {leaf: False, feature, name, threshold, left, right, n}.""" + n = len(labels) + counts: Dict[int, int] = {} + for label in labels: + counts[label] = counts.get(label, 0) + 1 + majority = max(sorted(counts), key=lambda k: counts[k]) + leaf = {"leaf": True, "prediction": majority, + "distribution": {str(k): v for k, v in sorted(counts.items())}, + "impurity": round(gini(labels), 4), "n": n} + if depth >= max_depth or n < 2 * min_leaf or gini(labels) == 0.0: + return leaf + split = _best_split(rows, labels) + if split is None: + return leaf + feature, threshold, _weighted = split + left_rows = [rows[i] for i in range(n) if rows[i][feature] < threshold] + left_labels = [labels[i] for i in range(n) if rows[i][feature] < threshold] + right_rows = [rows[i] for i in range(n) if rows[i][feature] >= threshold] + right_labels = [labels[i] for i in range(n) if rows[i][feature] >= threshold] + if len(left_labels) < min_leaf or len(right_labels) < min_leaf: + return leaf + return { + "leaf": False, + "feature": feature, + "name": _FEATURES[feature] if feature < len(_FEATURES) else f"f{feature}", + "threshold": round(threshold, 6), + "left": build_tree(left_rows, left_labels, depth + 1, max_depth, min_leaf), + "right": build_tree(right_rows, right_labels, depth + 1, max_depth, min_leaf), + "n": n, + } + + +def tree_classify(tree: Dict[str, Any], + features: Dict[str, float]) -> Tuple[int, List[str]]: + """Walk the tree; returns (prediction, the readable path taken).""" + path: List[str] = [] + node = tree + while not node.get("leaf"): + name = node["name"] + value = float(features.get(name, 0.0)) + go_left = value < node["threshold"] + path.append(f"{name} {'<' if go_left else '>='} {node['threshold']}") + node = node["left"] if go_left else node["right"] + path.append(f"-> {'accept' if node['prediction'] == 1 else 'reject'} " + f"(impurity {node['impurity']}, n={node['n']})") + return int(node["prediction"]), path + + +def tree_from_examples(examples: Sequence[Dict[str, Any]], + max_depth: int = MAX_DEPTH, + min_leaf: int = MIN_LEAF) -> Optional[Dict[str, Any]]: + """Train the tree on the learner's example log rows ({features, + label}); None when there are too few examples to split honestly + (the tree says nothing rather than guessing from thin air).""" + rows = [[float(e.get("features", {}).get(name, 0.0)) + for name in _FEATURES] + for e in examples if isinstance(e, dict) and "label" in e] + labels = [int(e["label"]) for e in examples + if isinstance(e, dict) and "label" in e] + if len(labels) < 2 * min_leaf: + return None + return build_tree(rows, labels, max_depth=max_depth, min_leaf=min_leaf) + + +def tree_to_rules(tree: Dict[str, Any], prefix: str = "") -> List[str]: + """Render every root-to-leaf path as one readable rule line.""" + if tree.get("leaf"): + prediction = "accept" if tree["prediction"] == 1 else "reject" + return [f"{prefix or 'always'} -> {prediction} " + f"(impurity {tree['impurity']}, n={tree['n']})"] + out: List[str] = [] + out.extend(tree_to_rules(tree["left"], + f"{prefix} and {tree['name']} < {tree['threshold']}" + if prefix else f"{tree['name']} < {tree['threshold']}")) + out.extend(tree_to_rules(tree["right"], + f"{prefix} and {tree['name']} >= {tree['threshold']}" + if prefix else f"{tree['name']} >= {tree['threshold']}")) + return [line.lstrip(" and ").replace("always and ", "") + for line in out] + + +def agreement_report(examples: Sequence[Dict[str, Any]], *, + test_fraction: float = 0.3, + max_depth: int = MAX_DEPTH, + min_leaf: int = MIN_LEAF) -> Optional[Dict[str, Any]]: + """Train the CART tree AND the logistic model on a training split of + the labeled examples, then measure how often they agree on the held-out + rest — the number that decides whether the tree is worth promoting to + a real verdict path. Deterministic split (every 3rd example held out + by position, no RNG). Returns None with too few examples to say + anything honest.""" + usable = [e for e in examples if isinstance(e, dict) and "label" in e] + if len(usable) < 4 * MIN_LEAF: + return None + stride = max(2, round(1.0 / test_fraction)) + train = [e for i, e in enumerate(usable) if i % stride != 0] + test = [e for i, e in enumerate(usable) if i % stride == 0] + if not train or not test: + return None + + tree = tree_from_examples(train, max_depth=max_depth, min_leaf=min_leaf) + from .learn import OnlineLogistic + model = OnlineLogistic() + # a fair fit, not a single undertrained pass: the same example log the + # learner itself replays; five epochs is where the online AdaGrad + # model stabilizes on corpora of this size (the learner itself sees + # each example exactly once per session and sessions repeat) + for _epoch in range(5): + for e in train: + model.update(e.get("features", {}), int(e["label"])) + if tree is None: + return None + + def _agree(rows: List[Dict[str, Any]]) -> Tuple[int, int]: + agree = 0 + for e in rows: + tree_label, _path = tree_classify(tree, e.get("features", {})) + logi_label = 1 if model.predict(e.get("features", {})) >= 0.5 else 0 + if tree_label == logi_label: + agree += 1 + return agree, len(rows) + + train_agree, train_n = _agree(train) + test_agree, test_n = _agree(test) + tree_right = sum(1 for e in test + if tree_classify(tree, e.get("features", {}))[0] == int(e["label"])) + logi_right = sum(1 for e in test + if (1 if model.predict(e.get("features", {})) >= 0.5 else 0) + == int(e["label"])) + return { + "n_train": train_n, "n_test": test_n, + "train_agreement": round(train_agree / max(1, train_n), 3), + "test_agreement": round(test_agree / max(1, test_n), 3), + "tree_test_accuracy": round(tree_right / max(1, test_n), 3), + "logistic_test_accuracy": round(logi_right / max(1, test_n), 3), + "rules": tree_to_rules(tree), + } diff --git a/plugins/caelestia-assistant/assistant/core/vectorize.py b/plugins/caelestia-assistant/assistant/core/vectorize.py new file mode 100755 index 0000000..ea854c0 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/core/vectorize.py @@ -0,0 +1,680 @@ +"""Lean semantic vectorization for the cortex router. + +Two classical engines, both deterministic, both stdlib-only: + +1. ``TfidfIndex`` — an Okapi BM25+ index (with the lower-bound ``delta`` + that keeps long documents from saturating) over the synthetic corpus + documents. This is the LEXICAL half of the router's score: exact and + stemmed word overlap between the user's phrase and each surface's + document. + +2. ``PpmiEmbedder`` — distributional word vectors: PPMI co-occurrence + matrix (positive pointwise mutual information) reduced by sparse + random projection (Achlioptas' {-1, 0, +1} matrix, the + Johnson-Lindenstrauss guarantee that pairwise distances survive the + reduction), then row-normalized. A text embeds as the sublinear-tf + weighted average of its word vectors. This is the SEMANTIC half: it + puts user vocabulary and registry vocabulary that co-occur in the + same phrase-doc pairs near each other in cosine space, so "make it + see-through-ish" lands near the transparency tools without anyone + hand-listing that synonym. + +This is deliberately the "poor man's word2vec" — explicit, auditable +arithmetic replacing a neural embedding. It cannot hallucinate: a word +absent from the corpus has a zero vector and contributes nothing. + +Determinism: the projection matrix is drawn from ``random.Random(seed)`` +with a FIXED default seed, so every build of the same corpus produces +bit-identical vectors. No clock, no os randomness, no I/O. +""" + +from __future__ import annotations + +import math +import random +from collections import Counter +from typing import Dict, Iterable, List, Sequence, Tuple + +from .corpus import all_rows, tool_documents +from .lexicon import stem + +# --------------------------------------------------------------------------- +# Tokenization shared by both engines (stemmed, stopworded). +# --------------------------------------------------------------------------- + +_STOPWORDS = frozenset({ + "a", "an", "the", "my", "me", "i", "please", "could", "would", "can", + "to", "of", "for", "and", "or", "but", "with", "at", "by", "in", "on", + "is", "are", "was", "be", "been", "am", "do", "does", "did", "so", + "just", "like", "want", "wants", "need", "needs", "it", "its", "this", + "that", "these", "those", "there", "here", "you", "your", "up", "out", + "make", "makes", "making", "set", "sets", "setting", "get", "gets", + "change", "changes", "changing", "adjust", "adjusts", "turn", "turns", + "put", "puts", "give", "gives", "apply", "applies", "bit", "little", + "slightly", "somewhat", "more", "most", "less", "least", "much", + "look", "looks", "feel", "feels", "feeling", "everything", "keep", + "keeps", "overall", "style", "vibe", "stuff", "thing", "things", + "too", "very", "really", "kind", "sort", "now", "then", "still", + "see", "through", "move", "moves", "moving", "want", "wanted", +}) + +_MINUS_STOP = frozenset({"it", "that", "this", "them", "those"}) # pronouns session.py resolves + +# A2 constants (see the PPMI+SVD section further down): the SVD seed and +# the supervised-pair weight above the corpus prior. +SVD_SEED = 0x20260926 +LABEL_WEIGHT = 4.0 # one supervised pair = four corpus rows of evidence + + +def tokenize(text: str, keep_pronouns: bool = False) -> List[str]: + """Stemmed, stopword-filtered word list. Pronouns are normally + dropped here (they carry no target information); ``session.py`` + re-injects resolved ones itself, so it passes keep_pronouns=True.""" + raw = [w for w in text.lower().replace("-", " ").split() if w] + out: List[str] = [] + for w in raw: + if not w.isalpha() and not w.isdigit(): + w = "".join(ch for ch in w if ch.isalpha()) + if not w: + continue + if not keep_pronouns and w in _MINUS_STOP: + continue + if w in _STOPWORDS and not (keep_pronouns and w in _MINUS_STOP): + continue + s = stem(w) + if s and (s not in _STOPWORDS or (keep_pronouns and s in _MINUS_STOP)): + out.append(s) + return out + + +# --------------------------------------------------------------------------- +# BM25+ lexical index. +# --------------------------------------------------------------------------- + + +class TfidfIndex: + """Okapi BM25+ (k1=1.5, b=0.75, delta=1.0) over {key: document}. + + Pure in-memory, built once per process from the synthetic corpus. + ``score`` returns the BM25+ sum for one query against one key — + the standard lexical retrieval baseline, delta-smoothed so a long + tool document never fully saturates its term weights. + """ + + def __init__(self, documents: Dict[str, str], k1: float = 1.5, + b: float = 0.75, delta: float = 1.0) -> None: + self.k1 = k1 + self.b = b + self.delta = delta + self.doc_tokens: Dict[str, List[str]] = { + key: tokenize(doc) for key, doc in documents.items() + } + self.doc_len = {key: max(1, len(toks)) for key, toks in self.doc_tokens.items()} + self.avg_len = sum(self.doc_len.values()) / max(1, len(self.doc_len)) + self.df: Counter = Counter() + for toks in self.doc_tokens.values(): + self.df.update(set(toks)) + self.n_docs = len(self.doc_tokens) + + def _idf(self, term: str) -> float: + df = self.df.get(term, 0) + return math.log((self.n_docs - df + 0.5) / (df + 0.5) + 1.0) + + def score(self, query_tokens: Sequence[str], key: str) -> float: + toks = self.doc_tokens.get(key) + if not toks: + return 0.0 + tf = Counter(toks) + dl = self.doc_len[key] + norm = self.k1 * (1.0 - self.b + self.b * dl / self.avg_len) + total = 0.0 + for term in query_tokens: + f = tf.get(term, 0) + if f == 0: + continue + idf = self._idf(term) + total += idf * (f * (self.k1 + 1.0)) / (f + norm) + self.delta * (1.0 if f > 0 else 0.0) + return total + + def search(self, text: str, keys: Iterable[str], k: int = 10) -> List[Tuple[str, float]]: + """Top-k (key, score) by BM25+ — deterministic tie-break by key.""" + q = tokenize(text) + scored = [(self.score(q, key), key) for key in keys] + scored.sort(key=lambda pair: (-pair[0], pair[1])) + return [(key, score) for score, key in scored[:k] if score > 0.0] + + +# --------------------------------------------------------------------------- +# PPMI + random-projection embedder. +# --------------------------------------------------------------------------- + + +class PpmiEmbedder: + """Distributional word vectors via PPMI + Achlioptas random projection. + + Co-occurrence counts are gathered from the synthetic corpus in two + modes (both deterministic): + + - phrase-internal: adjacent word pairs inside each row's text + (window 1, both orders) — teaches word similarity; + - phrase-to-document: every phrase word paired with every word of + its surface's document — teaches user-word to registry-word + proximity, which is what the router actually needs. + + The PPMI matrix is then multiplied by a sparse {-1,0,+1} projection + of width ``dim`` (entries drawn with probability 1/6, 2/3, 1/6, + scaled by 1/sqrt(dim)) and each word's projected row is L2-normalized. + + ``labeled_pairs`` (A2) optionally adds supervised (text, surface) + co-occurrences at ``label_weight`` above the corpus prior — the + reroute-correction seam. MEASURED on the current corpus (see the A2 + section below and scripts/measure_svd_delta.py): supervision at + weight 4.0 on a held-out split LOWERS top-1 retrieval 0.9683 -> + 0.9544, so the DEFAULT remains the corpus-only build; the parameter + exists so the next corpus regime (organic user queries, real vocab + growth) can adopt it with a fresh measurement instead of a guess. + """ + + def __init__(self, dim: int = 64, seed: int = 0x20260925, + labeled_pairs: Sequence[Tuple[str, str]] = (), + label_weight: float = LABEL_WEIGHT) -> None: + self.dim = dim + self.seed = seed + self._build(labeled_pairs, label_weight) + + # -- construction ------------------------------------------------------- + + def _build(self, labeled_pairs=(), label_weight=LABEL_WEIGHT) -> None: + pair_counts: Counter = Counter() + word_counts: Counter = Counter() + total = _count_pairs(_corpus_rows(), pair_counts, word_counts) + if labeled_pairs: + docs = tool_documents() + supervised = [(text, docs.get(surface, text)) + for text, surface in labeled_pairs] + total += _count_pairs(supervised, pair_counts, word_counts, + weight=label_weight) + + # PPMI matrix as sparse dict-of-Counters. + self.vocab = sorted(word_counts) + self.index = {w: i for i, w in enumerate(self.vocab)} + grand = max(1, total) + ppmi: List[Dict[int, float]] = [dict() for _ in self.vocab] + for (a, b), count in pair_counts.items(): + ia, ib = self.index.get(a), self.index.get(b) + if ia is None or ib is None: + continue + p_ab = count / grand + p_a = word_counts[a] / grand * 2.0 # symmetric counting doubles marginals + p_b = word_counts[b] / grand * 2.0 + denom = p_a * p_b + if denom <= 0: + continue + pmi = math.log(p_ab / denom) + if pmi > 0: + ppmi[ia][ib] = pmi + + # Achlioptas sparse random projection, seeded — deterministic. + rng = random.Random(self.seed) + scale = 1.0 / math.sqrt(self.dim) + vectors: List[List[float]] = [] + for i in range(len(self.vocab)): + vec = [0.0] * self.dim + for j, val in ppmi[i].items(): + # one projection column set per (word,col) drawn on demand + for col in range(self.dim): + r = rng.random() + if r < 1.0 / 6.0: + vec[col] += val * scale + elif r < 2.0 / 6.0: + vec[col] -= val * scale + norm = math.sqrt(sum(v * v for v in vec)) + if norm > 0: + vec = [v / norm for v in vec] + vectors.append(vec) + self.vectors = vectors + + # -- querying ----------------------------------------------------------- + + def word_vector(self, word: str) -> List[float]: + i = self.index.get(stem(word)) + return self.vectors[i] if i is not None else [0.0] * self.dim + + def embed(self, text: str, keep_pronouns: bool = False) -> List[float]: + """Sublinear-tf weighted average of word vectors (tf weight + ``1 + log(tf)``). Unknown words contribute exactly nothing.""" + toks = tokenize(text, keep_pronouns=keep_pronouns) + counts = Counter(toks) + vec = [0.0] * self.dim + mass = 0.0 + for word, tf in counts.items(): + i = self.index.get(word) + if i is None: + continue + weight = 1.0 + math.log(tf) + wv = self.vectors[i] + for col in range(self.dim): + vec[col] += weight * wv[col] + mass += weight + if mass > 0: + vec = [v / mass for v in vec] + norm = math.sqrt(sum(v * v for v in vec)) + if norm > 0: + vec = [v / norm for v in vec] + return vec + + @staticmethod + def cosine(a: Sequence[float], b: Sequence[float]) -> float: + dot = sum(x * y for x, y in zip(a, b)) + na = math.sqrt(sum(x * x for x in a)) + nb = math.sqrt(sum(y * y for y in b)) + return dot / (na * nb) if na > 0 and nb > 0 else 0.0 + + def similarity(self, text_a: str, text_b: str) -> float: + return self.cosine(self.embed(text_a), self.embed(text_b)) + + def neighbors(self, word: str, k: int = 5) -> List[Tuple[str, float]]: + """Top-k nearest vocabulary words by cosine — the DISTRIBUTIONAL + lexicon view (API parity with PpmiSvdEmbedder; see lexicon.py's + distributional_neighbors for the reviewed-workflow framing).""" + target = self.word_vector(word) + if not any(target): + return [] + stem_w = stem(word) + scored = [] + for other, i in self.index.items(): + if other == stem_w: + continue + scored.append((self.cosine(target, self.vectors[i]), other)) + scored.sort(key=lambda pair: (-pair[0], pair[1])) + return [(w, round(s, 4)) for s, w in scored[:k]] + + +# --------------------------------------------------------------------------- +# Process-wide singletons (built once, deterministic, cheap: ~300 docs). +# --------------------------------------------------------------------------- + +_INDEX: TfidfIndex | None = None +_EMBEDDER: PpmiEmbedder | None = None + + +def index() -> TfidfIndex: + """The shared BM25+ index over tool documents + surface rows.""" + global _INDEX + if _INDEX is None: + documents = tool_documents() + for row in all_rows(): + documents.setdefault(f"row::{row.text}", row.text) + _INDEX = TfidfIndex(documents) + return _INDEX + + +def embedder() -> PpmiEmbedder: + """The shared PPMI embedder (fixed seed). + + Lexicon-diff wiring (phase 2.6): if the brain state carries IMPORTED + lexicon pairs (opt-in `cortex lexicon import`), the FIRST build + includes them as supervision (A2's ``labeled_pairs`` seam); an + absent import keeps the corpus-only build byte-for-byte — the + A2-measured default the fingerprint test pins. One JSON read, once + per process, lazily (no brain-state dependency at import time). + """ + global _EMBEDDER + if _EMBEDDER is None: + pairs = _persisted_lexicon_pairs() + _EMBEDDER = PpmiEmbedder(labeled_pairs=pairs) if pairs \ + else PpmiEmbedder() + return _EMBEDDER + + +def _persisted_lexicon_pairs(): + """Imported (text, surface) pairs from the brain state, or [].""" + try: + from assistant.capabilities.brain import state as brain_state + from . import lexicon_diff + return lexicon_diff.persisted_pairs(brain_state.load()) + except Exception: + return [] # the embedder must never fail on state trouble + + +# --------------------------------------------------------------------------- +# A2 — PPMI + truncated SVD (LSA) with supervised reroute-correction pairs. +# +# The classic LSA upgrade of the random-projection embedder above: the PPMI +# co-occurrence matrix is factored with a REAL truncated eigendecomposition +# instead of an Achlioptas sketch, so word vectors span the dominant +# co-occurrence directions exactly (up to the truncation), not by random +# chance. Deterministic end to end: seeded range-finder draw, pure +# arithmetic, no clock, no I/O beyond the corpus import. +# +# MEASURED VERDICT on the current corpus (5814 tool-surfaced rows, one +# document per registry tool; scripts/measure_svd_delta.py + measure_svd_variants.py, run +# this session): the random projection WINS on this corpus regime — +# RP (status quo) top-1 0.9678 top-3 0.9905 top-5 0.9967 +# SVD best weighting top-1 0.8925 top-3 0.9723 top-5 0.9873 +# SVD + supervision top-1 0.9005 (supervision helps SVD: +0.7pt +# over its own corpus-only build) +# RP + supervision top-1 0.9544 (supervision HURTS RP: -1.4pt) +# The reason is structural: with a 377-word closed vocabulary, the 64-dim +# random projection is a nearly lossless Johnson-Lindenstrauss sketch of +# the FULL PPMI geometry, while ANY truncation discards discriminative +# mid-spectrum directions that separate similar tools. The SVD path is +# therefore NOT the router default (the measured winner stays the +# default, per this repo's own bar); it is kept as a tested capability for +# the corpus regime where it is the right tool — an organic, growing +# vocabulary — plus the supervision seam and the distributional-lexicon +# neighbors view. +# +# Pipeline (all pure Python, genius.linalg reused for the dense stages): +# +# 1. sparse symmetric PPMI matrix A (vocab x vocab, ~11k nonzero entries +# on the current corpus) — shared counting with PpmiEmbedder; +# 2. randomized range finder (Halko-Martinsson-Tropp): Q = orth((A)^q O) +# with a seeded O, so span(Q) captures A's dominant column space; +# 3. Rayleigh-Ritz: B = Q^T A Q (via linalg.matmul + linalg.transpose), +# eigendecomposed by cyclic Jacobi — the small k x k symmetric +# eigenproblem, cross-verified against linalg.power_iteration in the +# test suite; +# 4. word vectors = U * sqrt(lambda_+) rows (positive-part PPMI kernel, +# the textbook LSA choice: components with lambda <= 0 are dropped, +# keeping the embedded Gram matrix PSD); +# 5. labeled (text, surface) pairs — the cortex's reroute-corrections, +# i.e. learn.py's label==1 examples — contribute co-occurrences at +# LABEL_WEIGHT per occurrence, ABOVE the corpus prior's weight of 1, +# so accepted corrections dominate the geometry as they accumulate. +# --------------------------------------------------------------------------- + + +def _count_pairs(rows_iter, pair_counts, word_counts, weight=1.0): + """Shared co-occurrence counting (phrase-internal + phrase-to-doc), + factored out of PpmiEmbedder._build so both embedders count the same + way. ``rows_iter`` yields (text, doc_text) pairs.""" + total = 0 + + def _count_pair(a: str, b: str) -> None: + nonlocal total + if a == b: + return + pair_counts[(a, b)] += weight + pair_counts[(b, a)] += weight + total += 2 * weight + + for text, doc in rows_iter: + toks = tokenize(text, keep_pronouns=True) + for a, b in zip(toks, toks[1:]): + _count_pair(a, b) + doc_toks = tokenize(doc) + for a in toks: + for b in doc_toks: + _count_pair(a, b) + word_counts.update(set(toks)) + word_counts.update(set(doc_toks)) + return total + + +def _corpus_rows(): + """(text, doc) pairs for the whole synthetic corpus — the prior.""" + docs = tool_documents() + + def gen(): + for row in all_rows(): + yield row.text, docs.get(row.surface, row.text) + + return gen() + + +def _ppmi_sparse(pair_counts, word_counts, total): + """Sparse symmetric PPMI matrix: list-of-dicts rows + the vocab.""" + vocab = sorted(word_counts) + index = {w: i for i, w in enumerate(vocab)} + grand = max(1.0, total) + ppmi: List[Dict[int, float]] = [dict() for _ in vocab] + for (a, b), count in pair_counts.items(): + ia, ib = index.get(a), index.get(b) + if ia is None or ib is None: + continue + p_ab = count / grand + p_a = word_counts[a] / grand * 2.0 # symmetric counting doubles marginals + p_b = word_counts[b] / grand * 2.0 + denom = p_a * p_b + if denom <= 0: + continue + pmi = math.log(p_ab / denom) + if pmi > 0: + ppmi[ia][ib] = pmi + return vocab, index, ppmi + + +def _sparse_matvec(ppmi: List[Dict[int, float]], x: Sequence[float]) -> List[float]: + """y = A x for the sparse symmetric matrix (row-major dict rows).""" + n = len(ppmi) + y = [0.0] * n + for i, row in enumerate(ppmi): + s = 0.0 + for j, val in row.items(): + s += val * x[j] + y[i] = s + return y + + +def _gram_schmidt(block: List[List[float]]) -> List[List[float]]: + """Orthonormalize the COLUMNS of a list-of-rows matrix (modified + Gram-Schmidt, deterministic; near-zero columns are dropped).""" + n_rows = len(block) + n_cols = len(block[0]) if n_rows else 0 + basis: List[List[float]] = [] # each: a column as a row-list + kept: List[List[float]] = [] + for c in range(n_cols): + v = [block[r][c] for r in range(n_rows)] + for q in basis: + dot = sum(vr * qr for vr, qr in zip(v, q)) + v = [vr - dot * qr for vr, qr in zip(v, q)] + norm = math.sqrt(sum(vr * vr for vr in v)) + if norm > 1e-10: + q = [vr / norm for vr in v] + basis.append(q) + kept.append(q) + # transpose back to n_rows x len(kept) + out = [[0.0] * len(kept) for _ in range(n_rows)] + for c, q in enumerate(kept): + for r in range(n_rows): + out[r][c] = q[r] + return out + + +def _jacobi_eigh(matrix: List[List[float]], max_sweeps: int = 40, + tol: float = 1e-11) -> Tuple[List[float], List[List[float]]]: + """Cyclic Jacobi eigendecomposition of a SMALL dense symmetric matrix. + + Returns (eigenvalues, eigenvectors) with eigenvector j in column j of + the returned list-of-rows matrix. Deterministic sweep order (p, q) + ascending; convergence = off-diagonal Frobenius norm below tol. + Cross-verified against genius.linalg.power_iteration in the tests. + """ + from assistant.capabilities.genius import linalg + + n = len(matrix) + m = [row[:] for row in matrix] + v = linalg.identity(n) + for _ in range(max_sweeps): + off = math.sqrt(sum(m[i][j] * m[i][j] + for i in range(n) for j in range(i + 1, n))) + if off < tol: + break + for p in range(n - 1): + for q in range(p + 1, n): + apq = m[p][q] + if abs(apq) < 1e-300: + continue + theta = (m[q][q] - m[p][p]) / (2.0 * apq) + sign = 1.0 if theta >= 0 else -1.0 + t = sign / (abs(theta) + math.sqrt(theta * theta + 1.0)) + c = 1.0 / math.sqrt(t * t + 1.0) + s = t * c + for k in range(n): # rotate rows p, q of m and columns p, q + mkp, mkq = m[k][p], m[k][q] + m[k][p] = c * mkp - s * mkq + m[k][q] = s * mkp + c * mkq + mp = m[p][:] # row copies: apply the row rotation after + mq = m[q][:] + for k in range(n): + m[p][k] = c * mp[k] - s * mq[k] + m[q][k] = s * mp[k] + c * mq[k] + for k in range(n): # accumulate the rotation into v + vkp, vkq = v[k][p], v[k][q] + v[k][p] = c * vkp - s * vkq + v[k][q] = s * vkp + c * vkq + eigenvalues = [m[i][i] for i in range(n)] + return eigenvalues, v + + +class PpmiSvdEmbedder: + """PPMI co-occurrence + truncated SVD (LSA) word vectors. + + Same query API as PpmiEmbedder (word_vector / embed / cosine / + similarity), same determinism guarantees (seeded range finder), but + the reduction is an actual truncated eigendecomposition of the PPMI + kernel rather than a random projection, and optional supervised + (text, surface) pairs — the cortex's reroute-corrections — weight the + co-occurrences they touch LABEL_WEIGHT times above the corpus prior. + + Footprint (measured on the 5890-row corpus, vocab 377): build adds + ~1-2s CPU once per process; steady-state memory is the vocab x dim + vector table (377 x 64 floats) plus the discarded build scaffolding — + the same order as the projection embedder. + """ + + def __init__(self, dim: int = 64, seed: int = SVD_SEED, + labeled_pairs: Sequence[Tuple[str, str]] = (), + label_weight: float = LABEL_WEIGHT, + power_iters: int = 2) -> None: + from assistant.capabilities.genius import linalg + + self.dim = dim + self.seed = seed + pair_counts: Counter = Counter() + word_counts: Counter = Counter() + total = _count_pairs(_corpus_rows(), pair_counts, word_counts) + + # Supervised pairs: the reroute-corrections, weighted above the + # prior. Co-occurrences between the pair's text tokens and the + # surface document's tokens get label_weight per occurrence. + docs = tool_documents() + if labeled_pairs: + supervised = [] + for text, surface in labeled_pairs: + doc = docs.get(surface) + if doc is None: + # coarse surface: its corpus rows' own text is the doc + doc = text + supervised.append((text, doc)) + total += _count_pairs(supervised, pair_counts, word_counts, + weight=label_weight) + + self.vocab, self.index, ppmi = _ppmi_sparse( + pair_counts, word_counts, total) + n = len(self.vocab) + + # 1. Seeded range finder: Q = orth(A^q Omega) — column-wise sparse + # matvecs, then modified Gram-Schmidt, then power sweeps. + rng = random.Random(seed) + omega_cols = [[rng.uniform(-1.0, 1.0) for _r in range(n)] + for _c in range(dim)] + y_cols = [_sparse_matvec(ppmi, x) for x in omega_cols] + y = [[y_cols[c][r] for c in range(dim)] for r in range(n)] + q = _gram_schmidt(y) + for _ in range(power_iters): + q_cols = len(q[0]) if q else 0 + y_cols = [_sparse_matvec(ppmi, [q[r][c] for r in range(n)]) + for c in range(q_cols)] + y = [[y_cols[c][r] for c in range(q_cols)] for r in range(n)] + q = _gram_schmidt(y) + + # 2. Rayleigh-Ritz on the projected matrix B = Q^T A Q. + aq_cols = [_sparse_matvec(ppmi, [q[r][c] for r in range(n)]) + for c in range(len(q[0]))] if q else [] + aq = [[aq_cols[c][r] for c in range(len(aq_cols))] for r in range(n)] + b = linalg.matmul(linalg.transpose(q), aq) # k x k, genius.linalg + eigenvalues, w = _jacobi_eigh(b) + + # 3. Keep the top positive-eigenvalue components, value-descending. + order = sorted(range(len(eigenvalues)), + key=lambda j: -eigenvalues[j]) + kept = [j for j in order if eigenvalues[j] > 0][:dim] + scales = [math.sqrt(eigenvalues[j]) for j in kept] + + # U = Q W restricted to kept columns, word vectors = U * scales. + vectors: List[List[float]] = [] + for r in range(n): + row = [0.0] * len(kept) + for cj, j in enumerate(kept): + u_rj = sum(q[r][t] * w[t][j] for t in range(len(q[0]))) \ + if q else 0.0 + row[cj] = u_rj * scales[cj] + norm = math.sqrt(sum(x * x for x in row)) + if norm > 0: + row = [x / norm for x in row] + vectors.append(row) + self.vectors = vectors + self.eigenvalues = [eigenvalues[j] for j in kept] + + # -- querying (identical surface to PpmiEmbedder) ---------------------- + + def word_vector(self, word: str) -> List[float]: + i = self.index.get(stem(word)) + if i is None: + return [0.0] * max(1, len(self.vectors[0]) if self.vectors else 1) + return self.vectors[i] + + @property + def effective_dim(self) -> int: + return len(self.vectors[0]) if self.vectors else 0 + + def embed(self, text: str, keep_pronouns: bool = False) -> List[float]: + toks = tokenize(text, keep_pronouns=keep_pronouns) + counts = Counter(toks) + if not self.vectors: + return [] + dim = len(self.vectors[0]) + vec = [0.0] * dim + mass = 0.0 + for word, tf in counts.items(): + i = self.index.get(word) + if i is None: + continue + weight = 1.0 + math.log(tf) + wv = self.vectors[i] + for col in range(dim): + vec[col] += weight * wv[col] + mass += weight + if mass > 0: + vec = [v / mass for v in vec] + norm = math.sqrt(sum(v * v for v in vec)) + if norm > 0: + vec = [v / norm for v in vec] + return vec + + @staticmethod + def cosine(a: Sequence[float], b: Sequence[float]) -> float: + dot = sum(x * y for x, y in zip(a, b)) + na = math.sqrt(sum(x * x for x in a)) + nb = math.sqrt(sum(y * y for y in b)) + return dot / (na * nb) if na > 0 and nb > 0 else 0.0 + + def similarity(self, text_a: str, text_b: str) -> float: + return self.cosine(self.embed(text_a), self.embed(text_b)) + + def neighbors(self, word: str, k: int = 5) -> List[Tuple[str, float]]: + """Top-k nearest vocabulary words by cosine — the DISTRIBUTIONAL + lexicon view (what the SVD space believes is similar to this + word). Deterministic, tie-break alphabetical.""" + target = self.word_vector(word) + if not any(target): + return [] + scored = [] + for other, i in self.index.items(): + if other == stem(word): + continue + scored.append((self.cosine(target, self.vectors[i]), other)) + scored.sort(key=lambda pair: (-pair[0], pair[1])) + return [(w, round(s, 4)) for s, w in scored[:k]] From bf2480a25f69c5af3cf4bb5ebe918d362cc3d3ac Mon Sep 17 00:00:00 2001 From: 0x0nYx <0x0nYx@users.noreply.github.com> Date: Fri, 9 Oct 2026 12:18:59 +0000 Subject: [PATCH 05/10] feat(assistant): core cortex services and the measurement arena; typed executor (migration chunk 4/12) The rest of the core: cortex pipeline, router, dispatch, plans, schedules, inbox, personalization, refit, reranker, NL history, telemetry, the eval arena (dev/sealed sets) and the typed executor (argv-only, timeout-bounded plan runner). Note: dispatch and pipeline import the brain/settings capabilities at module level (upstream's own coupling); those imports resolve from chunks 07/08 onward. Chunk contents (42 files): - assistant/core/ask_pipeline.py - assistant/core/cli.py - assistant/core/coldstart.py - assistant/core/compound.py - assistant/core/coref.py - assistant/core/delegate.py - assistant/core/dispatch.py - assistant/core/encoder_onnx.py - assistant/core/engine_telemetry.py - assistant/core/ensemble.py - assistant/core/eval/__init__.py - assistant/core/eval/__main__.py - ... and 30 more Source: 0x0nYx/caelestia-assistant@2c193e7 (main, v0.1) Faithfulness: byte-identical copy (sha256-verified in the migration audit; only metadata.json / README.md are plugin-store scaffolding, and .caelestia-audit-ignore documents scanner false positives). Safety audit: 0 errors; 14 line-level findings documented in .caelestia-audit-ignore (string vocabularies / rulepack prose / test assertion targets / opt-in provider calls - nothing executes). Store CI: validate.py OK - check_safety.py OK - check_scope.py OK. Next chunk: plugin/caelestia-assistant/05-data-corpus --- .../assistant/core/ask_pipeline.py | 163 ++ .../caelestia-assistant/assistant/core/cli.py | 1532 +++++++++++++++++ .../assistant/core/coldstart.py | 143 ++ .../assistant/core/compound.py | 260 +++ .../assistant/core/coref.py | 156 ++ .../assistant/core/delegate.py | 214 +++ .../assistant/core/dispatch.py | 598 +++++++ .../assistant/core/encoder_onnx.py | 63 + .../assistant/core/engine_telemetry.py | 193 +++ .../assistant/core/ensemble.py | 256 +++ .../assistant/core/eval/__init__.py | 18 + .../assistant/core/eval/__main__.py | 5 + .../assistant/core/eval/baseline.json | 46 + .../assistant/core/eval/cli.py | 149 ++ .../assistant/core/eval/engine.py | 509 ++++++ .../assistant/core/eval/grow.py | 201 +++ .../assistant/core/eval/metamorphic.py | 259 +++ .../core/eval/sets/abstention_dev.json | 85 + .../core/eval/sets/diagnosis_dev.json | 105 ++ .../assistant/core/eval/sets/nlplan_dev.json | 185 ++ .../assistant/core/eval/sets/routing_dev.json | 837 +++++++++ .../core/eval/sets/sealed_abstention.json | 36 + .../core/eval/sets/sealed_manifest.sha256 | 3 + .../core/eval/sets/sealed_nlplan.json | 45 + .../core/eval/sets/sealed_routing.json | 148 ++ .../assistant/core/eval/stats.py | 126 ++ .../assistant/core/explain_unified.py | 497 ++++++ .../assistant/core/inbox.py | 520 ++++++ .../assistant/core/learn.py | 650 +++++++ .../assistant/core/nlhistory.py | 358 ++++ .../assistant/core/personalize.py | 284 +++ .../assistant/core/pipeline.py | 821 +++++++++ .../assistant/core/plans.py | 145 ++ .../assistant/core/power_advisor.py | 314 ++++ .../assistant/core/refit.py | 156 ++ .../assistant/core/reranker.py | 296 ++++ .../assistant/core/router.py | 1331 ++++++++++++++ .../assistant/core/schedules.py | 286 +++ .../assistant/core/session.py | 337 ++++ .../assistant/executor/__init__.py | 8 + .../assistant/executor/plan.py | 88 + .../assistant/executor/runner.py | 116 ++ 42 files changed, 12542 insertions(+) create mode 100755 plugins/caelestia-assistant/assistant/core/ask_pipeline.py create mode 100755 plugins/caelestia-assistant/assistant/core/cli.py create mode 100644 plugins/caelestia-assistant/assistant/core/coldstart.py create mode 100755 plugins/caelestia-assistant/assistant/core/compound.py create mode 100644 plugins/caelestia-assistant/assistant/core/coref.py create mode 100644 plugins/caelestia-assistant/assistant/core/delegate.py create mode 100644 plugins/caelestia-assistant/assistant/core/dispatch.py create mode 100644 plugins/caelestia-assistant/assistant/core/encoder_onnx.py create mode 100644 plugins/caelestia-assistant/assistant/core/engine_telemetry.py create mode 100644 plugins/caelestia-assistant/assistant/core/ensemble.py create mode 100644 plugins/caelestia-assistant/assistant/core/eval/__init__.py create mode 100644 plugins/caelestia-assistant/assistant/core/eval/__main__.py create mode 100644 plugins/caelestia-assistant/assistant/core/eval/baseline.json create mode 100644 plugins/caelestia-assistant/assistant/core/eval/cli.py create mode 100644 plugins/caelestia-assistant/assistant/core/eval/engine.py create mode 100644 plugins/caelestia-assistant/assistant/core/eval/grow.py create mode 100644 plugins/caelestia-assistant/assistant/core/eval/metamorphic.py create mode 100644 plugins/caelestia-assistant/assistant/core/eval/sets/abstention_dev.json create mode 100644 plugins/caelestia-assistant/assistant/core/eval/sets/diagnosis_dev.json create mode 100644 plugins/caelestia-assistant/assistant/core/eval/sets/nlplan_dev.json create mode 100644 plugins/caelestia-assistant/assistant/core/eval/sets/routing_dev.json create mode 100644 plugins/caelestia-assistant/assistant/core/eval/sets/sealed_abstention.json create mode 100644 plugins/caelestia-assistant/assistant/core/eval/sets/sealed_manifest.sha256 create mode 100644 plugins/caelestia-assistant/assistant/core/eval/sets/sealed_nlplan.json create mode 100644 plugins/caelestia-assistant/assistant/core/eval/sets/sealed_routing.json create mode 100644 plugins/caelestia-assistant/assistant/core/eval/stats.py create mode 100644 plugins/caelestia-assistant/assistant/core/explain_unified.py create mode 100644 plugins/caelestia-assistant/assistant/core/inbox.py create mode 100755 plugins/caelestia-assistant/assistant/core/learn.py create mode 100755 plugins/caelestia-assistant/assistant/core/nlhistory.py create mode 100644 plugins/caelestia-assistant/assistant/core/personalize.py create mode 100755 plugins/caelestia-assistant/assistant/core/pipeline.py create mode 100644 plugins/caelestia-assistant/assistant/core/plans.py create mode 100644 plugins/caelestia-assistant/assistant/core/power_advisor.py create mode 100644 plugins/caelestia-assistant/assistant/core/refit.py create mode 100644 plugins/caelestia-assistant/assistant/core/reranker.py create mode 100755 plugins/caelestia-assistant/assistant/core/router.py create mode 100644 plugins/caelestia-assistant/assistant/core/schedules.py create mode 100755 plugins/caelestia-assistant/assistant/core/session.py create mode 100644 plugins/caelestia-assistant/assistant/executor/__init__.py create mode 100644 plugins/caelestia-assistant/assistant/executor/plan.py create mode 100644 plugins/caelestia-assistant/assistant/executor/runner.py diff --git a/plugins/caelestia-assistant/assistant/core/ask_pipeline.py b/plugins/caelestia-assistant/assistant/core/ask_pipeline.py new file mode 100755 index 0000000..f10007b --- /dev/null +++ b/plugins/caelestia-assistant/assistant/core/ask_pipeline.py @@ -0,0 +1,163 @@ +"""Assistant pipeline: Layer 1 deterministic rules, then Layer 2 retrieval. + +Usage: + python3 -m assistant.core.ask_pipeline "text or pasted log" + ... | python3 -m assistant.core.ask_pipeline (stdin) + python3 -m assistant.core.ask_pipeline "text" --json + python3 -m assistant.core.ask_pipeline "text" --generative + python3 -m assistant.core.ask_pipeline "text" --generative --json + +assist(text) -> dict: +- Runs the Layer 1 deterministic engine (assistant.capabilities.diagnostics.engine). +- On MATCH/AMBIGUOUS: returns {"layer": "rules", ...} — verified signatures. +- On NO_MATCH: runs the offline retrieval search (assistant.capabilities.retrieval.search) + and returns {"layer": "retrieval", ...} with a banner stating these are the + closest past resolutions from the repo's docs and resolved issues, NOT + verified diagnoses. + +--generative (Layer 3, opt-in, only reached on a Layer 1 NO_MATCH): the +pipeline delegates to assistant.capabilities.generative.rag.suggest(text, k, enable=True) +and returns that result dict — {"enabled", "available", "suggestion", +"retrieval_hits", "reason"} — with one added "layer": "generative" marker +(--json emits exactly this dict; the human renderer is rag.render_result). +Layer 1 always wins when it matches: the generative layer exists only for +problems the rules cannot name. Every Layer 3 guarantee (opt-in only, +loopback-only single connection attempt, retrieval-grounded prompt, +SUGGESTED_NOT_EXECUTED labeling, graceful unavailability) lives in +assistant/generative/rag.py; this module routes to it and reimplements +none of it. Without --generative the generative code path is never taken +and the output is identical to the two-layer pipeline. + +Import surface: assistant.capabilities.diagnostics.engine + assistant.capabilities.retrieval + +assistant.capabilities.generative.rag (intra-package relative imports) + stdlib only. +Nothing here executes commands or touches the network. +""" + +from __future__ import annotations + +import argparse +import json +import sys +from typing import Any, Dict, List, Optional + +from assistant.capabilities.diagnostics import engine +from assistant.capabilities.generative import rag +from assistant.capabilities.retrieval import search + +RETRIEVAL_BANNER = ( + "Layer 2 — closest past resolutions from this repo's docs and resolved issues. " + "These are retrieval hits, NOT verified diagnoses: the assistant may be wrong. " + "Check the cited source before acting on anything below." +) + +NO_RESULTS_NOTE = ( + "Nothing in the local docs or resolved issues matched either. The honest answer is: " + "enable Debug Mode (Nexus -> About -> Advanced), capture logs with " + "journalctl --user -u caelestia-shell, and draft an issue report." +) + + +def assist(text: str, k: int = 5, generative: bool = False) -> Dict[str, Any]: + """Run Layer 1, fall back to Layer 2 retrieval on NO_MATCH. + + With generative=True, a NO_MATCH is delegated to Layer 3 + (rag.suggest(enable=True)) instead: its result dict — which carries the + Layer 2 hits, the availability state, and the safety-labeled suggestion — + is returned with a "layer": "generative" marker. A Layer 1 match always + wins regardless of the flag. + """ + diagnosis = engine.diagnose(text) + + if diagnosis["verdict"] != "NO_MATCH": + return { + "layer": "rules", + "verdict": diagnosis["verdict"], + "margin": diagnosis.get("margin"), + "candidates": [ + { + "id": result["rule"]["id"], + "title": result["rule"].get("title", ""), + "score": result["score"], + "confidence": result["rule"].get("confidence", "probable"), + "evidence": result.get("evidence", [])[:6], + } + for result in diagnosis["candidates"] + ], + "report": engine.render_report(diagnosis), + } + + if generative: + # Layer 3 owns this path end to end — grounding, loopback-only + # transport, availability, labeling — so delegate and add only the + # layer marker the renderer/JSON emit; suggest() already ran the + # Layer 2 search that fills its retrieval_hits. + return {"layer": "generative", **rag.suggest(text, k=k, enable=True)} + + results = search.search(text, k=k) + payload: Dict[str, Any] = { + "layer": "retrieval", + "verdict": "NO_MATCH", + "banner": RETRIEVAL_BANNER, + "results": results, + } + if not results: + payload["note"] = NO_RESULTS_NOTE + return payload + + +def render(payload: Dict[str, Any]) -> str: + """Human-readable rendering of an assist() payload.""" + if payload["layer"] == "rules": + return payload["report"] + if payload["layer"] == "generative": + return rag.render_result(payload) + lines: List[str] = [] + lines.append("caelestia assistant — layer 2 retrieval (closest past resolutions)") + lines.append(payload["banner"]) + lines.append("") + results = payload.get("results", []) + if not results: + lines.append(payload.get("note", "No results.")) + return "\n".join(lines) + for i, hit in enumerate(results, start=1): + lines.append(f"[{i}] {hit['doc_id']} — {hit['title']} (score {hit['score']})") + lines.append(f" source: {hit['source']}") + lines.append(f" snippet: {hit['snippet']}") + lines.append("") + lines.append("Reminder: these are past resolutions, not verified answers. Nothing was executed.") + return "\n".join(lines) + + +def main(argv: Optional[List[str]] = None) -> int: + parser = argparse.ArgumentParser( + prog="python3 -m assistant.core.ask_pipeline", + description="caelestia assistant: deterministic rules first, retrieval fallback (offline, runs nothing).", + ) + parser.add_argument("text", nargs="?", default="-", help="problem text or pasted log; '-' reads stdin") + parser.add_argument("--json", action="store_true", help="emit the raw payload as JSON") + parser.add_argument( + "--generative", + action="store_true", + help=( + "opt in to the Layer 3 generative suggestion layer when the rules layer has no match " + "(requires a local Ollama server on loopback; suggestion-only, nothing is executed)" + ), + ) + parser.add_argument("-k", type=int, default=5, help="max retrieval results (default 5)") + args = parser.parse_args(argv) + + if args.text == "-": + text = sys.stdin.read() + else: + text = args.text + + payload = assist(text, k=args.k, generative=args.generative) + if args.json: + print(json.dumps(payload, ensure_ascii=False, indent=2)) + else: + print(render(payload)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/plugins/caelestia-assistant/assistant/core/cli.py b/plugins/caelestia-assistant/assistant/core/cli.py new file mode 100755 index 0000000..9fa1846 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/core/cli.py @@ -0,0 +1,1532 @@ +"""CLI surface for the cortex layer: ``chat``, ``route``, ``cortex``. + +Commands (routed by hub.py): + + caelestia-assist chat [--json] [--file PATH] [--apply-confirmed] + Interactive conversational REPL. Every routed plan is shown with + evidence and a calibrated confidence; NOTHING writes until the + y/N prompt answers y (the multi-change confirmation gate issue + #120 asks for, in conversational form). ``--json`` switches to a + line-delimited JSON protocol for the QML bridge / scripts — pure + information unless ``--apply-confirmed`` ALSO asserts the + caller's own confirmation UI was used. + + caelestia-assist route "text" [--file PATH] [--json] [-k N] + One-shot: route + plan + evidence, no interaction, never writes. + + caelestia-assist cortex report|recall|reset-learning|suggest + The self-learning and memory dashboard: calibration, strategy + bandit, drift, episodic recall, and the proactive co-change + suggestion (as a ledger proposal — ``suggest`` never applies). + +State lives in the brain's state.json (keys ``cortex_learn`` and +``cortex_memory``), written through the same atomic-save path as every +other learned model. The chat/session state itself is per-process. +""" + +from __future__ import annotations + +import argparse +import json +import re +import sys +from datetime import datetime +from pathlib import Path +from typing import Any, Dict, List, Optional + +from assistant.capabilities.brain import state as brain_state +from assistant.capabilities.settings import applier as settings_applier +from assistant.capabilities.settings import consequences +from assistant.capabilities.settings import history as settings_history +from assistant.capabilities.settings import planner as settings_planner +from assistant.capabilities.settings.cli import default_target, render_plan +from . import learn as cortex_learn +from .delegate import run_delegate, runner_names +from .learn import CortexLearner +from .memory import ( + followup_suggestion, + record as memory_record, + recall as memory_recall, + resolve_halflife, + summarize as memory_summarize, +) +from .pipeline import episode_for, process as cortex_process +from .plans import DISCARD_RE, PlanCache +from .session import SessionState + +LEARN_KEY = "cortex_learn" +MEMORY_KEY = "cortex_memory" + + +# --------------------------------------------------------------------------- +# Shared state helpers. +# --------------------------------------------------------------------------- + + +def _load_learner(state: Optional[Dict[str, Any]] = None) -> CortexLearner: + data = state if state is not None else brain_state.load() + return CortexLearner(data.get(LEARN_KEY)) # type: ignore[arg-type] + + +def _load_memory(state: Optional[Dict[str, Any]] = None) -> List[Dict[str, Any]]: + data = state if state is not None else brain_state.load() + raw = data.get(MEMORY_KEY) or [] + return [dict(row) for row in raw] # type: ignore[union-attr] + + +def _now() -> datetime: + return datetime.now() + + +# --------------------------------------------------------------------------- +# Rendering. +# --------------------------------------------------------------------------- + + +def _fmt_candidates(result) -> List[str]: + lines = [] + for cand in result.candidates[:5]: + marker = "->" if cand is result.candidates[0] else " " + lines.append(f"{marker} {cand['surface']} (score {cand['score']:.3f}, " + f"kind {cand['kind']})") + return lines + + +def _render_turn(result, *, applied: bool = False, + inline_delegate: bool = False) -> List[str]: + """Human rendering of one cortex result (the chat card). + + ``inline_delegate``: the DELEGATE target already ran inline this turn + (its answer follows this card), so the "try:" hint is suppressed — + it stays the fallback for the rare case the inline run itself fails. + """ + lines: List[str] = [] + verdict_label = { + "PLAN": "FOUND A CHANGE" if applied else "PROPOSED CHANGE", + "QUESTION": "NEED A DETAIL", + "ABSTAIN": "NO MATCH", + "DELEGATE": "OTHER LAYER", + "EXPLAIN": "EXPLANATION", + "UNDO": "UNDO", + "LIST": "HISTORY", + "INERT": "OUTSIDE SHELL.JSON", + }.get(result.verdict, result.verdict) + lines.append("[cortex] " + verdict_label + " (confidence " + # D8: a cold-start confidence is the flat Beta prior — + # a fake number. Say so instead. + + ("uncalibrated (no history)" + if getattr(result, "calibrated", None) is False + else f"{result.confidence:.2f}") + + (f", strategy {result.strategy}" if result.strategy else "") + ")") + if result.session_note: + lines.append(f" {result.session_note}") + lines.extend(f" {line}" for line in _fmt_candidates(result)) + if result.evidence: + shown = "; ".join(dict.fromkeys(result.evidence))[:220] + lines.append(f" evidence: {shown}") + if result.verdict == "PLAN" and result.plan is not None: + lines.append("") + lines.extend(" " + line for line in render_plan( + result.plan, [], "cortex chat", None, applied, None, None)) + if result.verdict == "QUESTION": + lines.extend(f" ? {q}" for q in result.questions) + if result.verdict == "EXPLAIN" and result.explain_answer: + lines.append(f" {result.explain_answer.get('answer', '')}") + cites = result.explain_answer.get("cites") or [] + if cites: + lines.append(f" grounded in: {'; '.join(str(c) for c in cites)}") + if result.history_plan: + hp = result.history_plan + lines.append(f" {hp.get('reason', '')}") + for entry in hp.get("entries", [])[:5]: + label = entry.get("label") or f"#{entry.get('id')}" + lines.append(f" - [{entry.get('id')}] {label} at {entry.get('at')}") + if result.delegate and not inline_delegate: + hint = { + "diagnose": "caelestia-assist diagnose ", + "search": "caelestia-assist search \"...\"", + "brain": "caelestia-assist brain --help", + "issue": "caelestia-assist issue draft --title ...", + "agent": "caelestia-assist agent \"...\" --simulate", + }.get(result.delegate, result.delegate) + lines.append(f" try: {hint}") + if result.suggestions: + lines.extend(f" {s}" for s in result.suggestions) + for note in result.notes[:6]: + if note: + lines.append(f" note: {note}") + return lines + + +def _render_report(learner: CortexLearner, episodes: List[Dict[str, object]]) -> List[str]: + report = learner.report() + memory = memory_summarize(episodes) + lines = [ + "cortex — learned intelligence report", + f" routing examples observed : {report['examples']} " + f"({report['accepts']} accepted / {report['rejects']} rejected)", + f" acceptance rate : {report['acceptance_rate']}", + f" calibration (overall) : {report['calibration']['overall']}", + ] + for bucket, mean in report["calibration"]["buckets"].items(): + lines.append(f" {bucket:8s}: {mean}") + lines.append(" strategy arms (Thompson):") + for name, row in report["strategy_arms"].items(): + lines.append(f" {name:10s}: mean {row['mean']} over {row['draws']} draws") + lines.append(f" fitted signal weights : {report['fitted_weights']}") + lines.append(f" drift : {report['drift']}") + lines.append(f" drift (BOCPD, hit-rate) : {report['drift_bocpd']}") + # exponential-build 3 item B2: dual-detector consensus — drift is + # FLAGGED only when BOTH Page-Hinkley and ADWIN have alarmed. + lines.append(f" drift (PH+ADWIN consensus) : " + f"{report['drift_ph_adwin']['summary']}") + lines.append(f" bandit regret vs best arm : {report['regret'].get('status')}" + f" (est. {report['regret'].get('estimated_regret')})") + lines.append(f" memory episodes : {memory['episodes']} " + f"({memory['applied_episodes']} applied)") + if memory["top_surfaces"]: + tops = ", ".join(f"{row['surface']}({row['count']})" for row in memory["top_surfaces"][:5]) + lines.append(f" most-changed settings : {tops}") + if memory["top_cochanges"]: + pairs = ", ".join(f"{row['a']}+{row['b']} (lift {row['lift']})" for row in memory["top_cochanges"][:3]) + lines.append(f" strongest co-changes : {pairs}") + if memory["peak_hour"] is not None: + lines.append(f" customization peak hour : {memory['peak_hour']}:00") + return lines + + +# --------------------------------------------------------------------------- +# The chat REPL. +# --------------------------------------------------------------------------- + + +def _confirm(prompt: str) -> bool: + try: + answer = input(f"{prompt} [y/N] ").strip().lower() + except EOFError: + return False + return answer in ("y", "yes") + + +def _apply_plan(result, target: Path, text: str) -> bool: + """The one write path of the chat — the existing applier, gated by + the interactive confirmation (issue #120's multi-change gate).""" + if result.plan is None: + return False + if not _confirm("apply these changes?"): + return False + try: + settings_applier.apply(result.plan, target, write=True, label=f"chat: {text}") + except settings_applier.ApplierError as exc: + print(f" error: {exc}", file=sys.stderr) + return False + return True + + +def _run_undo(result, target: Path) -> bool: + if not result.history_plan: + return False + action = result.history_plan.get("action") + try: + if action == "undo": + steps = int(result.history_plan.get("steps") or 1) + if not _confirm(f"undo the last {steps} change(s)?"): + return False + outcome = settings_history.undo(target, steps=steps) + elif action == "undo_by_id": + entry_id = int(result.history_plan.get("entry_id") or 0) + if not _confirm(f"revert history entry #{entry_id}?"): + return False + outcome = settings_history.undo_by_id(target, entry_id=entry_id) + else: + return False + except settings_history.HistoryError as exc: + print(f" error: {exc}", file=sys.stderr) + return False + print(f" restored: {bool(outcome.get('restored') or outcome.get('written'))}" + + (f" — {outcome.get('message', '')}" if outcome.get("message") else "")) + return bool(outcome.get("restored") or outcome.get("written")) + + +def cmd_chat(argv: Optional[List[str]] = None) -> int: + parser = argparse.ArgumentParser( + prog="caelestia-assist chat", + description="conversational settings assistant (learned routing, " + "confirmation-gated applies, never writes without y)", + ) + parser.add_argument("--file", default=None, help="target shell.json override") + parser.add_argument("--json", action="store_true", + help="line-delimited JSON protocol per turn (machine mode)") + parser.add_argument("--apply-confirmed", action="store_true", + help="JSON mode only: the caller asserts its own confirmation " + "UI was used; single-op plans apply without the y/N prompt") + parser.add_argument("--no-learn", action="store_true", + help="do not read or update learned state this session") + args = parser.parse_args(argv) + + target = Path(args.file) if args.file else default_target() + state = brain_state.load() + learner = None if args.no_learn else _load_learner(state) + episodes = _load_memory(state) + review_bucket = list(state.get("cortex_review", [])) + session = SessionState() + plan_cache = PlanCache.from_dict(session.pending_plan) + + print(f"cortex chat — natural-language shell.json assistant") + print(f"target: {target}") + print("commands: /exit /history /undo N | everything else is a request") + if args.json: + print(json.dumps({"type": "session", "target": str(target), "apply_allowed": bool(args.apply_confirmed)})) + + for line in sys.stdin: + text = line.strip() + if not text: + continue + if text in ("/exit", "/quit", "/q"): + break + if text == "/history": + for turn in session.to_dict()["turns"]: + print(f" you: {turn['text']} -> {', '.join(turn['surfaces']) or turn['verdict']}") + continue + if text.startswith("/undo"): + parts = text.split() + steps = int(parts[1]) if len(parts) > 1 and parts[1].isdigit() else 1 + try: + outcome = settings_history.undo(target, steps=steps) + except settings_history.HistoryError as exc: + print(f" error: {exc}", file=sys.stderr) + continue + print(f" restored: {bool(outcome.get('restored'))}") + continue + + # Phase 2.5: explicit discard drops the pending plan (the honest + # way out of an iteration, instead of refusing it forever). + if DISCARD_RE.match(text): + dropped = plan_cache.pending_count() + plan_cache.discard() + session.pending_plan = None + print(f" discarded {dropped} pending change(s)") + continue + + # Phase 2.5: an explicit APPLY of the accumulated pending plan — + # recognized BEFORE the session's yes-answer machinery can eat it + # ("apply" is also a yes-word there; here it is an instruction). + if (re.match(r"^\s*(?:apply|apply these|apply these changes|" + r"apply them|apply it|go ahead|commit)\s*[.!]?\s*$", + text, re.IGNORECASE) + and plan_cache.pending_count() > 0): + pending_ops = plan_cache.pending() + class _ApplyResult: # minimal shape _apply_plan needs + plan = None + try: + apply_result = _ApplyResult() + apply_result.plan = settings_planner.plan(pending_ops, + target) + except settings_planner.PlannerError as exc: + print(f" error: composed plan refused: {exc}", + file=sys.stderr) + continue + if _apply_plan(apply_result, target, "pending plan"): + plan_cache.commit() + session.pending_plan = None + print(f" applied {len(pending_ops)} composed change(s) " + "(backup written; 'undo the last change' reverts it)") + else: + session.pending_plan = plan_cache.to_dict() + pending_line = plan_cache.summary() + print(f" {pending_line} — still pending (refused)") + continue + + # Phase 2.7: what-if turns render the CONSEQUENCE view for the + # composed plan (pending + this request) and never gate an apply — + # iterate first, commit later. + if re.match(r"^\s*what\s+if\b", text, re.IGNORECASE): + whatif_text = re.sub(r"^\s*what\s+if\b", "", text, + flags=re.IGNORECASE).strip() + if whatif_text: + # "what if X" — plan X (read-only), compose it with the + # pending plan, and project the CONSEQUENCES. + whatif_result = cortex_process( + whatif_text, session=session, learner=learner, + file_path=target, now=_now()) + new_ops = whatif_result.ops or [] + else: + # A BARE "what if" projects the pending plan itself — it + # must NOT route a placeholder request (the router's + # fuzzy match on "show my pending changes" once resolved + # to a toast toggle and polluted the pending plan). + new_ops = [] + ops = new_ops or plan_cache.pending() + if ops: + if new_ops: + ops = plan_cache.compose(new_ops, whatif_text) + current: Dict[str, Any] = {} + if target.exists(): + try: + current, _notes = settings_planner._read_current( + target) + except Exception: + current = {} + # The composed RAW ops (later-wins per tool, mirroring + # the compound layer) re-validate through the standard + # planner; the PROJECTION then runs over the planner's + # RESOLVED entries — step/multiply ops become absolute + # values, never raw deltas (projecting a step delta of + # -1 as an absolute scale was a real bug this pins). + resolved_ops: List[Dict[str, Any]] = [] + try: + composed_plan = settings_planner.plan(ops, target) + resolved_ops = [ + {"tool": e.get("tool"), "value": e.get("new")} + for e in composed_plan.get("entries", []) + if not e.get("error")] + except settings_planner.PlannerError: + pass # the consequence view renders regardless + projection = consequences.project( + resolved_ops or ops, current=current) + if args.json: + print(json.dumps({"type": "whatif", "projection": + projection}, default=str)) + else: + print("\n".join(consequences.render( + projection, title="what-if"))) + pending_line = plan_cache.summary() + if pending_line: + print(f" {pending_line}") + print(" say the next change, or 'apply these " + "changes' when ready") + session.pending_plan = plan_cache.to_dict() + else: + print(" nothing to project: no ops in this request and " + "no pending plan") + continue + + result = cortex_process(text, session=session, learner=learner, file_path=target, now=_now()) + + # Phase 2.5: compose this turn's ops with the PENDING plan (later + # wins per tool — the compound layer's own rule) and re-validate + # through the standard planner before proposing anything. + if result.verdict == "PLAN" and result.ops: + if plan_cache.pending_count() > 0: + composed_ops = plan_cache.compose(result.ops, text) + try: + composed_plan = settings_planner.plan(composed_ops, + target) + result.plan = composed_plan + result.ops = composed_ops + result.session_note = ( + (result.session_note + " " if result.session_note + else "") + f"composed with your pending plan " + f"({plan_cache.pending_count()} ops total)") + except settings_planner.PlannerError as exc: + result.notes.append(f"composed plan refused: {exc}") + else: + plan_cache.compose(result.ops, text) + + # Issue #120 phase 4.3: near-threshold phrases are parked for batch + # review instead of being silently absorbed by the online learner. + if cortex_learn.is_near_threshold(result.verdict): + review_bucket = cortex_learn.log_review_candidate( + review_bucket, text, result.verdict, + result.candidates or [], at=_now()) + + # Inline delegation (routing fix, phase 1.2/1.3): the DELEGATE + # target runs in this turn — genius (as before, now generalized), + # diagnose, search, brain, issue, and the agent's simulated task + # graph. A failed inline run degrades to the hint card below. + if result.verdict == "DELEGATE" and result.delegate in runner_names(): + inline = run_delegate(result.delegate, text, state) + if inline is not None: + payload, inline_lines = inline + if args.json: + print(json.dumps( + {"type": "turn", "verdict": "DELEGATE", + "delegate": result.delegate, + result.delegate: payload}, default=str)) + else: + print("\n".join(_render_turn(result, inline_delegate=True))) + print("\n".join(inline_lines)) + if learner is not None: + episodes = memory_record(episodes, + episode_for(result, text, "routed", now=_now())) + continue + result.notes.append( + f"inline {result.delegate} run failed — the fallback hint stands") + + # Calibration surfacing (phase 2.4): the honest line users can + # hold the assistant to — observed accuracy for THIS confidence + # bucket, only when the sample can support a claim. The bucket + # key is the RAW route probability (learn_hook carries it); the + # calibrated confidence is a different quantity. + raw_p = ((result.learn_hook or {}).get("p", result.confidence) + if result.learn_hook is not None else result.confidence) + calibration_note = (learner.calibration_note(raw_p) + if learner is not None else None) + + applied = False + undone = False + if result.verdict == "PLAN": + if args.json: + if args.apply_confirmed and result.plan and len(result.plan.get("entries", [])) == 1: + try: + settings_applier.apply(result.plan, target, write=True, label=f"chat: {text}") + applied = True + except settings_applier.ApplierError as exc: + result.notes.append(f"apply failed: {exc}") + else: + applied = _apply_plan(result, target, text) + elif result.verdict == "UNDO": + if not args.json: + undone = _run_undo(result, target) + + if args.json: + payload = result.to_dict() + payload["type"] = "turn" + payload["applied"] = applied + payload["undone"] = undone + print(json.dumps(payload)) + else: + card = _render_turn(result, applied=applied) + if calibration_note: + card.append(f" {calibration_note}") + print("\n".join(card)) + if applied: + plan_cache.commit() + session.pending_plan = None + print(" applied (backup written; 'undo the last change' " + "reverts it)") + elif result.verdict == "PLAN" and plan_cache.pending_count(): + session.pending_plan = plan_cache.to_dict() + pending_line = plan_cache.summary() + if pending_line: + print(f" {pending_line} — compose the next change or " + "say 'apply these changes'") + + # Learning + memory (persisted through the brain state). + if learner is not None: + outcome = ("applied" if applied else + "undone" if undone else + "rejected" if result.verdict == "PLAN" else + "clarified" if result.verdict == "QUESTION" else + "routed" if result.verdict == "PLAN" else result.verdict.lower()) + if result.learn_hook is not None: + hook = result.learn_hook + learner.observe(hook["text"], hook["surface"], hook["features"], + hook["p"], outcome) + if applied and result.learn_hook is not None: + learner.reward_strategy(result.strategy or "balanced", True) + elif result.verdict == "PLAN" and not applied: + learner.reward_strategy(result.strategy or "balanced", False) + episodes = memory_record(episodes, episode_for(result, text, outcome, now=_now())) + # Proactive follow-up (second-brain suggestion, proposal only). + if applied and result.candidates: + suggestions = followup_suggestion( + episodes, result.candidates[0]["surface"], now=_now(), + halflife_days=resolve_halflife(state)) + for suggestion in suggestions[:1]: + print(f" suggestion: you often also change {suggestion['surface']} " + f"({suggestion['count']}x together) — say '{suggestion['surface'].replace('set', 'change ').strip()}' " + f"if you want it proposed") + + if learner is not None or episodes or review_bucket: + state = brain_state.load() + state[LEARN_KEY] = learner.to_dict() if learner is not None else state.get(LEARN_KEY) + state[MEMORY_KEY] = episodes + state["cortex_review"] = review_bucket + brain_state.save(state) + if not args.json: + print("session ended; learned routing and memory updated") + return 0 + + +# --------------------------------------------------------------------------- +# One-shot route. +# --------------------------------------------------------------------------- + + +def cmd_route(argv: Optional[List[str]] = None) -> int: + parser = argparse.ArgumentParser( + prog="caelestia-assist route", + description="one-shot universal routing: any phrase -> ranked surfaces + " + "validated plan (read-only, never writes)", + ) + parser.add_argument("text", help="the request phrase") + parser.add_argument("--file", default=None, help="target shell.json override") + parser.add_argument("--json", action="store_true", help="JSON output") + parser.add_argument("-k", type=int, default=5, help="top-k candidates") + args = parser.parse_args(argv) + + target = Path(args.file) if args.file else default_target() + state = brain_state.load() + learner = _load_learner(state) + result = cortex_process(args.text, learner=learner, file_path=target, now=_now()) + # Inline delegation (routing fix, phase 1.2/1.3): one-shot answers the + # same way the chat REPL does — run the target layer inline, render in + # the same turn; a failed run falls through to the hint card. + if result.verdict == "DELEGATE" and result.delegate in runner_names(): + inline = run_delegate(result.delegate, args.text, state) + if inline is not None: + payload, inline_lines = inline + if args.json: + print(json.dumps({"verdict": "DELEGATE", "delegate": result.delegate, + result.delegate: payload}, default=str)) + else: + print("\n".join(_render_turn(result, inline_delegate=True))) + print("\n".join(inline_lines)) + return 0 + result.notes.append( + f"inline {result.delegate} run failed — the fallback hint stands") + if args.json: + print(json.dumps(result.to_dict())) + else: + print("\n".join(_render_turn(result))) + return 0 + + +# --------------------------------------------------------------------------- +# Cortex management (report / recall / reset-learning / suggest). +# --------------------------------------------------------------------------- + + +def cmd_cortex(argv: Optional[List[str]] = None) -> int: + parser = argparse.ArgumentParser( + prog="caelestia-assist cortex", + description="the learned-intelligence dashboard: calibration, strategies, " + "drift, episodic memory, co-change suggestions", + ) + sub = parser.add_subparsers(dest="cmd", required=True) + sub.add_parser("report", help="learning + memory report") + recall_p = sub.add_parser("recall", help="recall past interactions") + recall_p.add_argument("query", nargs="?", default="", help="surface or text filter") + recall_p.add_argument("-k", type=int, default=10) + sub.add_parser("reset-learning", help="wipe learned routing weights (memory kept)") + suggest_p = sub.add_parser("suggest", help="co-change follow-up suggestions") + suggest_p.add_argument("surface", help="tool name just applied (e.g. setBarScale)") + suggest_p.add_argument("--apply", action="store_true", + help="record the suggestion as a pending LEDGER proposal " + "(still needs ledger approve to write)") + review_p = sub.add_parser("review", help="batch-review near-threshold phrases " + "(logged, never silently " + "learned)") + review_p.add_argument("action", nargs="?", default="list", + choices=["list", "label", "dismiss"]) + review_p.add_argument("arg1", nargs="?", default="", + help="label/dismiss: the candidate index (see list)") + review_p.add_argument("arg2", nargs="?", default="", + help="label: the correct surface (e.g. setBarScale)") + hl = sub.add_parser("halflife", help="read or set the memory decay " + "half-life in days (user-editable; " + "default 14, bounds 0.5-365)") + hl.add_argument("days", nargs="?", type=float, default=None, + help="new half-life in days (omit to read)") + conf_p = sub.add_parser("confusables", help="list the mined confusable " + "tool pairs and their clarifying questions " + "(A4: the ambiguity ask, made answerable)") + conf_p.add_argument("--mine", action="store_true", + help="rebuild the committed pairs artifact " + "(assistant/cortex/confusable_pairs.json) — a " + "reviewed change like a registry re-pin") + gaps_p = sub.add_parser("gaps", help="cluster the logged local-ontology gaps " + "(cloud hand-offs) and surface candidates") + gaps_p.add_argument("--propose", action="store_true", + help="record qualifying clusters as pending LEDGER " + "proposals (kind ontology_gap; approve/reject " + "decides — never auto-applied)") + gaps_p.add_argument("--min-support", type=int, default=3, + help="minimum requests per cluster (default 3, the " + "workspace.py floor)") + gaps_p.add_argument("--purity", type=float, default=0.6, + help="minimum modal-shape coverage (default 0.6, the " + "workspace.py floor)") + gaps_p.add_argument("--draft-stubs", action="store_true", + help="draft a reviewable tool-template stub file " + "(name, cue words, TODO body) for each dense, " + "unaddressed cluster — never registered, never " + "wired into the dispatcher, never clobbered " + "once a human edits it") + gaps_p.add_argument("--stubs-dir", default=None, + help="where stub drafts are written (default: " + "~/.local/state/caelestia-brain/tool_templates)") + lex_p = sub.add_parser("lexicon", help="federated, opt-in, signed " + "lexicon-diff sharing " + "(export/import/forget; no network, " + "no auto-merge — verify signatures " + "with YOUR external tool)") + lex_p.add_argument("action", choices=["export", "import", "forget", + "list", "trust"], + help="export: print the reviewable diff; import: apply a " + "diff from stdin as supervised pairs; forget: drop " + "one imported set by id; list: imported sets; " + "trust: the ADVISORY signer trust view (never " + "auto-decides anything)") + lex_p.add_argument("diff_id", nargs="?", default="", + help="forget: the diff id to drop (see list)") + lex_p.add_argument("--signer", default=None, + help="import: the identity YOU verified with your own " + "tool (minisign/sq/gpg) — recorded for the " + "advisory trust history only", ) + lex_p.add_argument("--dp", nargs="?", const=1.0, default=None, + type=float, metavar="EPSILON", + help="export: pass the export through the Laplace-" + "mechanism noising pass (cortex/dp.py, Dwork " + "et al. 2006) — per-row n/p are noised at " + "epsilon per export (default 1.0 when the " + "value is omitted) and every row carries a " + "(dp: epsilon=X) provenance marker; absent " + "flag = the exact export, byte-identical to " + "before") + lex_p.add_argument("--dp-seed", type=int, default=None, metavar="SEED", + help="export --dp: the noise seed (default: derived " + "deterministically from the diff's content id, " + "so the same diff noised twice is reproducible " + "— reproducible noise is NOT independent " + "across exports; pass any int for fresh noise)") + cn = sub.add_parser("concept", help="taught concepts (F15): user-named " + "bundles of validated tool calls, " + "recalled by phrase, Beta-posterior " + "learning, reviewable share diffs") + cn.add_argument("action", choices=["teach", "list", "forget", "recall", + "outcome", "export", "import"]) + cn.add_argument("name", nargs="?", default="", + help="teach/forget/outcome/recall: the concept name " + "(or free text for recall)") + cn.add_argument("--call", action="append", dest="calls", default=None, + metavar="TOOL=VALUE", + help="teach: a validated tool call (repeatable; every " + "tool must exist in the registry)") + cn.add_argument("--example", action="append", dest="examples", default=None, + help="teach: an example phrase that should recall this " + "concept (repeatable, up to 4)") + cn.add_argument("--accept", action="store_true", + help="outcome: the concept's plan was accepted (default " + "with --accept; omit for reject)") + cn.add_argument("--force", action="store_true", + help="import: overwrite existing concepts with the " + "same name (default: skip them)") + cn.set_defaults(fn=None) + + pw = sub.add_parser("power", help="predictive battery/thermal advice " + "(read-only; caller-supplied series, " + "inert suggestions)") + pw.add_argument("--battery", default=None, metavar="P,P,...", + help="battery capacity series in percent, uniformly " + "spaced (e.g. 80,78,76,74)") + pw.add_argument("--thermal", default=None, metavar="M,M,...", + help="thermal zone series in millidegrees C, uniformly " + "spaced") + pw.add_argument("--battery-minutes", type=float, default=30.0, + metavar="MIN", + help="minutes between battery samples (default 30)") + pw.add_argument("--thermal-minutes", type=float, default=5.0, + metavar="MIN", + help="minutes between thermal samples (default 5)") + pw.add_argument("--low", type=float, default=20.0, metavar="PCT", + help="battery low threshold in percent (default 20)") + pw.add_argument("--high", type=float, default=85000.0, metavar="MC", + help="thermal high threshold in millidegrees C " + "(default 85000 = 85 C)") + pz = sub.add_parser("personalize", help="F16 personalized " + "suggestions mined from your " + "approved history") + pz.add_argument("action", nargs="?", default="list", + choices=["list", "file"], + help="list = read-only mining view; file = file " + "qualifying suggestions into the brain ledger " + "(the #120 proposal surface; you approve/reject " + "there)") + pz.add_argument("--file", metavar="PATH", default=None, + help="settings target whose history to mine (default: " + "the settings layer's default shell.json)") + pz.add_argument("--ledger", metavar="PATH", default=None, + help="brain ledger path for file (default: the brain " + "CLI's DEFAULT_LEDGER)") + cx = sub.add_parser("context", help="F30 context-aware " + "recommendations (read-only probes, " + "inert commands)") + cx.add_argument("--probe", action="store_true", + help="read the real power state from " + "/sys/class/power_supply (read-only; without " + "this, no battery advice is made)") + cx.add_argument("--now", metavar="ISO", default=None, + help="anchor for hour-bucket selection (default: the " + "real clock — this is a pull-based verb)") + cx.add_argument("--ledger", metavar="PATH", default=None, + help="fit the preference model from this brain ledger " + "instead of the DEFAULT_LEDGER") + sc = sub.add_parser("schedule", help="F19 workspace schedules " + "(pull-based; nothing runs by " + "itself)") + sc.add_argument("action", choices=["save", "list", "delete", "eval", + "file"], + help="save = define (needs --name and --profile or " + "--preset, condition via --window/--on-battery); " + "list/delete/eval are read-only; file = file the " + "FIRING schedules into the brain ledger") + sc.add_argument("--name", default=None, help="schedule name") + sc.add_argument("--profile", default=None, + help="action: a saved profile (F9)") + sc.add_argument("--preset", default=None, help="action: a preset name") + sc.add_argument("--window", default=None, + help="condition: daily HH:MM-HH:MM (may wrap midnight)") + sc.add_argument("--on-battery", default=None, + choices=["true", "false"], + help="condition: fire when discharging (true) or " + "charging/on AC (false)") + sc.add_argument("--now", dest="sched_now", metavar="ISO", default=None, + help="eval/file: anchor time (default: the real clock " + "— eval is a pull-based verb)") + sc.add_argument("--probe", action="store_true", + help="eval/file: read the real power state (read-only)") + sc.add_argument("--file", metavar="PATH", default=None, + help="settings target whose schedules/history to use") + sc.add_argument("--ledger", metavar="PATH", default=None, + help="brain ledger for file (default: DEFAULT_LEDGER)") + rf = sub.add_parser("refit", help="F28 guarded weight re-fit: replay " + "the example log through a fresh " + "logistic, measure candidate vs " + "current on the dev arena, adopt " + "only on no regression") + rf.add_argument("--apply", action="store_true", + help="persist the candidate weights when the ratchet " + "adopts (default: measure and report only)") + tm = sub.add_parser("telemetry", help="engine coverage/accuracy " + "report; opt-in Laplace-DP export " + "(read-only, stdout only)") + tm.add_argument("--export", action="store_true", + help="print the shareable artifact instead of the " + "local report") + tm.add_argument("--dp", nargs="?", const=1.0, default=None, + type=float, metavar="EPSILON", + help="--export: pass the artifact through the Laplace " + "noising pass (cortex/dp.py's mechanism; default " + "epsilon 1.0 when the value is omitted)") + tm.add_argument("--dp-seed", type=int, default=None, metavar="SEED", + help="--export --dp: noise seed (default: derived from " + "the rows' content hash — reproducible, NOT " + "independent across exports)") + args = parser.parse_args(argv) + + state = brain_state.load() + learner = _load_learner(state) + episodes = _load_memory(state) + + if args.cmd == "halflife": + from .memory import (HALFLIFE_BOUNDS, HALFLIFE_DAYS, MEMORY_HALFLIFE_KEY, + resolve_halflife) + if args.days is None: + print(f"memory decay half-life: {resolve_halflife(state)} days " + f"(default {HALFLIFE_DAYS}; bounds " + f"{HALFLIFE_BOUNDS[0]}-{HALFLIFE_BOUNDS[1]})") + return 0 + lo, hi = HALFLIFE_BOUNDS + if not (lo <= args.days <= hi): + print(f"error: half-life must be within {lo}-{hi} days", + file=sys.stderr) + return 1 + state[MEMORY_HALFLIFE_KEY] = args.days + brain_state.save(state) + print(f"memory decay half-life set to {args.days} days " + "(affects recall weighting from now on; history untouched)") + return 0 + + if args.cmd == "power": + # exponential-build-3 E2: read-only advisory over caller- + # supplied series. Suggestions are INERT SUGGESTED_NOT_EXECUTED + # strings; nothing writes, nothing executes. + from . import power_advisor + battery = thermal = None + try: + if args.battery is not None: + battery = [float(x) for x in args.battery.split(",") + if x.strip()] + if args.thermal is not None: + thermal = [float(x) for x in args.thermal.split(",") + if x.strip()] + except ValueError: + print("error: --battery/--thermal need comma-separated " + "numbers", file=sys.stderr) + return 2 + if battery is None and thermal is None: + print("error: pass --battery P,P,... and/or --thermal M,M,... " + "(telemetry series are caller-supplied; no persistent " + "sampler ships yet — sample with the on-demand probes " + "and pass the series)", file=sys.stderr) + return 2 + try: + if battery is not None: + report_b = power_advisor.advise_battery( + battery, sample_minutes=args.battery_minutes, + low_pct=args.low) + if thermal is not None: + report_t = power_advisor.advise_thermal( + thermal, sample_minutes=args.thermal_minutes, + high_mc=args.high) + except ValueError as exc: + print(f"error: {exc}", file=sys.stderr) + return 1 + halves = [] + if battery is not None: + halves.append(("battery", report_b)) + if thermal is not None: + halves.append(("thermal", report_t)) + for title, r in halves: + print(f"{title}:") + if not r.get("available"): + print(f" {r['reason']}") + continue + if title == "battery": + print(f" level {r['level']:g}%, trend " + f"{r['trend_pct_per_hour']:+.2f}%/h" + + (" (charging)" if r["charging"] else "")) + if r["minutes_to_low"] is not None: + print(f" projected to reach " + f"{r['low_threshold_pct']:g}% in ~" + f"{r['minutes_to_low'] / 60:.1f} h") + else: + print(f" level {r['level_mc'] / 1000:.1f} C, trend " + f"{r['trend_mc_per_sample'] / 1000:+.2f} C/sample") + if r["minutes_to_high"] is not None: + print(f" projected to reach " + f"{r['high_threshold_mc'] / 1000:.0f} C in ~" + f"{r['minutes_to_high']:.0f} min") + path = "; ".join( + f"{f['point']} [{f['low']}, {f['high']}]" + for f in r["forecast"][:3]) + print(f" forecast: {path} ... ({r['interval_note']})") + cp = r["changepoint"] + if cp.get("recent"): + print(" changepoint: RECENT regime change — " + "trend extrapolation is built on mixed history") + elif cp.get("checked"): + print(f" changepoint: {cp['note']}") + else: + print(f" changepoint: {cp['note']}") + if r.get("suggestion"): + print(f" {r['suggestion']}") + return 0 + + if args.cmd == "personalize": + # F16: personalized suggestions mined from CONSENTED evidence + # (the settings history ring holds only approved applies). + # list = read-only; file = writes ONLY the brain ledger, the + # same #120 proposal surface every other proposal rides — the + # approve/reject decision is the user's, through the existing + # flow. Filing is an explicit verb, never a background loop. + from . import personalize + from assistant.capabilities.settings.history import entries as history_entries + from assistant.capabilities.settings.cli import default_target + target = Path(args.file) if args.file else default_target() + try: + entries = history_entries(target) + except Exception as exc: + print(f"error: cannot read the settings history at {target}: " + f"{exc}", file=sys.stderr) + return 1 + mined = personalize.mine(entries) + if args.action == "list": + print("\n".join(personalize.render_lines(mined))) + return 0 + from assistant.capabilities.brain.cli import DEFAULT_LEDGER + from assistant.capabilities.brain.ledger import Ledger + ledger = Ledger(Path(args.ledger) if args.ledger else DEFAULT_LEDGER) + stats = personalize.file_suggestions(mined, ledger) + print(f"filed {stats['filed']} suggestion(s) into " + f"{ledger.path} " + f"(pending duplicates skipped: " + f"{stats['skipped_pending']}, recently decided skipped: " + f"{stats['skipped_cooldown']})") + if stats["filed"] == 0: + print("nothing new to file (already pending, recently " + "decided, or below the evidence floors)") + print("decide via: caelestia-assist inbox (the unified " + "pending-decisions view; or brain ledger approve|reject)") + return 0 + + if args.cmd == "context": + # F30: context-aware recommendations. Read-only probes; the + # command strings are SUGGESTED_NOT_EXECUTED; the clock selects, + # it never supplies evidence. + from . import context as context_mod + from datetime import datetime as _dt + now = None + if args.now: + try: + now = _dt.fromisoformat(args.now) + except ValueError: + print("error: --now needs an ISO-8601 datetime", + file=sys.stderr) + return 2 + else: + now = _dt.now() + power = context_mod.read_power_state() if args.probe else None + model = None + from assistant.capabilities.brain.cli import DEFAULT_LEDGER + from assistant.capabilities.brain.ledger import Ledger + from assistant.capabilities.brain.prefs import PreferenceModel + ledger_path = args.ledger or str(DEFAULT_LEDGER) + if Path(ledger_path).exists(): + model = PreferenceModel() + model.from_ledger(Ledger(ledger_path).items) + if not model.table: + model = None + view = context_mod.recommend_contextual(now=now, power=power, + model=model) + print("\n".join(context_mod.render_lines(view))) + return 0 + + if args.cmd == "schedule": + # F19: pull-based workspace schedules. eval/file are explicit + # verbs; nothing runs by itself, ever. + from . import schedules as sched_mod + from assistant.capabilities.settings.cli import default_target + from assistant.capabilities.settings.history import HistoryError + target = Path(args.file) if args.file else default_target() + try: + if args.action == "save": + if not args.name: + print("error: save needs --name", file=sys.stderr) + return 2 + on_battery = (None if args.on_battery is None + else args.on_battery == "true") + entry = sched_mod.save( + target, args.name, profile=args.profile, + preset=args.preset, window=args.window, + on_battery=on_battery) + print(f"saved schedule {entry['name']!r} " + f"(window {entry.get('window')}, " + f"on-battery {entry.get('on_battery')})") + print("check it with: cortex schedule eval") + return 0 + if args.action == "list": + saved = sched_mod.list_schedules(target) + if not saved: + print("no schedules defined; define one with " + "schedule save --name N --profile P " + "--window HH:MM-HH:MM") + for s in saved: + print(f" {s['name']:<20} action={s['action']} " + f"window={s.get('window')} " + f"on-battery={s.get('on_battery')}") + return 0 + if args.action == "delete": + if not args.name: + print("error: delete needs --name", file=sys.stderr) + return 2 + result = sched_mod.delete(target, args.name) + print(f"deleted schedule {result['deleted']!r}") + return 0 + # eval / file + from datetime import datetime as _dt + if args.sched_now: + try: + now = _dt.fromisoformat(args.sched_now) + except ValueError: + print("error: --now needs an ISO-8601 datetime", + file=sys.stderr) + return 2 + else: + now = _dt.now() + power = (context_probe_power() if args.probe else None) + result = sched_mod.evaluate(target, now=now, power=power) + print("\n".join(sched_mod.render_eval(result))) + if args.action == "file": + from assistant.capabilities.brain.cli import DEFAULT_LEDGER + from assistant.capabilities.brain.ledger import Ledger + ledger = Ledger(Path(args.ledger) if args.ledger + else DEFAULT_LEDGER) + stats = sched_mod.file_firing(result, ledger, now=now) + print(f"filed {stats['filed']} firing schedule(s) into " + f"the ledger (pending duplicates skipped: " + f"{stats['skipped_pending']}, recently decided " + f"skipped: {stats['skipped_cooldown']})") + return 0 + except sched_mod.ScheduleError as exc: + print(f"error: {exc}", file=sys.stderr) + return 1 + except HistoryError as exc: + print(f"error: {exc}", file=sys.stderr) + return 1 + + if args.cmd == "refit": + # F28: the guarded re-fit. The arena measurement decides; the + # audit trail records every decision; --apply persists the + # candidate model ONLY when the ratchet adopted it. + from . import refit as refit_mod + from .learn import LEARN_KEY + from .learn import CortexLearner + state = brain_state.load() + learner_data = dict(state.get(LEARN_KEY) or {}) + result = refit_mod.refit_ratchet(learner_data, state) + if result["adopted"] and args.apply: + learner_data["model"] = result["candidate_model"] + state[LEARN_KEY] = learner_data + brain_state.save(state) + print("\n".join(refit_mod.render_lines(result))) + if result["adopted"] and not args.apply: + print("(dry-run: re-run with --apply to persist the " + "candidate weights)") + return 0 + + if args.cmd == "telemetry": + # exponential-build-3 F3: coverage/accuracy-only engine metrics, + # opt-in Laplace-DP export via the B4 mechanism. Read-only. + from . import features as capabilities + if not capabilities.enabled("engine_telemetry"): + print("error: engine_telemetry is disabled in the capability " + "manifest (edit capabilities.json to enable; it cannot " + "be enabled by a request)", file=sys.stderr) + return 1 + from . import engine_telemetry + rows = engine_telemetry.metrics(learner) + if not rows: + print("no routed examples logged yet — nothing to report " + "(the engine logs its own routed turns locally)") + return 0 + if not args.export: + print("engine telemetry (coverage/accuracy only — no text, " + "no phrases, no features leave this machine unless you " + "--export)") + for row in rows: + thin = " (thin)" if row["n"] < engine_telemetry.MIN_N \ + else "" + acc = "-" if row["accuracy"] is None \ + else f"{row['accuracy']:.2f}" + cov = "-" if row["coverage"] is None \ + else f"{row['coverage']:.2f}" + print(f" {row['surface']:<28} n={row['n']:>3} " + f"decided={row['decided']:>3} coverage={cov:<5} " + f"accuracy={acc}{thin}") + print("export opt-in: telemetry --export [--dp EPSILON] " + "(exact artifact is local read-back; --dp applies the " + "Laplace mechanism per Dwork et al. 2006)") + return 0 + date = datetime.now().strftime("%Y-%m-%d") + if args.dp is None: + sys.stdout.write(engine_telemetry.export_text(rows, date=date)) + print("# (exact artifact — local read-back; use --dp for the " + "shareable noised form)", file=sys.stderr) + return 0 + try: + noised = engine_telemetry.noise_metrics( + rows, epsilon=args.dp, seed=args.dp_seed) + except ValueError as exc: + print(f"error: {exc}", file=sys.stderr) + return 1 + sys.stdout.write(engine_telemetry.export_text( + noised["rows"], date=date, dp=noised)) + print(f"# (dp) epsilon={noised['epsilon']:g}, " + f"seed={noised['seed']}: " + f"n floored at zero: {noised['n_floored_at_zero']}; " + f"rates clipped to [0,1]: {noised['p_clipped']}", + file=sys.stderr) + print("# (dp) composition: k sequential exports compose to roughly " + "k*epsilon (Dwork & Roth 2014) — the practical bound is how " + "often you export", file=sys.stderr) + return 0 + + if args.cmd == "concept": + from . import concepts + state = brain_state.load() + try: + if args.action == "teach": + if not args.name or not args.calls: + print("error: teach needs a NAME and at least one " + "--call TOOL=VALUE", file=sys.stderr) + return 2 + hit = concepts.teach(state, args.name, args.calls, + examples=args.examples, + source="cli-explicit") + brain_state.save(state) + print(f"taught concept '{hit['name']}' with " + f"{len(hit['calls'])} call(s) " + f"({hit['n_concepts']} concepts stored); nothing " + "applied — recall only proposes, the consent gate " + "applies") + return 0 + if args.action == "list": + rows = concepts.list_concepts(state) + if not rows: + print("no taught concepts yet — teach one: cortex " + "concept teach glassy --call setBlurEnabled=true") + return 0 + for r in rows: + p = ", ".join(f"{x['tool']}={x['value']!r}" + + (f" p={x['p']} n={x['n']}" + if x["p"] is not None else "") + for x in r["posterior"]) + print(f"{r['name']}: {p}") + if r["examples"]: + print(f" phrases: {'; '.join(r['examples'])}") + return 0 + if args.action == "forget": + if concepts.forget(state, args.name): + brain_state.save(state) + print(f"forgot concept '{args.name}'") + return 0 + print(f"error: unknown concept '{args.name}'", + file=sys.stderr) + return 2 + if args.action == "recall": + from assistant.capabilities.settings.curations import PRESETS + hit = concepts.recall(state, args.name, presets=PRESETS) + print(f"verdict: {hit['verdict']}") + if hit["verdict"] == "RECALL": + for c in hit["calls"]: + print(f" {c['name']} = {c['value']!r}") + print(" (proposal only — the consent gate applies)") + return 0 + if args.action == "outcome": + hit = concepts.record_outcome(state, args.name, + accepted=bool(args.accept)) + brain_state.save(state) + print(f"recorded {'accept' if hit['accepted'] else 'reject'} " + f"for '{hit['name']}'") + return 0 + if args.action == "export": + names = [args.name] if args.name else None + print(json.dumps(concepts.export_diff(state, names), + indent=1, ensure_ascii=False)) + return 0 + if args.action == "import": + entries = json.load(sys.stdin) + res = concepts.import_diff(state, entries, + force=bool(args.force)) + brain_state.save(state) + print(f"import: {res['added']} added, {res['updated']} " + f"updated, {res['skipped']} skipped (existing; " + "use --force to overwrite)") + return 0 + except concepts.ConceptError as exc: + print(f"error: {exc}", file=sys.stderr) + return 2 + + if args.cmd == "lexicon": + from . import features as capabilities + if not capabilities.enabled("lexicon_sharing"): + print("error: lexicon_sharing is disabled in the capability " + "manifest (edit capabilities.json to enable; it cannot " + "be enabled by a request)", file=sys.stderr) + return 1 + from . import lexicon_diff + if args.action == "export": + rows = lexicon_diff.export_rows(state) + if not rows: + print("nothing learned to share yet (the learner's example " + "log is empty)") + return 0 + if args.dp is not None: + # opt-in (exponential-build 3 B4): the Laplace-mechanism + # noising pass over the export artifact; the default + # path below stays byte-identical when the flag is absent + from . import dp + try: + report = dp.noise_diff( + rows, epsilon=args.dp, seed=args.dp_seed, + date=datetime.now().strftime("%Y-%m-%d")) + except ValueError as exc: + print(f"error: {exc}", file=sys.stderr) + return 1 + sys.stdout.write(report["text"]) + print(f"# (dp) epsilon={report['epsilon']:g}, " + f"seed={report['seed']}: " + f"{report['rows_out']}/{report['rows_in']} rows " + f"kept; n floored at zero: " + f"{report['n_floored_at_zero']}; p clipped to " + f"[0,1]: {report['p_clipped']}; " + f"{report['guarantee']}", file=sys.stderr) + print("# (dp) composition: k sequential exports compose to " + "roughly k*epsilon (Dwork & Roth 2014) — the " + "practical bound is how often you export", + file=sys.stderr) + print("# export is read-only: sign it with YOUR external tool " + "(minisign/sq/gpg) before sharing", file=sys.stderr) + return 0 + sys.stdout.write(lexicon_diff.render( + rows, date=datetime.now().strftime("%Y-%m-%d"))) + print("# export is read-only: sign it with YOUR external tool " + "(minisign/sq/gpg) before sharing", file=sys.stderr) + return 0 + if args.action == "import": + text = sys.stdin.read() + report = lexicon_diff.import_diff(state, text, signer=args.signer) + if "error" in report: + print(f"error: {report['error']}", file=sys.stderr) + for warn in report.get("warnings", []): + print(f" warning: {warn}", file=sys.stderr) + return 1 + brain_state.save(state) + print(f"imported diff {report['diff_id']}: " + f"{report['imported']} pair(s)") + print(" tools this diff boosts (review them):") + for tool in report["boosted_tools"]: + print(f" - {tool}") + for warn in report.get("warnings", []): + print(f" warning: {warn}") + print(f" {report['note']}") + if report.get("signer_trust"): + print(f" {report['signer_trust']}") + print(f" {report['verify']}") + print(f" rollback: {report['rollback']}") + return 0 + if args.action == "forget": + report = lexicon_diff.forget(state, args.diff_id) + if "error" in report: + print(f"error: {report['error']}", file=sys.stderr) + return 1 + brain_state.save(state) + print(f"forgot {report['forgot']} " + f"({report['rows_dropped']} row(s)); {report['note']}") + return 0 + if args.action == "trust": + scores = lexicon_diff.signer_trust(state) + if not scores: + print("no signer history — imports without --signer " + "record nothing; trust starts at the flat prior") + return 0 + print(lexicon_diff.render_advisory(scores)) + return 0 + # list + ids = lexicon_diff.imported_ids(state) + if not ids: + print("no imported lexicon diffs") + return 0 + imports = state.get(lexicon_diff.IMPORTS_KEY) or {} + for did in ids: + entry = imports.get(did) or {} + print(f" {did} {entry.get('n', '?')} pair(s)") + print("forget with: cortex lexicon forget ") + return 0 + + if args.cmd == "report": + print("\n".join(_render_report(learner, episodes))) + return 0 + + if args.cmd == "recall": + rows = memory_recall(episodes, args.query, now=_now(), k=args.k, + halflife_days=resolve_halflife(state)) + if not rows: + print("no matching episodes in memory") + return 0 + for row in rows: + surfaces = ", ".join(str(s) for s in row.get("surfaces", [])) + print(f" [{row.get('at')}] {row.get('outcome')}: {row.get('text')}" + + (f" -> {surfaces}" if surfaces else "")) + return 0 + + if args.cmd == "reset-learning": + state[LEARN_KEY] = CortexLearner().to_dict() + brain_state.save(state) + print("learned routing weights reset to priors (memory kept)") + return 0 + + if args.cmd == "review": + from . import learn as cortex_learn + bucket = list(state.get(cortex_learn.REVIEW_KEY, [])) + if args.action == "list": + if not bucket: + print("no near-threshold candidates logged yet (ambiguous or " + "abstained chat phrases land here)") + return 0 + print(f"{len(bucket)} candidate(s), oldest last:") + for i, c in enumerate(bucket): + print(f" [{i}] {c['verdict']:<8} p={c.get('p')} :: {c['text']}") + print("label with: cortex review label INDEX SURFACE " + "(teaches the router, nothing applies)") + print("drop with: cortex review dismiss INDEX") + return 0 + if learner is None: + print("learning is disabled (--no-learn or no state); cannot label", + file=sys.stderr) + return 1 + try: + if args.action == "label": + if not args.arg1 or not args.arg2: + print("review label needs INDEX and SURFACE", file=sys.stderr) + return 2 + res = cortex_learn.label_candidate(state, int(args.arg1), + args.arg2, learner) + state[LEARN_KEY] = learner.to_dict() + brain_state.save(state) + print(f"taught: {res['text']!r} -> {res['surface']} " + f"({res['remaining']} candidate(s) left)") + else: + res = cortex_learn.dismiss_candidate(state, int(args.arg1)) + brain_state.save(state) + print(f"dismissed: {res['text']!r} ({res['remaining']} left)") + return 0 + except (ValueError, KeyError) as exc: + print(f"error: {exc}", file=sys.stderr) + return 1 + + if args.cmd == "confusables": + from assistant.core.features import enabled + if not enabled("confusable_clarifier"): + print("confusable_clarifier is disabled in the capability " + "manifest (edit capabilities.json to enable; it cannot " + "be enabled from a request)", file=sys.stderr) + return 1 + from . import confusables + if args.mine: + data = confusables.mine_pairs() + confusables.PAIRS_PATH.write_text( + json.dumps(data, indent=1, ensure_ascii=False) + "\n", + encoding="utf-8") + print(f"wrote {confusables.PAIRS_PATH.name}: " + f"{data['n_pairs']} pairs") + return 0 + for line in confusables.render_lines(): + print(line) + return 0 + + if args.cmd == "gaps": + from .dispatch import (cluster_gaps, propose_gap_clusters, + select_stub_candidates, tool_template_slug, + tool_template_stub_text) + from assistant.capabilities.brain.cli import DEFAULT_LEDGER + from assistant.capabilities.brain.ledger import Ledger + + # Stub selection runs BEFORE any proposal is filed, so one run can + # both file the ledger proposal and leave the human a reviewable + # scaffold to look at while that proposal is still pending. A + # cluster the ledger already knows about (any status) is addressed: + # the ledger flow IS the address, no second review surface. + draft_report = None + if args.draft_stubs: + sel = select_stub_candidates(state, Ledger(DEFAULT_LEDGER), + min_support=args.min_support, + purity=args.purity) + out_dir = (Path(args.stubs_dir) if args.stubs_dir else + Path.home() / + ".local/state/caelestia-brain/tool_templates") + drafted, skipped_existing = [], [] + for cand in sel["unaddressed"]: + slug = tool_template_slug(cand["label"]) + path = out_dir / f"{slug}.md" + if path.exists(): + # A stub that already exists may carry human edits — + # never clobbered, reported instead. + skipped_existing.append(slug) + continue + if not out_dir.exists(): + out_dir.mkdir(parents=True, exist_ok=True) + path.write_text( + tool_template_stub_text( + cand, datetime.now().isoformat(timespec="seconds")), + encoding="utf-8") + drafted.append(slug) + draft_report = {"dir": out_dir, "drafted": drafted, + "skipped_existing": skipped_existing, + "addressed": [c["label"] + for c in sel["addressed"]]} + + if args.propose: + res = propose_gap_clusters(state, Ledger(DEFAULT_LEDGER), + min_support=args.min_support, + purity=args.purity) + if res["proposals"]: + print(f"{len(res['proposals'])} pending proposal(s) recorded " + f"(kind ontology_gap) — `caelestia-assist brain ledger` " + f"decides; nothing is applied automatically") + else: + print("no qualifying cluster reached the support/purity floor " + "— nothing proposed") + summary = res["summary"] + else: + summary = cluster_gaps(state, min_support=args.min_support, + purity=args.purity) + print(f"local-ontology gaps: {summary['n_gaps']} logged shape(s); " + f"k={summary['k']}, {summary['rejected_clusters']} cluster(s) " + f"below the support/purity floor") + if not summary["candidates"]: + print("no candidate local tools — a handful of scattered gaps is " + "noise, not a need (by design)") + for c in summary["candidates"]: + print(f" {c['support']}x \"{c['label']}\" " + f"(category {c['category']}, purity {c['purity']}, " + f"{c['shapes']} phrasing(s))") + if summary["candidates"] and not args.propose: + print("surface with: cortex gaps --propose (ledger proposals, " + "never auto-applied)") + if draft_report is not None: + d = draft_report + if d["drafted"]: + print(f"drafted {len(d['drafted'])} tool-template stub(s) " + f"in {d['dir']}: {', '.join(d['drafted'])}") + print(" stubs are DRAFT files only — never registered, " + "never wired into the dispatcher; a human writes the " + "real module") + else: + print("no stub drafted — every qualifying cluster is " + "already addressed in the ledger or already has its " + "stub file") + if d["skipped_existing"]: + print(f" skipped {len(d['skipped_existing'])} existing " + f"stub file(s) (never clobbered)") + if d["addressed"]: + print(f" {len(d['addressed'])} cluster(s) already " + f"addressed in the ledger (no second review " + f"surface): {'; '.join(d['addressed'])}") + return 0 + + if args.cmd == "suggest": + suggestions = followup_suggestion(episodes, args.surface, now=_now(), + halflife_days=resolve_halflife(state)) + if not suggestions: + print(f"no co-change pattern with {args.surface} yet " + f"(needs repeated applied history)") + return 0 + for suggestion in suggestions: + print(f" {suggestion['surface']}: {suggestion['count']}x together, " + f"decay-weighted score {suggestion['weight']}") + if args.apply: + from assistant.capabilities.brain import ledger as brain_ledger + from assistant.capabilities.brain import settings_bridge + top = suggestions[0]["surface"] + # brain/ledger.py exposes the Ledger class (no module-level + # load/save helpers); use DEFAULT_LEDGER for continuity with the + # brain CLI's proposal store. + from assistant.capabilities.brain.cli import DEFAULT_LEDGER + ledger = brain_ledger.Ledger(DEFAULT_LEDGER) + pid = settings_bridge.propose( + ledger, str(default_target()), None, [], + reason=f"cortex co-change suggestion after {args.surface} " + f"({top} changed together {suggestions[0]['count']}x)", + confidence=round(min(0.9, 0.4 + 0.1 * suggestions[0]["count"]), 2), + ) + if pid is None: + print("nothing to propose (the dry-run plan was blocked or a no-op)") + else: + print(f"ledger proposal {pid} created (approve with: " + f"caelestia-assist brain ledger approve {pid})") + return 0 + + return 2 + + +# --------------------------------------------------------------------------- +# Entry points. +# --------------------------------------------------------------------------- + + +def main(argv: Optional[List[str]] = None) -> int: + argv = list(argv if argv is not None else []) + if not argv: + argv = ["--help"] + if argv[0] == "chat": + return cmd_chat(argv[1:]) + if argv[0] == "route": + return cmd_route(argv[1:]) + if argv[0] in ("report", "recall", "reset-learning", "suggest", "review"): + return cmd_cortex(argv) + return cmd_cortex(argv) + + +def context_probe_power(): + """One read-only power probe (F30's reader), shared by the schedule + verbs.""" + from . import context as context_mod + return context_mod.read_power_state() + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/plugins/caelestia-assistant/assistant/core/coldstart.py b/plugins/caelestia-assistant/assistant/core/coldstart.py new file mode 100644 index 0000000..04afbf1 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/core/coldstart.py @@ -0,0 +1,143 @@ +"""cortex.coldstart — DP-noised community priors for a fresh install +(exponential-build-4 G). + +The gap: a new install's bandits start flat (Beta(1,1) everywhere) and +learn the user's tool-usage shape from zero. The community fix: users +who already have history EXPORT a noised summary of their bandit +evidence; a fresh install IMPORTS it as its starting priors instead of +flat ones. + +THE PRIVACY MECHANISM IS NOT NEW — deliberately. cortex/dp.py's +Laplace mechanism (Dwork, McSherry, Nissim & Smith 2006) was built for +the lexicon-diff export; this module REUSES it (dp.laplace_noise, the +same inverse-CDF sampling, the same sensitivity accounting, the same +epsilon semantics) pointed at bandit evidence instead of phrase +counts. Per-arm sensitivities: alpha and beta are per-user COUNTS in +the neighboring relation "this user's history in / out", so +N_SENSITIVITY = 1.0 each — the same accounting dp.py already +documents. Composition across arms: the export noises each arm +independently at the caller's epsilon (the artifact records the +epsilon it was made at; importing does not re-noise). + +What is exported: the Beta POSTERIOR parameters (alpha, beta) per +strategy/tool arm — aggregates, never rows. Post-processing is the +standard DP kind: noised parameters are CLIPPED to the flat-prior +floor (1.0) on import, and the clip is recorded in the import report; +noising first then clipping keeps the DP guarantee (post-processing +of DP output is DP). + +Honesty: the imported priors are EVIDENCE WITH PROVENANCE, not +truth — the import report carries the artifact's epsilon, the marker +string, and per-arm clip status; a user can inspect the artifact +(canonical JSON) before importing; and nothing forces the import +(flat priors remain the default). State stays in the caller's +learned-state JSON; nothing here writes. +""" +from __future__ import annotations + +import random +from typing import Any, Dict, List + +from .dp import N_SENSITIVITY, laplace_noise + +__all__ = ["SCHEMA", "STATE_KEY", "DEFAULT_EPSILON", "export_priors", + "import_priors", "bootstrap_learner"] + +SCHEMA = "caelestia-coldstart/1" +STATE_KEY = "community_priors" +DEFAULT_EPSILON = 1.0 +_FLAT_FLOOR = 1.0 +#: the prior CEILING per arm (pseudo-observations). An imported prior is +#: EVIDENCE, not a verdict: past this mass the "prior" would dominate +#: any amount of the user's own lived evidence, which is the hostile- +#: artifact failure mode the build-4 adversarial sweep caught (an +#: unbounded beta could permanently silence an arm). Clipped down and +#: reported — standard DP post-processing either way. +_MAX_PRIOR_MASS = 1000.0 + + +def export_priors(arms: Dict[str, List[float]], epsilon: float, + rng: random.Random) -> Dict[str, Any]: + """One learner's Beta arms -> the DP-noised community artifact. + + ``arms``: {name: [alpha, beta]} exactly as NamedBandit persists + them. Each parameter is noised independently at + Laplace(0, N_SENSITIVITY / epsilon). Negative or sub-floor noised + values are LEFT IN THE ARTIFACT (the importer clips — clipping is + post-processing either way, and the artifact should show the true + noised draw rather than a pre-chewed one).""" + if epsilon <= 0: + raise ValueError("epsilon must be > 0 (a noise scale is not " + "definable from a non-positive epsilon)") + noised: Dict[str, Dict[str, float]] = {} + for name in sorted(arms): + alpha, beta = float(arms[name][0]), float(arms[name][1]) + noised[name] = { + "alpha": round(laplace_noise(alpha, N_SENSITIVITY, epsilon, rng), 4), + "beta": round(laplace_noise(beta, N_SENSITIVITY, epsilon, rng), 4), + } + return { + "schema": SCHEMA, + "epsilon": epsilon, + "sensitivity": N_SENSITIVITY, + "mechanism": "Laplace (cortex/dp.py), per-arm independent " + "draws; aggregates only, never rows", + "arms": noised, + } + + +def import_priors(artifact: Dict[str, Any], + target_arms: Dict[str, List[float]] + ) -> Dict[str, Any]: + """Clip-and-merge one artifact into a learner's arm state. + + ``target_arms`` is the learner's CURRENT {name: [alpha, beta]} + dict, mutated in place (the caller persists through the usual + state path). Arms not present in the artifact keep their current + posterior (an import ADDS evidence, it never deletes it). + Returns the per-arm report: prior, noised, floored.""" + if not isinstance(artifact, dict) or artifact.get("schema") != SCHEMA: + raise ValueError( + f"artifact schema must be {SCHEMA!r} — refusing an " + "unversioned or foreign artifact") + epsilon = artifact.get("epsilon") + if not isinstance(epsilon, (int, float)) or epsilon <= 0: + raise ValueError("artifact epsilon must be a positive number") + report: List[Dict[str, Any]] = [] + for name, pair in sorted((artifact.get("arms") or {}).items()): + try: + alpha = float(pair["alpha"]) + beta = float(pair["beta"]) + except (KeyError, TypeError, ValueError) as exc: + raise ValueError( + f"arm {name!r} lacks numeric alpha/beta: {exc}") from exc + a0, b0 = target_arms.get(name, [_FLAT_FLOOR, _FLAT_FLOOR]) + clipped = False + capped = False + if alpha < _FLAT_FLOOR: + alpha, clipped = _FLAT_FLOOR, True + if beta < _FLAT_FLOOR: + beta, clipped = _FLAT_FLOOR, True + if alpha > _MAX_PRIOR_MASS: + alpha, capped = _MAX_PRIOR_MASS, True + if beta > _MAX_PRIOR_MASS: + beta, capped = _MAX_PRIOR_MASS, True + target_arms[name] = [round(alpha, 4), round(beta, 4)] + report.append({"arm": name, + "prior": [round(float(a0), 4), round(float(b0), 4)], + "imported": [round(alpha, 4), round(beta, 4)], + "clipped_to_flat_floor": clipped, + "capped_at_prior_ceiling": capped}) + return {"epsilon": epsilon, "arms": report, + "note": "evidence with provenance: the artifact's epsilon " + "and clipping are recorded; flat priors remain the " + "default and nothing forces an import"} + + +def bootstrap_learner(learner: Any, artifact: Dict[str, Any]) -> Dict[str, Any]: + """Wire the import into the learner's strategy bandit: the noised + community evidence becomes the bandit's starting Beta state (the + cold-start the module exists for). The learner's other state + (model, calibration, examples) is untouched.""" + report = import_priors(artifact, learner.bandit.arms) + return report diff --git a/plugins/caelestia-assistant/assistant/core/compound.py b/plugins/caelestia-assistant/assistant/core/compound.py new file mode 100755 index 0000000..0b57a69 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/core/compound.py @@ -0,0 +1,260 @@ +"""Multi-intent clause splitting: one sentence, many settings. + +parser.py deliberately refuses compound requests ("multiple value phrases +found in one request; split that into separate requests") because a +frozen grammar cannot attribute values to tools safely. The cortex +router can: each clause gets routed independently, and the pipeline +composes the per-clause plans into one multi-op proposal — which then +goes through the SAME multi-change confirmation gate (``--confirm`` / +ledger approval) that single-sentence multi-setting presets use. + +Algorithm — deterministic clause segmentation: + +1. Split on coordinating/contrastive conjunctions and commas OUTSIDE + any protectable span. Splits happen only when BOTH sides carry + addressable content (a noun hit, a direction/bool/position/number + cue, or a non-stopword token count above threshold) — "blur and + transparency" is one concept, "disable blur and move the bar up" is + two intents. +2. Contrast scope: "but keep the blur on" / "except the dock" clauses + are marked ``contrast`` so the pipeline treats them as + negative-scoped (a request to NOT touch, or to restore, that thing) + rather than a second change. +3. Each clause is routed via router.route; clause results are merged + left-to-right (later clauses win conflicts, mirroring how humans + read "make it bigger but the dock smaller"). + +PURE module: no I/O, no randomness. Deterministic for identical input. +""" + +from __future__ import annotations + +import re +from dataclasses import dataclass, field +from typing import Dict, List, Tuple + +from .router import RouteResult, RouterState, DEFAULT_STATE, route + +# Split points: coordinating conjunctions, additive adverbs, commas, +# semicolons, and "then" sequencing. Contrast markers are recorded but +# flagged (the clause is a modifier of intent, not a new one). +_SPLIT_RE = re.compile( + r"\s+(?:and|also|plus|then|after that|while you're at it)\s+|[,;]\s+" +) +_CONTRAST_SPLIT_RE = re.compile(r"\s+(?:but|except|however|although|instead)\s+") +# Contrast clauses often carry a keep/leave verb phrase — protected from +# being misread as a change request when composed. +_CONTRAST_KEEP_RE = re.compile( + r"\b(?:keep|leave|stay|maintain|don'?t (?:touch|change|move)|do not (?:touch|change|move))\b", + re.IGNORECASE, +) + +# A clause must carry at least one addressable signal to be routable on +# its own: a cue, or this many non-stopword tokens. +_MIN_CONTENT_TOKENS = 1 + +# Words that make a clause a follow-up modifier rather than an intent: +# "a bit smaller", "a little more", "same for the dock". +_MODIFIER_RE = re.compile(r"^\s*(?:a\s+(?:bit|little|tad|touch)|same(?:\s+for|\s+too|\s+with)|me\s+too|also)\b", re.IGNORECASE) + + +@dataclass +class Clause: + """One split-out piece of the original request.""" + + text: str # clause text, stripped, lowercased + contrast: bool # True when introduced by but/except/... + keep: bool # True when the clause says "keep/leave X" + position: int # clause order index (0-based) + + +@dataclass +class CompoundResult: + """Routed clauses plus composition guidance.""" + + clauses: List[Clause] = field(default_factory=list) + routes: List[RouteResult] = field(default_factory=list) + single: bool = True # True when no split happened + notes: List[str] = field(default_factory=list) + + +def _has_content(clause_text: str) -> bool: + """A clause carries content when it yields any router cue or at + least one non-stopword token (routing will score it regardless; this + is the cheap pre-filter that prevents conjunction-shredding of + single concepts like "blur and transparency").""" + from .router import extract_cues # local import avoids a cycle at import time + + cues = extract_cues(clause_text) + if cues: + return True + from .vectorize import tokenize + + return len(tokenize(clause_text)) >= _MIN_CONTENT_TOKENS + + +def split_clauses(text: str) -> List[Clause]: + """Deterministic clause segmentation with content guards. + + Contrast markers (but/except/...) split too, but the right-hand + clause is flagged; if it is a keep-phrase it is marked ``keep`` and + routed like any clause (the router will find the tool; the pipeline + turns keep-clauses into no-op/restore notes instead of changes). + """ + raw = text.strip() + if not raw: + return [] + lowered = raw.lower() + + # First split on contrast markers (they subsume coordination for + # scoping purposes), then on plain coordination within each side. + spans: List[Tuple[str, bool]] = [] + last = 0 + for match in _CONTRAST_SPLIT_RE.finditer(lowered): + spans.append((lowered[last:match.start()], False)) + last = match.end() + # the contrast clause runs until the next contrast marker or end + nxt = _CONTRAST_SPLIT_RE.search(lowered, last) + end = nxt.start() if nxt else len(lowered) + spans.append((lowered[last:end], True)) + last = end + spans.append((lowered[last:], False)) + + clauses: List[Clause] = [] + for chunk, is_contrast in spans: + pieces = _SPLIT_RE.split(chunk) if not is_contrast else [chunk] + for piece in pieces: + piece = piece.strip() + if not piece: + continue + if not _has_content(piece): + continue + clauses.append(Clause( + text=piece, + contrast=is_contrast, + keep=bool(_CONTRAST_KEEP_RE.search(piece)), + position=len(clauses), + )) + # A single trailing modifier clause ("... and a bit smaller") folds + # back into the previous clause — it modifies, not adds. + if len(clauses) >= 2 and _MODIFIER_RE.match(clauses[-1].text) and not clauses[-1].contrast: + merged = f"{clauses[-2].text} {clauses[-1].text}" + clauses = clauses[:-2] + [Clause(merged, clauses[-2].contrast, clauses[-2].keep, clauses[-2].position)] + return clauses + + +def route_compound(text: str, state: RouterState = DEFAULT_STATE, k: int = 3) -> CompoundResult: + """Split, then route each clause. Single-intent input collapses to a + one-clause result with ``single=True`` (identical behavior to plain + ``router.route`` on the whole text — the split is a no-op).""" + clauses = split_clauses(text) + if not clauses: + return CompoundResult(single=True, notes=["nothing addressable in the request"]) + if len(clauses) == 1: + return CompoundResult( + clauses=clauses, + routes=[route(clauses[0].text, state=state, k=k)], + single=True, + ) + routes = [route(c.text, state=state, k=k) for c in clauses] + notes: List[str] = [] + kept = [c.text for c in clauses if c.keep] + if kept: + notes.append("keep-clauses are honored as do-not-touch, not changes: " + "; ".join(kept)) + return CompoundResult(clauses=clauses, routes=routes, single=False, notes=notes) + + +# --------------------------------------------------------------------------- +# Issue #120 Phase 4.2: tool-dependency ordering for compound requests. +# +# A small, explicitly declared DAG over tool names: an edge (A -> B) means +# A must be applied BEFORE B. The only order-sensitive shape the shipped +# registry actually has is master-toggle -> dependent-strength inside one +# subsystem (a strength of a mode you are switching off is dead weight and +# can flash a transient state; the mode decision comes first). The table +# is hand-written from the registry's own group structure and cited — not +# inferred at runtime. Tools not in the table keep their spoken order. +# +# Ordering algorithm: stable Kahn topological sort over the ops' tool +# names (indegree ties break by original spoken order, preserving the +# existing "later clause wins" rule), plus last-value deduplication when +# two clauses touch the same tool. +# --------------------------------------------------------------------------- + +_PRECEDES: Dict[str, Tuple[str, ...]] = { + # master toggle dependent strengths (same subsystem) + "setTransparencyEnabled": ("setTransparencyBase", "setTransparencyLayers"), + "setToastsTransparency": ("setToastsTransparencyBase",), + "setBlurEnabled": ("setBlurMask", "setVisualiserBlur"), +} + + +def order_ops(ops: List[Dict[str, Any]]) -> Tuple[List[Dict[str, Any]], List[str]]: + """Deduplicate (same tool twice -> the later clause wins) and order the + composed ops so declared precedences hold. Deterministic; no I/O. + + Returns (ordered_ops, notes). Ops whose tools are not in the + precedence table keep their original relative order. + """ + if not ops: + return [], [] + notes: List[str] = [] + + # Last-value deduplication (mirrors "later clauses win conflicts"). + seen: Dict[str, int] = {} + for idx, op in enumerate(ops): + seen[str(op.get("tool", ""))] = idx + deduped: List[Dict[str, Any]] = [] + dropped: List[str] = [] + for idx, op in enumerate(ops): + tool = str(op.get("tool", "")) + if seen.get(tool) != idx and tool in seen: + dropped.append(tool) + continue + deduped.append(op) + if dropped: + notes.append("duplicate tools collapsed to the last spoken value: " + + ", ".join(sorted(set(dropped)))) + + if not deduped: + return [], notes + + # Stable Kahn topological sort over the declared edges. + names = [str(op.get("tool", "")) for op in deduped] + position = {name: i for i, name in enumerate(names)} + indegree = {name: 0 for name in names} + dependents: Dict[str, List[str]] = {name: [] for name in names} + for before, afters in _PRECEDES.items(): + if before not in position: + continue + for after in afters: + if after in position and after != before: + indegree[after] += 1 + dependents[before].append(after) + + import heapq # local import: only needed when ops exist + + heap = [position[name] for name, deg in indegree.items() if deg == 0] + heapq.heapify(heap) + ordered_names: List[str] = [] + while heap: + pos = heapq.heappop(heap) + name = names[pos] + ordered_names.append(name) + for after in dependents.get(name, ()): # release dependents + indegree[after] -= 1 + if indegree[after] == 0: + heapq.heappush(heap, position[after]) + if len(ordered_names) != len(names): + # The declared table is acyclic by construction; a cycle here would + # be a bug, so refuse to reorder rather than guess. + notes.append("order: precedence cycle detected; keeping spoken order") + return deduped, notes + + by_name = {name: op for name, op in zip(names, deduped)} + ordered = [by_name[name] for name in ordered_names] + reordered = ordered_names != names + if reordered: + notes.append("order: mode toggles applied before their dependent " + "strengths (issue #120 phase 4.2 ordering)") + return ordered, notes diff --git a/plugins/caelestia-assistant/assistant/core/coref.py b/plugins/caelestia-assistant/assistant/core/coref.py new file mode 100644 index 0000000..b8f257c --- /dev/null +++ b/plugins/caelestia-assistant/assistant/core/coref.py @@ -0,0 +1,156 @@ +"""cortex.coref — cross-turn pronoun resolution for the pending-plan +composer (exponential-build-4 F). + +Hobbs 1978, "Resolving Pronoun References", Lingua 44: the naive +(impoverished) coreference algorithm. What the paper actually does: +walk the parse trees of preceding sentences in a fixed breadth-first +order, propose each NP as antecedent, apply the binding-theory +filters, take the first survivor. What this repo has: NO parser (a +stdlib-only repo does not ship parse trees), so this is the paper's +SEARCH DISCIPLINE faithfully applied to shallow candidates +— sentences walked most-recent-first, candidates scanned right-to-left +(the recency order the naive algorithm's tree walk produces), filters +applied in the paper's spirit: + + * the antecedent is not itself a pronoun; + * number agreement for "them" (a plural-looking head: the candidate + ends in a plural 's' or is a known compound) — a heuristic, stated; + * "it"/"this"/"that" prefer singular candidates (the mirror heuristic); + * proper nouns outrank common nouns at equal recency? NO — the + naive algorithm has no such preference, and inventing one would be + tuning past the citation. First survivor in walk order wins. + +Honest envelope (said twice on purpose): without parse trees this is +NOT Hobbs' algorithm — it is the recency-first, filter-gated search +over shallow candidates that fits a stdlib-only repo. It will +occasionally bind "it" to the wrong object ("open the terminal and +close it" resolves fine; "move the window and break it" — 'it' means +the window — also resolves fine; ambiguity between two same-turn +objects is where the shallowness shows). The composer re-validates +through the standard planner regardless, so a wrong binding is caught +by the planner's own validation, not trusted blindly. + +Pure functions; no state; the PlanCache wiring (cortex/plans.py) is +where this gets called BEFORE the composed plan re-validates. +""" +from __future__ import annotations + +import re +from typing import Any, Dict, List, Optional, Sequence + +__all__ = ["resolve_pronoun", "resolve_turn", "PRONOUNS"] + +PRONOUNS = {"it", "this", "that", "them", "they"} + +_PRONOUN_RE = re.compile(r"\b(it|this|that|them|they)\b", re.IGNORECASE) +_TOKEN_RE = re.compile(r"[A-Za-z][A-Za-z0-9_-]*") + +_STOP = { + "the", "a", "an", "and", "or", "to", "of", "in", "on", "for", "with", + "please", "make", "set", "open", "close", "then", "also", "again", + "now", "just", "turn", "put", "get", "my", "me", "i", "you", "your", + "is", "are", "be", "do", "does", "can", "could", "would", "should", + "want", "want", "need", "little", "bit", "more", "less", "smaller", + "bigger", "larger", "shorter", "longer", "thinner", "wider", +} + +_PLURAL_SUFFIXES = ("s", "es") + + +def _tokens(text: str) -> List[str]: + return _TOKEN_RE.findall(text) + + +def _is_pronoun(token: str) -> bool: + return token.lower() in PRONOUNS + + +def _is_content(token: str) -> bool: + low = token.lower() + return low not in _STOP and not _is_pronoun(low) + + +def _looks_plural(token: str) -> bool: + low = token.lower() + return any(low.endswith(s) for s in _PLURAL_SUFFIXES) and len(low) > 3 + + +def _agrees(pronoun: str, candidate: str) -> bool: + """The number-agreement heuristic, stated as a heuristic: 'them'/ + 'they' want plural-looking candidates; 'it'/'this'/'that' want + non-plural ones. Wrong on irregulars ("mice") — the docstring's + honesty applies.""" + pronoun = pronoun.lower() + if pronoun in ("them", "they"): + return _looks_plural(candidate) + return not _looks_plural(candidate) + + +def resolve_pronoun(pronoun: str, context_turns: Sequence[str], + pending_labels: Optional[Sequence[str]] = None + ) -> Dict[str, Any]: + """Resolve one pronoun against the conversation's prior context, + Hobbs-style: most recent sentence first, candidates right-to-left, + first filter-passing content word wins. + + ``pending_labels``: the pending plan's own human-readable labels + (tool names, raw targets) — the plan itself is the MOST recent + context (the just-composed ops are what "it" most plausibly refers + to), so they are walked BEFORE the older turns. + + Returns {"resolved": bool, "antecedent": str-or-None, "source": + "pending-plan"|"prior-turn", "note": str}. No mutation, no state. + """ + if not _PRONOUN_RE.fullmatch(pronoun.strip().lower() or "it"): + return {"resolved": False, "antecedent": None, "source": None, + "note": f"{pronoun!r} is not a resolvable pronoun here " + f"(resolved set: {sorted(PRONOUNS)})"} + for label in reversed(list(pending_labels or [])): + for token in reversed(_tokens(str(label))): + if _is_content(token) and _agrees(pronoun, token): + return {"resolved": True, "antecedent": token.lower(), + "source": "pending-plan", + "note": "first filter-passing candidate in " + "Hobbs walk order over the pending plan"} + for turn in reversed(list(context_turns or [])): + for token in reversed(_tokens(str(turn))): + if _is_content(token) and _agrees(pronoun, token): + return {"resolved": True, "antecedent": token.lower(), + "source": "prior-turn", + "note": "first filter-passing candidate in " + "Hobbs walk order over prior turns"} + return {"resolved": False, "antecedent": None, "source": None, + "note": "no candidate survived the filters — refusing to " + "guess (the naive algorithm's honest dead end)"} + + +def resolve_turn(text: str, context_turns: Sequence[str], + pending_labels: Optional[Sequence[str]] = None + ) -> Dict[str, Any]: + """Resolve every pronoun in one new turn against the context. + Returns the rewritten text (pronouns replaced by their antecedent, + deterministically, left to right) plus the per-pronoun reports. + Unresolved pronouns are LEFT AS-IS and reported — a silent guess + is exactly what this module refuses.""" + reports: List[Dict[str, Any]] = [] + seen: Dict[str, Dict[str, Any]] = {} + + def replace(match: re.Match) -> str: + pronoun = match.group(0) + if pronoun.lower() not in seen: + seen[pronoun.lower()] = resolve_pronoun( + pronoun, context_turns, pending_labels) + reports.append(seen[pronoun.lower()]) + verdict = seen[pronoun.lower()] + if verdict["resolved"]: + return str(verdict["antecedent"]) + return pronoun + + rewritten = _PRONOUN_RE.sub(replace, text) + return {"original": text, "rewritten": rewritten, + "resolved": [r for r in reports if r["resolved"]], + "unresolved": [r for r in reports if not r["resolved"]], + "note": "Hobbs 1978 search discipline over shallow " + "candidates (no parser in a stdlib repo) — the " + "composed plan still re-validates through the " + "standard planner"} diff --git a/plugins/caelestia-assistant/assistant/core/delegate.py b/plugins/caelestia-assistant/assistant/core/delegate.py new file mode 100644 index 0000000..88a497b --- /dev/null +++ b/plugins/caelestia-assistant/assistant/core/delegate.py @@ -0,0 +1,214 @@ +"""cortex.delegate — inline execution of DELEGATE verdicts. + +When the router hands a request to another layer (genius / diagnose / +search / brain / issue / agent), the conversation does not stop at a +"try: " hint: the target layer's own existing entry function +runs inline, read-only, and its answer renders in the same turn. This is +the routing fix's core: every verb's worth of request — verbless or not +— gets an answer, never a pointer somewhere else. + +Runners (each calls an EXISTING entry point; nothing here is a second +implementation of anything): + +- ``genius`` : ``genius.meta.route_and_do`` (the one the chat REPL + already used inline — generalized, not replaced). +- ``diagnose`` : ``diagnostics.engine.diagnose`` — signature matching of + the routed text, rendered by ``render_report``. +- ``search`` : ``retrieval.search.search`` — the offline BM25 index + (the same function ``issues`` uses for similar issues). +- ``brain`` : ``brain.cli.main(["brief"])`` — the brain's synthesized + answer to plan/focus-shaped requests (pending proposals, + forecasts, rhythm), composed from the ledger. +- ``issue`` : ``issues.cli.main(["draft", ...])`` — a PREVIEW draft + composed from the routed text; without ``--confirm`` it + writes nothing, ever (the module's own contract). +- ``agent`` : ``agent.cli.main(["--simulate", ...])`` — the projected + task graph, nothing executed. The agent's execute path + (with its stdin consent gate) is deliberately NOT + reachable from here: consent stays a manual step. + +Safety spine (unchanged, inherited — this module adds zero write paths): + +- every runner is read-only or preview-only (see per-runner notes); +- a runner failure degrades to the caller's hint path (``run_delegate`` + returns None) — the turn shows the "try:" fallback, never a crash; +- stdlib + existing assistant modules only; the behavioral safety tests + untouched; no subprocess, no network, no clock dependence beyond what + the called modules already do. +""" + +from __future__ import annotations + +import contextlib +import io +from typing import Any, Callable, Dict, List, Optional, Tuple + +__all__ = ["RUNNERS", "runner_names", "run_delegate"] + +# A runner: (routed text, brain state dict) -> (JSON-safe payload, lines). +# The payload is what --json / the QML bridge emit; the lines are the +# terminal rendering for the same turn. +DelegateRunner = Callable[[str, Dict[str, Any]], Tuple[Dict[str, Any], List[str]]] + + +# --------------------------------------------------------------------------- +# Formatters. +# --------------------------------------------------------------------------- + + +def _format_genius(payload: Dict[str, Any]) -> List[str]: + """Compact formatter for an inline genius answer (the chat card body + the REPL has always printed, factored out so both surfaces share it).""" + lines: List[str] = [] + domain = payload.get("domain") or payload.get("verdict") + confidence = payload.get("confidence") + lines.append(f" genius -> {domain}" + + (f" (confidence {confidence})" if confidence else "")) + result = payload.get("result") + if result is None: + if payload.get("error"): + lines.append(f" error: {payload['error']}") + elif payload.get("message"): + lines.append(f" {payload['message']}") + return lines + for key, value in list(result.items())[:14]: + if key == "note": + continue # rendered separately below + if isinstance(value, (int, float, str, bool)) or value is None: + lines.append(f" {key.replace('_', ' ')}: {value}") + elif isinstance(value, list) and value and isinstance(value[0], (int, float, str)): + lines.append(f" {key.replace('_', ' ')}: {value[:8]}") + note = result.get("note") if isinstance(result, dict) else None + if note: + lines.append(f" note: {note}") + return lines + + +def _format_search(payload: Dict[str, Any]) -> List[str]: + results = payload.get("results") or [] + if not results: + return [" no corpus document matched the local docs/issues index"] + lines = [" retrieval hits (offline BM25):"] + for i, hit in enumerate(results, start=1): + lines.append(f" [{i}] {hit.get('doc_id', '?')} — {hit.get('title', '')}" + f" (score {hit.get('score', 0)})") + if hit.get("source"): + lines.append(f" source: {hit['source']}") + if hit.get("snippet"): + snippet = str(hit["snippet"]).replace("\n", " ") + lines.append(f" {snippet[:160]}") + return lines + + +# --------------------------------------------------------------------------- +# Runners (one per DELEGATE category; each reuses an existing entry). +# --------------------------------------------------------------------------- + + +def _delegate_genius(text: str, state: Dict[str, Any]) -> Tuple[Dict[str, Any], List[str]]: + from assistant.capabilities.genius import meta as genius_meta + + payload = genius_meta.route_and_do(text, state.get("genius_learn")) + return payload, _format_genius(payload) + + +def _delegate_diagnose(text: str, state: Dict[str, Any]) -> Tuple[Dict[str, Any], List[str]]: + from assistant.capabilities.diagnostics.engine import diagnose as diagnose_text + from assistant.capabilities.diagnostics.engine import render_report + + payload = diagnose_text(text) + # render_report is the diagnose CLI's own renderer; reuse verbatim. + lines = [f" {line}" for line in render_report(payload).splitlines()] + return payload, lines + + +def _delegate_search(text: str, state: Dict[str, Any]) -> Tuple[Dict[str, Any], List[str]]: + from assistant.capabilities.retrieval import search as retrieval_search + + results = retrieval_search.search(text, k=5) + payload = {"query": text, "results": results} + return payload, _format_search(payload) + + +def _delegate_brain(text: str, state: Dict[str, Any]) -> Tuple[Dict[str, Any], List[str]]: + """The brain's answer to plan/focus-shaped requests: the daily brief + (pending proposals + forecast + rhythm), composed exactly the way + ``caelestia-assist brief`` composes it — same entry function, same + ledger, read-only.""" + from assistant.capabilities.brain import cli as brain_cli + + buffer = io.StringIO() + with contextlib.redirect_stdout(buffer): + code = brain_cli.main(["brief"]) + if code != 0: + raise RuntimeError(f"brain brief exited {code}") + body = buffer.getvalue() + payload = {"brief": body} + lines = [f" {line}" for line in body.splitlines() if line.strip()] + return payload, lines + + +def _delegate_issue(text: str, state: Dict[str, Any]) -> Tuple[Dict[str, Any], List[str]]: + """Compose an issue-draft PREVIEW from the routed text (title seed + + description). Without --confirm the issues layer writes nothing — + its own docstring contract, relied on here verbatim.""" + from assistant.capabilities.issues import cli as issues_cli + + title = " ".join(text.split())[:72] + buffer = io.StringIO() + with contextlib.redirect_stdout(buffer): + code = issues_cli.main(["draft", "--title", title], stdin_text=text) + if code != 0: + raise RuntimeError(f"issue draft exited {code}") + body = buffer.getvalue() + payload = {"draft": body} + lines = [f" {line}" for line in body.splitlines()] + return payload, lines + + +def _delegate_agent(text: str, state: Dict[str, Any]) -> Tuple[Dict[str, Any], List[str]]: + """Simulate the multi-step goal and render the projected task graph. + Calls ``agent.cli.main`` with ``--simulate`` — the agent's execute + path (and its consent gate) is never reached from the conversation: + turning a simulation into action stays a manual, explicit step.""" + from assistant.capabilities.agent import cli as agent_cli + + buffer = io.StringIO() + with contextlib.redirect_stdout(buffer): + code = agent_cli.main(["--simulate", *text.split()]) + if code != 0: + raise RuntimeError(f"agent simulate exited {code}") + body = buffer.getvalue() + payload = {"simulated": True, "output": body} + lines = [f" {line}" for line in body.splitlines() if line.strip()] + return payload, lines + + +RUNNERS: Dict[str, DelegateRunner] = { + "genius": _delegate_genius, + "diagnose": _delegate_diagnose, + "search": _delegate_search, + "brain": _delegate_brain, + "issue": _delegate_issue, + "agent": _delegate_agent, +} + + +def runner_names() -> List[str]: + """Delegate categories that can answer inline this turn.""" + return sorted(RUNNERS) + + +def run_delegate(name: str, text: str, + state: Optional[Dict[str, Any]] = None + ) -> Optional[Tuple[Dict[str, Any], List[str]]]: + """Run one delegate inline. Returns ``(payload, lines)`` on success, + or ``None`` when the category has no runner or the run failed — the + caller keeps its hint path in that case (the safety net stays).""" + runner = RUNNERS.get(name) + if runner is None: + return None + try: + return runner(text, state or {}) + except Exception: # honest degradation: the caller's hint path stands + return None diff --git a/plugins/caelestia-assistant/assistant/core/dispatch.py b/plugins/caelestia-assistant/assistant/core/dispatch.py new file mode 100644 index 0000000..d14f60b --- /dev/null +++ b/plugins/caelestia-assistant/assistant/core/dispatch.py @@ -0,0 +1,598 @@ +"""cortex.dispatch — the unified local-vs-cloud decision point. + +One dispatcher, two backends, one existing confidence gate deciding between +them. The decision to serve a request from the local ontology or hand it +off to the (opt-in, user-keyed) cloud sidebar lives HERE — in the cortex +layer's own machinery — never in the sidebar's QML. The sidebar asks the +bridge (op ``dispatch``); this module answers. + +THE HAND-OFF RULE (existing gates only — no second threshold system): + +- verdict ``ABSTAIN``, or ``QUESTION`` with no candidates at all (nothing + scored: the router's own min_score gate in effect) -> cloud, + reason ``router-abstain``; +- verdict ``DELEGATE`` to a surface WITHOUT an inline runner -> cloud, + reason ``delegate:``. A DELEGATE surface WITH an inline + runner (genius / diagnose / search / brain / issue / agent — the + routing fix's generalized inline execution, ``cortex/delegate.py``) + answers LOCALLY: the target layer runs read-only in the same turn + (the agent always in --simulate) and its answer becomes the sidebar + bubble. Only a FAILED inline run hands off, reason + ``delegate:-inline-failed``; +- verdict ``PLAN`` whose top-route score is NOT covered by the conformal + calibrator's verdict, when calibration data exists (>= 5 accepted + routes) -> cloud, reason ``below-conformal-threshold``. No calibration + data means no distribution-free claim either way — the request stays + local rather than being punted on a guess; +- everything else stays LOCAL: PLAN (validated ops), QUESTION with + candidates (the local layer owns the clarification, with its session + machinery), EXPLAIN / UNDO / LIST / INERT, and runnable DELEGATEs. + +GAP LOGGING (every hand-off, §5.2): the state's ``cortex_gaps`` bucket — +the same bounded-bucket discipline as ``cortex_review`` (dedup by shape, +newest-first, bounded) — records the query SHAPE (stemmed, stopword- +filtered, distinctive-token signature) and the intent category, NOT the +raw text: enough to cluster, count and describe the gap later ("N requests +like X fell through"), with no reason to retain user prose. Near-threshold +hand-offs also feed the existing ``cortex_review`` batch surface. + +GAP CLUSTERING (§5.3): ``cluster_gaps`` reuses genius' k-means (the same +deterministic implementation workspace.py uses) over the gap vectors, and +applies the SAME minimum-support (3) + cluster-purity (0.6) floor +workspace.py established — a handful of scattered gaps produces ZERO +candidates, by design and by test. + +SURFACING (§5.4): ``propose_gap_clusters`` turns a qualifying cluster into +a LEDGER PROPOSAL (kind ``ontology_gap``) — never an automatically-added +tool. The ledger's approve/reject is the whole interaction, exactly like +every other proposal in the system. + +TOOL-TEMPLATE STUBS (§5.5, exponential-build 1.1): a dense, UNADDRESSED +gap cluster can additionally be drafted into a reviewable stub file +(name, cue words, a TODO body) by ``select_stub_candidates`` + the CLI's +explicit ``--draft-stubs`` flag — a candidate scaffold for a future +local tool that is never registered in the router, never wired into +this dispatcher, never executed, and never clobbered once a human has +edited it. The functions here stay PURE (no I/O): the CLI owns writing +the files, exactly as it owns writing state. + +Read-only except the state buckets and the ledger proposals it is given; +this module executes nothing and writes no files itself. +""" + +from __future__ import annotations + +import math +import re +from datetime import datetime, timezone +from typing import Any, Dict, List, Optional + +from .learn import REVIEW_KEY, CortexLearner, log_review_candidate +from .delegate import run_delegate, runner_names +from .pipeline import process +from .session import SessionState +from .vectorize import tokenize + +__all__ = ["GAPS_KEY", "MAX_GAPS", "query_shape", "log_gap", "dispatch", + "cluster_gaps", "propose_gap_cluster", "propose_gap_clusters", + "tool_template_slug", "tool_template_stub_text", + "select_stub_candidates"] + +# The gap bucket: same discipline as cortex_review (bounded, newest-first, +# deduped by shape). Gaps are lower-frequency events than review candidates, +# so the bound is larger, but it stays a bound. +GAPS_KEY = "cortex_gaps" +MAX_GAPS = 120 + +# How many distinctive tokens make up a gap's shape (enough to describe and +# cluster; deliberately not the full request). +SHAPE_TOKENS = 8 + + +# --------------------------------------------------------------------------- +# Query shape (the privacy-preserving signature of a request). +# --------------------------------------------------------------------------- + +def query_shape(text: str) -> List[str]: + """Distinctive-token signature: stemmed, stopword-filtered tokens, + longest-first (content words beat function words), capped at + SHAPE_TOKENS, deduplicated. Two phrasings of the same request shape + collide far more often than two unrelated ones.""" + tokens = tokenize(text) + unique = sorted(set(tokens), key=lambda w: (-len(w), w)) + return unique[:SHAPE_TOKENS] + + +def log_gap(state: Dict[str, Any], text: str, category: str, + now: str) -> Dict[str, Any]: + """Record one hand-off in the bounded gap bucket (mutates ``state``; + the caller owns persistence). Same-shape requests are counted, not + re-stored; the newest categorization wins. Returns the updated entry.""" + shape = query_shape(text) or ["(unparsed)"] + bucket = [g for g in (state.get(GAPS_KEY) or []) + if isinstance(g, dict)] + entry: Optional[Dict[str, Any]] = None + for existing in bucket: + if existing.get("shape") == shape: + entry = existing + bucket.remove(existing) + break + if entry is not None: + entry["n"] = int(entry.get("n", 1)) + 1 + entry["category"] = category + entry["last_at"] = now + else: + entry = {"shape": shape, "category": category, "n": 1, + "first_at": now, "last_at": now} + bucket.insert(0, entry) + state[GAPS_KEY] = bucket[:MAX_GAPS] + return entry + + +# --------------------------------------------------------------------------- +# The hand-off decision. +# --------------------------------------------------------------------------- + +def _hand_off_reason(result, state: Dict[str, Any]) -> Optional[str]: + """Why this request must go to the cloud tier, or None if it stays + local. Uses the router's own verdicts and the conformal calibrator's + own verdict only — no new thresholds are introduced anywhere.""" + if result.verdict == "ABSTAIN": + return "router-abstain" + if result.verdict == "OUT_OF_ONTOLOGY": + # F6: the request names nothing in the local ontology — the + # cloud tier is exactly the escape hatch for this, and the gap + # bucket records the shape for later clustering. + return "out-of-ontology" + if result.verdict == "DELEGATE": + return f"delegate:{result.delegate or 'unknown'}" + if result.verdict == "QUESTION" and not result.candidates: + # every clause came back "nothing matched" — the router's min_score + # gate in effect; the local ontology has nothing to say. + return "router-abstain" + if result.verdict == "PLAN" and result.plan and not result.plan.get("apply_blocked"): + from .conformal import ConformalCalibrator + data = state.get("conformal") + if isinstance(data, dict) and data.get("scores"): + cal = ConformalCalibrator() + cal.from_dict(data) + verdict = cal.verdict(result.confidence) + if verdict.get("covered") is False: + return "below-conformal-threshold" + return None + + +def render_answer(result) -> List[str]: + """The local tier's chat answer (sidebar-flavoured rendering; the CLI + keeps its own chat card in cli.py — same result object, different + surface, no shared presentation code to drift).""" + lines: List[str] = [] + if result.session_note: + lines.append(result.session_note) + if result.verdict == "PLAN" and result.plan is not None: + entries = result.plan.get("entries", []) + if result.plan.get("apply_blocked"): + lines.append("I parsed this, but the plan has validation errors:") + for err in result.plan.get("errors", [])[:5]: + lines.append(f" {err.get('tool', '?')}: {err.get('error', '?')}") + else: + applicable = [e for e in entries if e.get("new") is not None] + if len(applicable) == 1: + e = applicable[0] + lines.append(f"Applied: {e.get('path', '?')} " + f"{e.get('old', '(unset)')} -> {e.get('new')}.") + lines.append("Undo is available — just say 'undo the last change'.") + else: + lines.append("I found several changes that match your request — " + "approve them above to apply.") + for e in applicable[:8]: + lines.append(f" {e.get('path', '?')}: {e.get('old', '(unset)')} " + f"-> {e.get('new')}") + elif result.verdict == "QUESTION": + for q in result.questions[:4]: + lines.append(q) + # an apply-blocked plan's validation errors ARE the answer (the + # issue's own rule: out-of-range simply isn't applied) + if result.plan and result.plan.get("errors"): + for err in result.plan.get("errors", [])[:5]: + lines.append(f" {err.get('tool', '?')}: {err.get('error', '?')}") + elif result.verdict == "EXPLAIN" and result.explain_answer: + lines.append(str(result.explain_answer.get("answer", ""))) + cites = result.explain_answer.get("cites") or [] + if cites: + lines.append(f"grounded in: {'; '.join(str(c) for c in cites[:3])}") + elif result.verdict in ("UNDO", "LIST") and result.history_plan: + hp = result.history_plan + if hp.get("action"): + lines.append(f"Undoing: {hp.get('reason', '')}") + else: + lines.append(f"{hp.get('reason', '')}") + for entry in hp.get("entries", [])[:5]: + label = entry.get("label") or f"#{entry.get('id')}" + lines.append(f" [{entry.get('id')}] {label} at {entry.get('at')}") + elif result.verdict == "INERT": + lines.extend(result.suggestions) + if getattr(result, "calibration_note", None): + lines.append(str(result.calibration_note)) + if result.evidence: + shown = "; ".join(dict.fromkeys(result.evidence))[:220] + lines.append(f"(why: {shown})") + for note in result.notes[:3]: + if note: + lines.append(f"note: {note}") + if not lines: + lines.append("(no local answer for this verdict — say more and I'll try again)") + return lines + + +def apply_calls(result) -> Optional[Dict[str, Any]]: + """SettingsTools-shaped apply payload for a local PLAN: the validated + entries as [{name, value}] plus a label. The sidebar applies them + through the EXISTING SettingsTools gate (single entry applies + immediately and is undoable; multiple entries show the preview card); + this function only extracts data, it writes nothing. None when the plan + is blocked or the verdict is not PLAN.""" + if result.verdict != "PLAN" or result.plan is None: + return None + if result.plan.get("apply_blocked"): + return None + entries = result.plan.get("entries", []) + calls = [{"name": e.get("tool"), "value": e.get("new")} + for e in entries if e.get("new") is not None] + if not calls: + return None + label = (result.candidates[0].get("clause") if result.candidates + else "cortex dispatch") + return {"calls": calls, "label": label} + + +def undo_action(result) -> Optional[Dict[str, Any]]: + """The gated undo the sidebar should run for a local UNDO verdict + (SettingsTools.undo / undoById — the existing surfaces). None when + there is nothing to undo.""" + if result.verdict != "UNDO" or not result.history_plan: + return None + hp = result.history_plan + if not hp.get("action"): + return None + if hp.get("entry_id") is not None: + return {"id": hp.get("entry_id")} + return {"steps": hp.get("steps") or 1} + + +def dispatch(text: str, *, state: Optional[Dict[str, Any]] = None, + session: Optional[SessionState] = None, + file_path: Optional[str] = None, + now: Optional[str] = None) -> Dict[str, Any]: + """Decide one request: local answer or cloud hand-off. + + ``state`` is the caller's brain-state dict; on a hand-off the gap + bucket (and, for near-threshold verdicts, the review bucket) are + updated in it — the caller persists. The returned outcome dict: + + ``{"action": "local"|"cloud", "reason": str|None, "confidence": float, + "session": {...}, "result": {...}, + "answer": [lines] # local only + "apply": {calls, label} # local PLAN only (gated by the caller) + "undo": {steps}|{id} # local UNDO only (gated by the caller)}`` + """ + now = now or datetime.now(timezone.utc).isoformat(timespec="seconds") + state = state if isinstance(state, dict) else {} + session = session if session is not None else SessionState() + learner = CortexLearner(state.get("cortex_learn")) \ + if state.get("cortex_learn") else None + result = process(text, session=session, learner=learner, file_path=file_path) + + # Calibration surfacing (phase 2.4): the honest accuracy line for + # THIS confidence bucket, when the sample supports it — the same + # sentence the CLI chat card shows. + if learner is not None: + try: + # raw route probability is the bucket key (learn_hook), not + # the calibrated confidence — a different quantity + raw_p = ((result.learn_hook or {}).get("p", result.confidence) + if result.learn_hook is not None else result.confidence) + result.calibration_note = learner.calibration_note(raw_p) + except Exception: + result.calibration_note = None + + reason = _hand_off_reason(result, state) + + # Inline-runnable delegates answer LOCALLY (the routing fix's decision + # point, kept in the cortex layer — never the sidebar's QML): genius / + # diagnose / search / brain / issue / agent requests run their target + # layer inline, read-only, and the sidebar shows that answer instead of + # handing the request to the cloud tier. A failed inline run falls back + # to the cloud tier with a distinct, countable reason. + inline: Optional[tuple] = None + if (reason and result.verdict == "DELEGATE" + and result.delegate in runner_names()): + inline = run_delegate(result.delegate, text, state) + if inline is not None: + reason = None + else: + reason = f"delegate:{result.delegate}-inline-failed" + + # Taught concepts (F15): when the cortex would hand this off, a + # user-taught concept may own the phrase. Recall only PROPOSES — the + # apply payload goes through the same gated surface as every plan, + # and a built-in preset match asks instead of replacing. + if reason: + from assistant.core import concepts as _concepts + from assistant.capabilities.settings.curations import PRESETS as _PRESETS + try: + hit = _concepts.recall(state, text, presets=_PRESETS) + except Exception: + hit = None + if hit and hit.get("verdict") == "RECALL": + lines = [ + f"taught concept '{hit['name']}' (similarity {hit['score']}): " + f"propose {len(hit['calls'])} call(s)", + ] + for c in hit["calls"]: + lines.append(f" {c['name']} = {c['value']!r}") + for p in hit["posterior"]: + if p["p"] is not None: + lines.append(f" ({p['tool']} accepted {p['p']} over " + f"{p['n']} past uses)") + return { + "action": "local", "reason": None, + "confidence": hit["score"], + "session": session.to_dict(), + "result": result.to_dict(), + "answer": lines, + "apply": {"calls": hit["calls"], + "label": f"taught concept: {hit['name']}"}, + "concept": hit, + } + if hit and hit.get("verdict") in ("CONFLICT_ASK", "AMBIGUOUS"): + if hit["verdict"] == "CONFLICT_ASK": + lines = [hit["question"], + f" concept: {hit['concept']['name']} " + f"({hit['concept']['score']})", + f" preset: {hit['preset']['name']} " + f"({hit['preset']['score']})"] + else: + lines = ["several taught concepts match:"] + for cand in hit["candidates"]: + lines.append(f" {cand['name']} ({cand['score']})") + return { + "action": "local", "reason": None, + "confidence": 0.5, "session": session.to_dict(), + "result": result.to_dict(), "answer": lines, + "concept": hit, + } + + outcome: Dict[str, Any] = { + "action": "cloud" if reason else "local", + "reason": reason, + "confidence": result.confidence, + "session": session.to_dict(), + "result": result.to_dict(), + } + if reason: + log_gap(state, text, reason, now) + if result.verdict in ("ABSTAIN", "QUESTION", "OUT_OF_ONTOLOGY"): + # the same near-threshold phrases the CLI chat loop parks for + # batch review — sidebar traffic feeds the same surface. + # OUT_OF_ONTOLOGY phrases are exactly the review material for + # "should a local capability cover this?" (F6). + state[REVIEW_KEY] = log_review_candidate( + list(state.get(REVIEW_KEY, [])), text, result.verdict, + result.candidates or [], at=now) + return outcome + + if inline is not None: + payload, inline_lines = inline + answer = [line.strip() for line in inline_lines if line.strip()] + outcome["answer"] = answer or render_answer(result) + outcome["delegate_payload"] = payload + else: + outcome["answer"] = render_answer(result) + apply_info = apply_calls(result) + if apply_info is not None: + outcome["apply"] = apply_info + undo = undo_action(result) + if undo is not None: + outcome["undo"] = undo + return outcome + + +# --------------------------------------------------------------------------- +# Gap clustering (the workspace.py discipline, applied to gap vectors). +# --------------------------------------------------------------------------- + +def cluster_gaps(state: Dict[str, Any], *, k: Optional[int] = None, + min_support: int = 3, purity: float = 0.6, + seed: int = 42) -> Dict[str, Any]: + """Cluster the logged gap shapes; only consistent clusters surface. + + Vectors are token-count bags over the gaps' own vocabulary; clustering + reuses genius' deterministic k-means (k-means++ seeding under a fixed + seed — the same implementation workspace.py uses, lazily imported to + keep the layer boundary explicit). A cluster is a candidate only when + its total request count (sum of the member shapes' ``n``) reaches + ``min_support`` AND its modal shape covers at least ``purity`` of + those requests — the exact floor workspace.py established for session + profiles, because a handful of scattered gaps is noise, not a need.""" + gaps = [g for g in (state.get(GAPS_KEY) or []) if isinstance(g, dict) + and g.get("shape")] + n = len(gaps) + if n == 0: + return {"n_gaps": 0, "k": 0, "candidates": [], "rejected_clusters": 0} + + vocab: Dict[str, int] = {} + for gap in gaps: + for token in gap["shape"]: + vocab.setdefault(token, len(vocab)) + points = [[0.0] * len(vocab) for _ in gaps] + for i, gap in enumerate(gaps): + for token in gap["shape"]: + points[i][vocab[token]] += 1.0 + + if k is None: + k = min(8, max(2, round(math.sqrt(n / 2)))) + k = max(1, min(k, n)) + if n >= 2 and k >= 2: + from assistant.capabilities.genius.data import kmeans + labels = kmeans(points, k, seed=seed)["labels"] + else: + labels = [0] * n # one cluster; the support/purity floor still applies + + candidates: List[Dict[str, Any]] = [] + rejected = 0 + for cid in sorted(set(labels)): + members = [g for g, label in zip(gaps, labels) if label == cid] + support = sum(int(m.get("n", 1)) for m in members) + if support < min_support: + rejected += 1 + continue + modal = max(members, key=lambda m: (int(m.get("n", 1)), + " ".join(m.get("shape", [])))) + p = int(modal.get("n", 1)) / support + if p < purity: + rejected += 1 + continue + candidates.append({ + "tokens": modal["shape"], + "category": modal.get("category"), + "support": support, + "purity": round(p, 3), + "shapes": len(members), + "label": " ".join(modal["shape"][:5]), + }) + candidates.sort(key=lambda c: (-c["support"], c["label"])) + return {"n_gaps": n, "k": k, "candidates": candidates, + "rejected_clusters": rejected} + + +def _propose_candidate(candidate: Dict[str, Any], ledger) -> Optional[int]: + """File ONE qualifying cluster as a ledger proposal (kind + ``ontology_gap``), or None when a pending duplicate exists. The + single proposal step both surfacing functions share.""" + target = f"gap-cluster:{candidate['label']}" + if target in {p.get("target") for p in ledger.pending()}: + return None + why = (f"{candidate['support']} request(s) shaped like " + f"\"{candidate['label']}\" fell through to the cloud tier " + f"(category {candidate['category']}, purity " + f"{candidate['purity']}, {candidate['shapes']} distinct " + f"phrasing(s)) — want a local tool for this?") + return ledger.propose("ontology_gap", target, + {"cluster": candidate}, why, + candidate["purity"]) + + +def propose_gap_cluster(state: Dict[str, Any], ledger, label: str, + **kwargs: Any) -> Dict[str, Any]: + """Surface ONE gap cluster (by its modal-shape label) as a ledger + proposal — the single-cluster entry point the unified inbox + (cortex/inbox.py) dispatches ``approve`` through. Same floors, same + proposal shape, same never-auto-absorb rule as + ``propose_gap_clusters``; a cluster already pending is skipped, not + stacked. Returns ``{"proposed": pid|None, "candidate": dict|None}`` — + ``candidate`` None means no qualifying cluster carries that label + right now.""" + summary = cluster_gaps(state, **kwargs) + for candidate in summary["candidates"]: + if candidate["label"] == label: + pid = _propose_candidate(candidate, ledger) + return {"proposed": pid, "candidate": candidate} + return {"proposed": None, "candidate": None} + + +def propose_gap_clusters(state: Dict[str, Any], ledger, + **kwargs: Any) -> Dict[str, Any]: + """Turn qualifying gap clusters into LEDGER PROPOSALS (kind + ``ontology_gap``). Never auto-absorbs anything: the ledger's + approve/reject flow is the whole interaction, same as every other + proposal. One live proposal per cluster target (a pending duplicate is + skipped, not stacked).""" + summary = cluster_gaps(state, **kwargs) + pids: List[int] = [] + for candidate in summary["candidates"]: + pid = _propose_candidate(candidate, ledger) + if pid is not None: + pids.append(pid) + return {"proposals": pids, "summary": summary} + + +# --------------------------------------------------------------------------- +# Tool-template stub drafting (exponential-build 1.1). Pure helpers only: +# the CLI's explicit --draft-stubs flag turns the selected candidates into +# reviewable .md files; nothing here registers, wires, or executes anything. +# --------------------------------------------------------------------------- + +def tool_template_slug(label: str) -> str: + """A filesystem-safe slug for a cluster label: lowercase, non- + alphanumerics collapsed to underscores, trimmed. Deterministic (a + pure function of the label, which is itself the cluster's modal + shape), so the same cluster always drafts the same stub filename.""" + stem = re.sub(r"[^a-z0-9]+", "_", label.lower()).strip("_") + return stem or "unnamed_cluster" + + +def tool_template_stub_text(candidate: Dict[str, Any], + drafted_at: str) -> str: + """The full markdown text of one tool-template stub (pure). The stub + names itself DRAFT, cites the evidence that produced it, lists the + cue words, and leaves a TODO body — it becomes a tool only if a + human writes the named classical algorithm behind it (author/year + citation required, the same discipline every existing module + follows). Until then the requests keep falling through honestly.""" + cues = ", ".join(candidate["tokens"][:SHAPE_TOKENS]) + name = tool_template_slug(candidate["label"]) + return "\n".join([ + f"# tool-template: {name}", + "", + f"status: DRAFT — auto-drafted from a cortex gap cluster on " + f"{drafted_at};", + " NOT registered in the router, NOT wired into the dispatcher,", + " NOT executable by anything. It becomes a tool only if a human", + " writes the named classical algorithm behind it (author, year", + " citation required, same discipline as every existing module).", + "", + "## Evidence (why this cluster qualifies)", + "", + f"- {candidate['support']} request(s) shaped like " + f"\"{candidate['label']}\" fell through to the cloud tier", + f"- category: {candidate['category']}; purity " + f"{candidate['purity']}; {candidate['shapes']} distinct phrasing(s)", + "", + "## Proposed surface", + "", + f"- name: {name}", + f"- cue words: {cues}", + "", + "## Body", + "", + "TODO: implement this tool as a named classical algorithm with a", + "citation in its docstring (author, year). Until that module", + "exists, these requests keep falling through honestly instead of", + "being guessed at.", + "", + ]) + + +def select_stub_candidates(state: Dict[str, Any], ledger=None, + **kwargs: Any) -> Dict[str, Any]: + """Qualifying clusters that are still UNADDRESSED — the ledger holds + NO item at all (pending, approved, or rejected) for the cluster's + ``gap-cluster:

+ +Caelestia logo + +# caelestia-kde + +[![Arch Linux](https://img.shields.io/badge/Arch_Linux-1793d1?logo=arch-linux&logoColor=white&style=for-the-badge&labelColor=101418)](https://archlinux.org) +[![Fedora](https://img.shields.io/badge/Fedora-51A2DA?logo=fedora&logoColor=white&style=for-the-badge&labelColor=101418)](https://fedoraproject.org) +[![Ubuntu](https://img.shields.io/badge/Ubuntu-E95420?logo=ubuntu&logoColor=white&style=for-the-badge&labelColor=101418)](https://ubuntu.com) +[![KDE Plasma](https://img.shields.io/badge/Plasma_6-1D99F3?logo=kde&logoColor=white&style=for-the-badge&labelColor=101418)](https://kde.org/plasma-desktop) +[![License: GPL-3.0-or-later](https://img.shields.io/badge/License-GPL--3.0--or--later-9bd0cc?style=for-the-badge&labelColor=101418)](LICENSE) + +
+ + +https://github.com/user-attachments/assets/38b24e7f-fdd9-43db-872b-8c0ac23a44fd + +> [!NOTE] +> This repo is the KDE Plasma port of [`caelestia-dots/shell`](https://github.com/caelestia-dots/shell). +> Upstream runs on Hyprland; the port runs the same shell on KWin and Plasma. For the original +> Hyprland dotfiles, see [`caelestia-dots/caelestia`](https://github.com/caelestia-dots/caelestia). + +## Installation + +**Requirements:** Arch-based, Fedora, or Debian/Ubuntu - KDE Plasma 6 on Wayland, Qt 6.9+ + +```bash +curl -fsSL https://raw.githubusercontent.com/ladybug-me/caelestia-kde/main/install.sh | sh +``` + +### Updating + +- **Installer TUI:** run the installer and choose *Update* +- **GUI:** Nexus -> Updates -> select branch -> Install Updates +- **CLI:** `bash update.sh` and choose `main` (stable) or `dev` (bleeding edge) + +Shell settings are preserved across updates. + +### Uninstalling + +Choose *Uninstall* from the installer TUI, or run: + +```bash +bash ./uninstall.sh +``` + +## Keybinds + +| Shortcut | Action | +| --- | --- | +| `Super` | App launcher | +| `Super + /` | Keybind cheatsheet | +| `Super + Enter` | Terminal | +| `Super + Tab` | Overview | +| `Super + 1-5` | Switch workspace | +| `Super + B` | Notification sidebar | +| `Super + V` | Clipboard history | +| `Super + Shift + S` | Screenshot | +| `Super + Shift + A` | Google Lens | +| `Super + Shift + D` | Text recognition | +| `Super + Ctrl + S` | Screen recorder | +| `Super + Shift + C` | Color picker | +| `Super + Shift + V` | Emoji selector | + +## Configuring + +Open Nexus (`Super`, then `>Settings`). + +- Appearance: wallpaper, colors, fonts, and the wallpaper slideshow +- Panels: every bar element, dashboard, launcher, sidebar and overview +- Desktop: window rules, the context menu, Krohnkite +- Shortcuts: rebind any built-in shortcut, or add a command shortcut +- Plugins: browse the store, or install a plugin you built yourself + +Set the wallpaper from Appearance. The stock KDE wallpaper manager does not drive +the color scheme, so using it leaves the shell on stale colors. + +Settings are written to `~/.config/caelestia/shell.json`. + +## Troubleshooting + +| Problem | Fix | +| --- | --- | +| Widgets not appearing | Log out and back in, or run `caelestia shell -d` | +| Colors not applying | Run `caelestia scheme set -n dynamic`, or `caelestia wallpaper -f `. See [TROUBLESHOOTING.md](docs/TROUBLESHOOTING.md#34-colors-not-applying) | +| Install failed mid-way | Re-run `bash ./scripts/setup.sh` | +| Full reset needed | See [TROUBLESHOOTING.md](docs/TROUBLESHOOTING.md) | + +For detailed logs, enable Debug Mode in Nexus -> About -> Advanced, then run +`caelestia shell -l`. Bug reports and questions go to +[GitHub Issues](https://github.com/ladybug-me/caelestia-kde/issues). + +## Repository layout + +``` +installer/ TUI installer and the per-distro package lists + tui/ C++ TUI source and its CMakeLists + data/ menu.json, theme.json, tui.version + distro/ per-distro package installation (arch, debian, fedora) +scripts/ install/update pipeline: the numbered steps and their shared lib/ +src/ files copied onto the system, plus the vendored submodules +shell/ the QML shell and its C++ QML plugin +docs/ guides, plus design notes under docs/architecture/ +tests/ bash tests for the step-script helpers +tools/ repo maintenance scripts, never shipped +assets/ the logo and screenshots used by the docs +.github/ workflows, issue and PR templates, CI checks +``` + + + + + + Star History Chart + + + +## Credits + +- [caelestia-dots/shell](https://github.com/caelestia-dots/shell) and the [Caelestia dotfiles](https://github.com/caelestia-dots/caelestia) by [@soramanew](https://github.com/soramanew) - the design language, shell and dotfiles this port is built on +- [ladybug-me](https://github.com/ladybug-me) - KDE port lead +- [0xSolanaceae](https://github.com/0xSolanaceae) - Head maintainer +- [Bali10050](https://github.com/Bali10050/Darkly) - Darkly Qt +- [wrymt](https://github.com/wrymt/darkly-gtk) - Darkly GTK +- [Haidir](https://bitbucket.org/dirn-typo/yet-another-monochrome-icon-set) - icon set + +## License + +GPL-3.0-or-later - see [LICENSE](LICENSE). diff --git a/plugins/caelestia-assistant/assistant/data/corpus/DOC-TS-01.md b/plugins/caelestia-assistant/assistant/data/corpus/DOC-TS-01.md new file mode 100755 index 0000000..6e57a3c --- /dev/null +++ b/plugins/caelestia-assistant/assistant/data/corpus/DOC-TS-01.md @@ -0,0 +1,68 @@ +id: DOC-TS-01 +title: 1. Build & Compilation Issues +source: docs/TROUBLESHOOTING.md — section 1 (Build & Compilation Issues) +tags: build, compile, cmake, g++, gcc, make, installer tui, c++20, qt6, qml module metadata, qmldir, ccache, sigsegv, exit 139, exit 127 +synonyms: install fails cmake missing, g++ command not found, build errors + +### 1.1 C++ Installer Compilation Fails + +The installer compiles the `caelestia-install` TUI binary during `setup.sh`. The CMake project requires **C++20** (`CMAKE_CXX_STANDARD 20`). + +| Symptom | Likely Cause | Fix | +|---|---|---| +| `g++: command not found` | Build tools not installed | Arch: `sudo pacman -S base-devel` — Fedora: `sudo dnf install gcc-c++` | +| `cmake: command not found` | CMake missing | Auto-installer handles this if `BASE_DISTRO` is detected; otherwise install manually | +| `[FATAL] Failed to build the Caelestia installer` | General CMake/make error | Read build log: `cat /tmp/caelestia_build.log` | +| Compiler error about modern C++ features | GCC older than 10 | Ensure GCC 10+ is installed: `g++ --version` | +| Exit 139 (SIGSEGV) at runtime | C++ bug in the TUI | Check stderr log at `/tmp/caelestia_installer_err.log` | +| Exit 127 at runtime | Missing shared library | Run `ldd` on the binary to find missing `.so` files | + +### 1.2 Shell / Plugin Compilation Fails + +The shell build (`08-build-shell.sh`) requires **Qt 6.9+** and several system libraries. The CMake project in `shell/CMakeLists.txt` uses `qt_standard_project_setup(REQUIRES 6.9)`. + +#### Qt / QML Dependencies + +| Missing Dependency | CMake Error Clue | Arch Package | Fedora Package | +|---|---|---|---| +| Qt6::Qml / Qt6::Quick | `find_package` failed | `qt6-declarative` | `qt6-qtdeclarative-devel` | +| Qt6::ShaderTools | Shader tool config | `qt6-shadertools` | `qt6-qtshadertools-devel` | +| Qt6::WaylandClient | Wayland client plugin | `qt6-wayland` | `qt6-qtwayland-devel` | +| KF6WindowSystem | KWindowSystem not found | `kwindowsystem` | `kf6-kwindowsystem-devel` | +| KGlobalAccel | kglobalaccel not found | `kglobalaccel` | `kf6-kglobalaccel-devel` | +| KPipeWire | pipewire integration | `kpipewire` | `kf6-kpipewire-devel` | + +#### Library Dependencies (pkg_check_modules) + +| Library | Arch Package | Fedora Package | +|---|---|---| +| `libqalculate` | `libqalculate` | `libqalculate-devel` | +| `libpipewire-0.3` | `pipewire` | `pipewire-devel` | +| `aubio` | `aubio` | `aubio-devel` | +| `libcava` | Prebuilt release asset / `libcava` | Prebuilt release asset / `celestelove/libcava` (COPR) | +| `libpulse` | `libpulse` | `pulseaudio-libs-devel` | +| `libpam` | `pam` | `pam-devel` | +| `lm_sensors` (Fedora) | not needed | `lm_sensors-devel` | + +**Fedora note:** The custom `cmake/sensorslib.cmake` module loads `lm_sensors`. If it's missing, the build may silently skip sensor support. + +### 1.3 "Missing QML Module Metadata" After Build + +```text +[ERR] Missing QML module metadata: $HOME/.local/lib/qt6/qml/Caelestia/Config/qmldir +``` + +This means the CMake install step didn't copy required `qmldir` or `.so` files properly. + +**Causes & fixes:** +- **Install prefix mismatch:** The build uses `-DCMAKE_INSTALL_PREFIX=$HOME/.local`. If Qt6 looks for QML modules elsewhere, the module won't load. +- **Stale build artifacts:** Run `rm -rf shell/build shell/plugin/build` before re-running +- **Partial installation:** If CMake install was interrupted, files may be missing. Re-run `08-build-shell.sh` + +### 1.4 ccache Not Speeding Up Rebuilds + +The project enables ccache in both `installer/CMakeLists.txt` and `shell/CMakeLists.txt`. If rebuilds are still slow: + +- Check ccache stats: `ccache -s` +- The cache directory (`~/.cache/ccache`) may be too small — increase it: `ccache -M 5G` +- Debug builds (`-DCMAKE_BUILD_TYPE=Debug`) are much slower; the installer uses `Release` diff --git a/plugins/caelestia-assistant/assistant/data/corpus/DOC-TS-02.md b/plugins/caelestia-assistant/assistant/data/corpus/DOC-TS-02.md new file mode 100755 index 0000000..9648dd0 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/data/corpus/DOC-TS-02.md @@ -0,0 +1,54 @@ +id: DOC-TS-02 +title: 2. Dependency & Package Issues +source: docs/TROUBLESHOOTING.md — section 2 (Dependency & Package Issues) +tags: packages, pacman, yay, aur, fedora, copr, dnf, rpm fusion, matugen, dos2unix, crlf, failed_packages.txt, quickshell-git, libcava + +### 2.1 Arch Linux / yay Failures + +| Issue | Cause | +|---|---| +| `yay` fails to install | Network issues, AUR down, or PKGBUILD changes. The script (`installer/distro/arch/packages.sh`) retries individually and falls back to `makepkg -si`. | +| `pacman` errors during install | The script uses `-Sy --noconfirm` (refresh DB) then `-S --needed --noconfirm`. If the system update step (`00a-system-update.sh`) was skipped, partial upgrades can cause conflicts. | + +**AUR packages used by Caelestia:** + +| AUR Package | Failure Symptoms | +|---|---| +| `quickshell-git` | Shell won't start; autostart fails with exit 127 | +| `matugen` | `caelestia wallpaper` and `caelestia scheme` fail with "matugen is not installed". It is in Arch's `extra`, so it is not an AUR package; it is listed here because nothing themes without it. | +| `darkly` | KDE theme won't apply | + +### 2.2 Fedora / COPR Failures + +| Package | COPR / Source | Known Issues | +|---|---|---| +| `quickshell-git` | `errornointernet/quickshell` | COPR may be out of date | +| `gpu-screen-recorder` | `brycensranch/gpu-screen-recorder-git` | May need `ffmpeg` from RPM Fusion | +| `app2unit` | `celestelove/app2unit` | Falls back to `make install` | +| `libcava` | Prebuilt release asset / `celestelove/libcava` | Downloads prebuilt SDK from release; falls back to COPR | +| `starship` | `atim/starship` | Stable, rarely fails | +| `wl-clip-persist` | `leloubil/wl-clip-persist` | Needed for clipboard persistence | + +**RPM Fusion requirement:** `ffmpeg` with H264 support requires RPM Fusion. The script auto-enables it, but this may fail behind a proxy or on air-gapped systems. + +**matugen on Fedora:** there is no package for it, and it is what generates the palette. The installer reports it when it is missing; `cargo install matugen` fixes it. + +### 2.3 CRLF / dos2unix Failure + +If CRLF line endings are detected and `dos2unix` auto-install fails, the installer **aborts** with: + +```text +[FATAL] Line ending normalization step failed. Aborting installer. +``` + +**Fix:** Install `dos2unix` manually, or answer `n` to the CRLF prompt to skip normalization. + +### 2.4 Failed Packages Log + +Failed packages are logged to: + +```text +$XDG_CACHE_HOME/caelestia-kde/failed_packages.txt +``` + +The installer does **not** abort on package failure — it logs and continues. Check this file after installation if something doesn't work. diff --git a/plugins/caelestia-assistant/assistant/data/corpus/DOC-TS-03.md b/plugins/caelestia-assistant/assistant/data/corpus/DOC-TS-03.md new file mode 100755 index 0000000..210e1a6 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/data/corpus/DOC-TS-03.md @@ -0,0 +1,161 @@ +id: DOC-TS-03 +title: 3. Runtime Issues — Shell +source: docs/TROUBLESHOOTING.md — section 3 (Runtime Issues — Shell) +tags: runtime, shell, quickshell, caelestia-shell.service, systemd user unit, journalctl, environment variables, environment.d, plasma-workspace env, caelestia.sh, kscreenlocker_greet, qml2_import_path, window thumbnails, screencast, screen share, vesktop, camera freeze, colors not applying, scheme, screen recording, screenshots, screen flashes, kde-material-you-colors, workspace tracker, workspace pills, kde update, tonal spot +synonyms: shell does not start, blank screen at login, vesktop freezes when i screenshare, colors revert after reboot, workspace pills not loading, scheme resets + +### 3.1 Shell Doesn't Start After Login + +The shell starts from the systemd user unit `caelestia-shell.service`, which `caelestia install` enables once. The environment the shell needs is set by `~/.local/bin/caelestia-autostart.sh` for a source install, and by `/usr/bin/caelestia-autostart` for a packaged one; the unit runs whichever belongs to that install. + +| Symptom | Likely Cause | +|---|---| +| Blank screen at login | Shell binary launched but crashed immediately. Check `journalctl --user -xe`. | +| Plasma desktop visible, no shell | The unit didn't start. `systemctl --user status caelestia-shell.service`, and `systemctl --user is-enabled caelestia-shell.service` for whether it is on at all. | +| Shell appears briefly then disappears | Quickshell crashed. Run manually from a terminal. | +| `quickshell: command not found` | Quickshell not in PATH at login. The wrapper the unit runs resolves the binary path. | + +**Manual start for debugging:** +```bash +export QML2_IMPORT_PATH="$HOME/.local/lib/qt6/qml" +export CAELESTIA_LIB_DIR="$HOME/.local/lib/caelestia" +quickshell -d -n -p ~/.config/quickshell/caelestia/shell.qml +``` + +### 3.2 Environment Variables Not Set On Login + +They live in two locations: +1. `~/.config/environment.d/caelestia.conf`: read by systemd for every session process and for the user manager the shell's unit runs under. +2. `~/.config/plasma-workspace/env/caelestia.sh`: sourced by KDE Plasma on session startup for KWin, `kscreenlocker_greet`, and graphical applications. + +```bash +QML2_IMPORT_PATH=$HOME/.local/lib/qt6/qml:$HOME/.config/quickshell/caelestia +CAELESTIA_LIB_DIR=$HOME/.local/lib/caelestia +CAELESTIA_BIN_DIR=$HOME/.local/bin +CAELESTIA_SHELL_CONFIG=$HOME/.config/quickshell/caelestia/shell.qml +``` + +**If they are missing:** re-run `scripts/08-build-shell.sh`, then log out and back +in. `systemctl --user show-environment` lists what the systemd user manager has. + +### 3.3 Window Thumbnails / Screencast Not Working + +KWin only grants `zkde_screencast_unstable_v1` to clients whose `.desktop` file lists the protocol. + +**Fix:** +```bash +# Verify the desktop file exists +cat ~/.local/share/applications/quickshell.desktop +# Rebuild KService cache +kbuildsycoca6 --noincremental +# Reload KWin +qdbus6 org.kde.KWin /KWin reconfigure +``` + +If the desktop file is missing, re-run `scripts/10-autostart.sh`. + +### 3.3.1 Screen Sharing / Camera Freezes Vesktop (or other apps) + +Some NVIDIA + KWin setups cannot handle two separate clients using KWin's +privileged `zkde_screencast_unstable_v1` protocol at the same time. Caelestia +uses this protocol for live taskbar/overview/alt-tab window thumbnails, which +can conflict with another app's screencast (e.g. Vesktop screen share with +audio, or camera) using the same KWin subsystem via xdg-desktop-portal-kde, +causing that app to freeze or crash. + +**Fix:** Disable live window previews: +- Nexus -> Taskbar -> "Live window previews" toggle, or +- Set `"bar": { "livePreviews": false }` in `shell.json` and reload + +This falls back to static app icons for thumbnails instead of live video and +avoids Caelestia's use of the protocol entirely. + +### 3.4 Colors Not Applying + +| Symptom | Fix | +|---|---| +| Colors do not change with the wallpaper | `caelestia wallpaper -f ` generates and applies the palette. If Plasma stays on the old one, check that `plasma-apply-colorscheme --list-schemes` names `Matugen`. | +| Two Material You entries in System Settings | Expected: `Matugen` and `Matugen Alt`. `plasma-apply-colorscheme` does nothing when handed the scheme already in effect, so the palette is applied under whichever of the two is not current. | +| A leftover accent color wins over the palette | Plasma rewrites the focus, link and selection colors from `kdeglobals`' accent, so the palette is applied with that key removed. If it is set again - System Settings, or a theme tool of your own - the colors it drives will follow it. | +| Colors come back as the built-in default (Mocha) | The CLI derives dynamic colors from the wallpaper it was last told about. When it has none it writes nothing, and the shell keeps its own default palette. The shell re-derives from the wallpaper it is showing at every start. | +| Konsole keeps its own colors | The command writes `~/.local/share/konsole/Matugen.colorscheme` and points the profiles that exist at it. Konsole's built-in default profile is not a file, so a fresh account has nothing to point: create a profile once and the next change themes it. | +| The desktop flickers between two palettes | A `kde-material-you-colors` unit from an older install is still applying a scheme of its own. See 3.7. | + +There is no service to restart. A palette is generated and applied by the command the shell calls, so +the way to redo it by hand is: + +```bash +caelestia scheme set -n dynamic # re-derive from the wallpaper on screen +caelestia wallpaper -f ~/Pictures/Wallpapers/one.png +``` + +### 3.5 Screen Recording Issues + +| Symptom | Cause | +|---|---| +| Recording appears stuck | `gpu-screen-recorder` not installed or not in PATH | +| Portal dialog doesn't appear | The `caelestia-record` wrapper restarts `plasma-xdg-desktop-portal-kde` and `xdg-desktop-portal` before launching `gpu-screen-recorder`. If the portal still doesn't appear, restart them manually: `systemctl --user restart plasma-xdg-desktop-portal-kde xdg-desktop-portal`. | +| Recording doesn't start | `caelestia-record` wraps `gpu-screen-recorder` directly with KDE-specific monitor detection (via `kscreen-doctor`) and portal management. No Python/OpenCV dependency. | + +The recorder now verifies both `pidof gpu-screen-recorder` AND that `recording.mp4` exists, preventing false positives from stale PID matches. + +### 3.6 Screenshot Issues + +The screenshot tool uses `spectacle` (KDE's native screenshot utility) via the `caelestia-screenshot` wrapper. + +- If `spectacle` isn't installed, screenshots silently fail +- Full-screen screenshots save to `~/Pictures/Screenshots/` by default + +### 3.7 Screen Flashes and the Shell Stutters Every Second + +The screen flashes, colors look briefly wrong and the shell hangs for about a +second, repeating on a rhythm of roughly one second. + +That was `kde-material-you-colors` getting stuck. It decided on every loop that +the palette had changed, applied an identical scheme again and spawned +`plasma-apply-colorscheme` each time, and every apply rewrites `kdeglobals` and +repaints every window. Nothing here runs it any more: it is not installed, the +installer removes its unit, and the palette is applied once per change rather than +once per poll. + +If it is still happening, a unit from an older install is behind it: + +```bash +systemctl --user status kde-material-you-colors # active means it is still applying +systemctl --user disable --now kde-material-you-colors +pgrep -af plasma-apply-colorscheme # a new pid every second means something still loops +``` + +`bash scripts/10-autostart.sh` stops that unit and deletes it, if you would rather +not do it by hand. It also removes the `MaterialYou*.colors` files KMY left in +System Settings. + +Applying once when the wallpaper or theme changes is expected and does not +trigger any of this. + +--- + +### 3.8 Workspace Tracker Effect Stops Loading After a KDE Update + +The workspace pills show the focused screen's desktop on every screen, swiping +does not track the gesture, and the shell reports that the workspace tracker +effect is not running. + +`kwin_workspace_tracker` is a compiled KWin effect, and KWin makes no promise +that a binary effect keeps working across releases: it is linked against +libkwin's internals and has to be relinked when KDE updates them. KWin then +refuses the stale binary, so per-output desktops and the swipe offset stop +arriving. A routine `pacman -Syu` is enough to cause it; nothing in Caelestia is +corrupted. + +Rebuild it by re-running the installer or `update.sh`, then log out and back in - +KWin only loads effects at startup: + +```bash +bash update.sh # rebuilds and reinstalls the effect +qdbus6 org.kde.KWin /Caelestia/Workspaces org.freedesktop.DBus.Introspectable.Introspect +``` + +The last command prints the effect's interface once it is loaded again, and +fails while it is not. `bash shell/scripts/check-workspace-tracker.sh` answers the +same question with an exit status (3 means enabled but not loaded). diff --git a/plugins/caelestia-assistant/assistant/data/corpus/DOC-TS-04.md b/plugins/caelestia-assistant/assistant/data/corpus/DOC-TS-04.md new file mode 100755 index 0000000..04bfa45 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/data/corpus/DOC-TS-04.md @@ -0,0 +1,29 @@ +id: DOC-TS-04 +title: 4. Runtime Issues — Lock Screen +source: docs/TROUBLESHOOTING.md — section 4 (Runtime Issues — Lock Screen) +tags: lock screen, lockscreen, greeter, breeze, kscreenlockerrc, plasmashellrc, shell package, kreadconfig6, kwriteconfig6 +synonyms: breeze lock screen shows instead of caelestia + +### 4.1 Lock Screen Greeter Diagnostic + +The Caelestia lock screen runs as a native KDE Plasma 6 shell package (`caelestia.desktop`), loaded directly by KDE's `kscreenlocker_greet`. + +**Diagnostic commands:** +```bash +# Verify Caelestia shell package is configured +kreadconfig6 --file plasmashellrc --group "Shell" --key "ShellPackage" +# Expected output: caelestia.desktop + +# Verify greeter files exist in local plasma shells directory +ls -la ~/.local/share/plasma/shells/caelestia.desktop/contents/lockscreen/LockScreenUi.qml + +# Test and run the greeter in a window (non-blocking test) +/usr/lib/kscreenlocker_greet --testing +``` + +| Symptom | Cause | Solution | +|---|---|---| +| Stock Breeze lock screen appears | `ShellPackage` reset after KDE update or theme switch. | Caelestia autostart (`caelestia-autostart.sh`) automatically self-heals this at next login if `caelestia.desktop` is present. To restore immediately in session: `kwriteconfig6 --file plasmashellrc --group "Shell" --key "ShellPackage" "caelestia.desktop" && kwriteconfig6 --file kscreenlockerrc --group "Greeter" --key "Theme" --delete`. | +| Lock screen fails or crashes | Greeter files missing or corrupted in `~/.local/share/plasma/shells/`. | Re-deploy via `BUNDLE_DIR=. ./scripts/02-packages.sh` or `cp -r src/kde/shells/caelestia.desktop ~/.local/share/plasma/shells/`. | +| Lock screen shows wallpaper error | Legacy `PlasmaApplicationWallpaper` left in `kscreenlockerrc`. | Reset WallpaperPlugin: `kwriteconfig6 --file kscreenlockerrc --group Greeter --key WallpaperPlugin "org.kde.image"`. | +| Profile picture missing | `~/.face` does not exist and no system user avatar set. | Place your avatar image at `~/.face` or configure an avatar in KDE System Settings → Users. | diff --git a/plugins/caelestia-assistant/assistant/data/corpus/DOC-TS-05.md b/plugins/caelestia-assistant/assistant/data/corpus/DOC-TS-05.md new file mode 100755 index 0000000..941673d --- /dev/null +++ b/plugins/caelestia-assistant/assistant/data/corpus/DOC-TS-05.md @@ -0,0 +1,65 @@ +id: DOC-TS-05 +title: 5. Configuration Issues +source: docs/TROUBLESHOOTING.md — section 5 (Configuration Issues) +tags: configuration, darkly, theme, window decoration, osd, virtual desktops, kglobalaccel, shortcut conflicts, stolen shortcuts, terminal, garbled output +synonyms: shortcuts stopped working, osd keeps showing, wrong number of desktops + +### 5.1 Darkly Theme Not Applied + +| Symptom | Cause | +|---|---| +| Plasma style unchanged | `APPLY_DARKLY` was set to `false` in the configuration menu | +| Window decorations missing | The installer tries `org.kde.darkly` library, falls back silently to `org.kde.breeze` | +| `lookandfeeltool --apply "Darkly"` failed | The `darkly` package may not be installed (AUR/COPR/prebuilt packages) | + +**Manual apply:** +```bash +kwriteconfig6 --file kwinrc --group "org.kde.kdecoration2" --key "library" "org.kde.darkly" +kwriteconfig6 --file kwinrc --group "org.kde.kdecoration2" --key "theme" "@darkly" +qdbus6 org.kde.KWin /KWin reconfigure +``` + +### 5.2 KDE OSD Still Showing + +The tweak script disables OSD in `plasmarc`, `kdeglobals`, `plasmanotifyrc`, `powerdevilrc`, and `kmixrc`. If OSD still appears: + +```bash +systemctl --user restart plasma-plasmashell +``` + +Some KDE versions (6.1 vs 6.2) may use slightly different config keys. + +### 5.3 Wrong Number of Virtual Desktops + +The installer configures exactly **5 desktops**. If you had a different count before: +- Re-run `scripts/09-system-tweaks.sh` to re-apply +- The uninstaller resets desktop count to `1` + +### 5.4 Keyboard Shortcut Conflicts + +Caelestia's `GlobalShortcut` system uses `kglobalacceld`. When it registers a shortcut that conflicts with another app, it "steals" the binding and records it in: + +```text +~/.config/caelestia/stolen-shortcuts.json +``` + +**If shortcuts are missing or wrong:** +```bash +rm -f ~/.config/caelestia/stolen-shortcuts.json +systemctl --user status plasma-kglobalaccel.service +``` + +If `keyd` is active and manages Meta+1..5, the tweak script skips KWin bindings for those combos to avoid conflicts. + +### 5.5 Terminal Sequence Bleeding (Garbled Output) + +If ANSI escape sequences leak from the `caelestia` CLI into your terminal: + +```bash +cat $XDG_CACHE_HOME/caelestia-kde/failed_patches.txt +``` + +If `Caelestia CLI Theme Sequence Patch` appears in the failed list, re-run: +```bash +bash scripts/09-system-tweaks.sh +``` diff --git a/plugins/caelestia-assistant/assistant/data/corpus/DOC-TS-06.md b/plugins/caelestia-assistant/assistant/data/corpus/DOC-TS-06.md new file mode 100755 index 0000000..7710bba --- /dev/null +++ b/plugins/caelestia-assistant/assistant/data/corpus/DOC-TS-06.md @@ -0,0 +1,48 @@ +id: DOC-TS-06 +title: 6. Network & Proxy Issues +source: docs/TROUBLESHOOTING.md — section 6 (Network & Proxy Issues) +tags: network, proxy, mirror ranking, pacman mirrors, git submodules, src/dots empty, aur behind proxy +synonyms: git clone fails, submodule empty + +### 6.1 Pacman Mirror Ranking Fails + +On CachyOS, the installer uses the native `cachyos-rate-mirrors` command, which ranks both Arch and CachyOS repositories. Other Arch-based systems use `reflector` as a fallback. Fedora refreshes its configured DNF metadata and Debian-based systems refresh their configured APT indexes; neither needs mirror-list rewriting during installation. Failure modes: +- **Offline:** Mirror ranking fails and the existing mirror lists are kept +- **cachyos-rate-mirrors unavailable:** CachyOS mirror ranking is skipped and the existing mirror lists are kept +- **reflector not installed:** On non-Cachy Arch systems, it is auto-installed via `pacman -Sy reflector`; if that fails, ranking is skipped +- **DNF or APT refresh fails:** Fedora/Debian package installation continues and reports the package-manager error later if the configured sources remain unavailable + +### 6.2 Git / Submodule Failures + +The submodule `src/dots` is critical. If it cannot be fetched: + +```text +[ERR] src/dots is still empty, and the installer cannot deploy without it. +``` + +Step 02a checks the submodule has content and fetches it again by other means before reporting this: a normal update, then a sync of the recorded URL followed by another update, then a forced update, and finally a plain clone of the URL `.gitmodules` records. So this message means all four were attempted and every one failed, which is usually a network that cannot reach GitHub or a checkout that cannot be written to. + +This is a **hard failure** - the installer cannot proceed past config deployment. Fetch it by hand and re-run the step: + +```bash +git -C ~/caelestia-kde submodule update --init --recursive src/dots +bash ~/caelestia-kde/scripts/02a-submodules.sh +``` + +The shared folder mounted at `/mnt/hgfs/` is read-only, so an install run from there cannot fetch anything: clone the repository to a writable directory first. + +**Behind a proxy?** +```bash +git config --global http.proxy http://proxy:port +git config --global https.proxy http://proxy:port +export GIT_SSL_NO_VERIFY=1 +``` + +### 6.3 AUR Builds Fail Behind Proxy + +`makepkg -si` downloads sources from various URLs. Set proxy environment variables before running `setup.sh`: +```bash +export http_proxy=http://proxy:port +export https_proxy=http://proxy:port +export ALL_PROXY=http://proxy:port +``` diff --git a/plugins/caelestia-assistant/assistant/data/corpus/DOC-TS-07.md b/plugins/caelestia-assistant/assistant/data/corpus/DOC-TS-07.md new file mode 100755 index 0000000..8c45f00 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/data/corpus/DOC-TS-07.md @@ -0,0 +1,137 @@ +id: DOC-TS-07 +title: 7. KDE & Plasma Specific Issues +source: docs/TROUBLESHOOTING.md — section 7 (KDE & Plasma Specific Issues) +tags: kde, plasma, plasmalogin, plasmalogin.service, sddm.service, kwin, qs-kwin-bridge, xdg-desktop-portal, portals, ydotoold, krohnkite, kwin script injection, login screen, sddm, window rules, installer window rules + +### 7.1 Legacy qs-kwin-bridge Service + +The old `qs-kwin-bridge` Python daemon is now **disabled** in favor of native C++ plugins. If you see it running: +```bash +systemctl --user disable --now qs-kwin-bridge.service +``` + +### 7.2 xdg-desktop-portal-kde + +The recording patch restarts `plasma-xdg-desktop-portal-kde` before each recording. This may fail if: +- The portal service is masked +- The user's systemd session is in a bad state + +### 7.3 ydotoold (On-Screen Keyboard) + +`ydotoold` needs access to `/dev/uinput`. The installer: +1. Creates `/etc/udev/rules.d/80-uinput.rules` +2. Adds user to `input` group +3. Creates sudoers NOPASSWD rule + +**If ydotoold doesn't work:** +- Re-login (group changes take effect on next login) +- Verify: `groups $USER` should include `input` +- Verify: `ls -la /run/user/$(id -u)/.ydotool_socket` + +### 7.4 Krohnkite Tiling Disabled on Uninstall + +The uninstaller disables `krohnkiteEnabled` in `kwinrc`. If you don't have the Krohnkite KWin script installed, this setting is simply ignored. + +### 7.5 KWin Script Injection Fails + +The plugin injects a temporary KWin script for window tracking. If KWin scripting is disabled: +```bash +qdbus6 org.kde.KWin /Scripting org.kde.kwin.Scripting.loadScript +``` + +### 7.6 The Login Screen (Plasma Login and SDDM) + +Plasma 6.6 and newer boot into Plasma Login, KDE's fork of SDDM. The two are +configured in different places, and the installer picks a branch at install time: + +| | Plasma Login | SDDM | +|---|---|---| +| How to tell | `plasmalogin.service` is active/enabled | `sddm.service` is active/enabled | +| Theme | none: its greeter is a Plasma shell, and it loads no SDDM theme | `/usr/share/sddm/themes/caelestia` | +| Wallpaper | `[Greeter][Wallpaper][org.kde.image][General] Image` in `/etc/plasmalogin.conf`, pointing at a copy under the `plasmalogin` user's `wallpapers/` | `assets/background` inside the theme | +| Colors | the `plasmalogin` user's own `~/.config/kdeglobals` plus the scheme files in its `~/.local/share/color-schemes/` | `theme.conf` inside the theme | +| Sync helper | `/usr/local/bin/caelestia-greeter-sync` | `/usr/share/sddm/themes/caelestia/scripts/sync.sh` | + +The greeter runs as its own system user, which cannot read your home directory, so +anything it shows has to be copied to it. That is what the sync helper does, and it +runs after every wallpaper or color change through the posthook in +`~/.config/caelestia/cli.json`. An install that switches display managers replaces +its hook rather than stacking a second one. + +**The login screen shows Breeze colors or no background:** + +```bash +# Which display manager is actually installed +command -v plasmalogin sddm + +# Plasma Login: what the greeter is told to show +kreadconfig6 --file /etc/plasmalogin.conf --group Greeter --group Wallpaper \ + --group org.kde.image --group General --key Image + +# SDDM: which theme each config source selects, last one read wins +grep -rn "Current=" /etc/sddm.conf /etc/sddm.conf.d/ /usr/lib/sddm/sddm.conf.d/ 2>/dev/null +ls /usr/share/sddm/themes/caelestia/theme.conf + +# Re-copy the wallpaper and the scheme, then log out +sudo /usr/local/bin/caelestia-greeter-sync # Plasma Login +sudo /usr/share/sddm/themes/caelestia/scripts/sync.sh # SDDM +``` + +Both greeters read their configuration when they start, so a change is visible at +the next logout rather than immediately. + +### 7.7 Installer Window Rules + +The installer writes three groups into `~/.config/kwinrulesrc`. `caelestia-opacity` +gives normal windows and dialogs an inactive opacity of 95 percent, +`caelestia-dialogs` forces centered placement on dialogs, and `caelestia-pip` keeps +windows whose title matches `Picture(-| )in(-| )[Pp]icture` above others. Opacity is +a per-activation-state key, so a window is dimmed only while it is not focused, and +the dialog rule is the one that can disagree with a placement policy chosen in +System Settings. + +A group only takes effect if the index names it. `[General] rules=` is the list KWin +loads its rule groups from, and a group that is present in the file but missing from +that list is never loaded, and is removed the next time KWin saves the file. The +installer writes the list as the union of the entries that were already in it, every +group the file holds and its own three names, with `count` set to the number of +entries, so the user's own rules are named alongside ours and keep their order. + +To read a value back: + +```bash +kreadconfig6 --file kwinrulesrc --group caelestia-opacity --key opacityinactive +kreadconfig6 --file kwinrulesrc --group caelestia-dialogs --key placement +kreadconfig6 --file kwinrulesrc --group caelestia-pip --key above +kreadconfig6 --file kwinrulesrc --group General --key rules +``` + +To remove the rules, delete the three `[caelestia-...]` sections out of the file, or +delete the key that switches each group on. A group that is deleted has to leave the +index with it, or the list keeps a name whose group is gone and `count` no longer +matches it. `uninstall.sh` removes the keys, strips the three names out of the list, +rewrites `count`, and deletes both index keys once no name is left. KWin does not +watch kwinrulesrc, so the reload is not optional: + +```bash +kwriteconfig6 --file kwinrulesrc --group caelestia-opacity \ + --key opacityinactiverule --delete +kwriteconfig6 --file kwinrulesrc --group caelestia-dialogs \ + --key placementrule --delete +kwriteconfig6 --file kwinrulesrc --group caelestia-pip --key aboverule --delete +qdbus6 org.kde.KWin /KWin reconfigure +``` + +Those commands delete each group's `*rule` key, which is the action. The match keys +are left behind, and a group that matches but carries no action is empty as far as +KWin is concerned: it discards such a rule once a window it matches has been +withdrawn, so the residue is harmless. + +A window that is already open keeps what a rule forced on it. Opacity and keep-above +are set on the window itself, so an open window stays dimmed or pinned after the rules +are gone, until it is closed and reopened or another rule forces the value back. Only +windows created after the removal start clean. + +The installer always applies the rules; `APPLY_WINDOW_RULES=false` is an override +for running the step by hand (`APPLY_WINDOW_RULES=false bash ./scripts/setup.sh`). +`WINDOW_OPACITY` changes the percentage the opacity rule writes. diff --git a/plugins/caelestia-assistant/assistant/data/corpus/DOC-TS-08.md b/plugins/caelestia-assistant/assistant/data/corpus/DOC-TS-08.md new file mode 100755 index 0000000..9b322d9 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/data/corpus/DOC-TS-08.md @@ -0,0 +1,95 @@ +id: DOC-TS-08 +title: 8. Post-Install Issues +source: docs/TROUBLESHOOTING.md — section 8 (Post-Install Issues) +tags: post-install, shell not visible, installer exited prematurely, confirm_arg, stale lock files, update.sh fails, partial upgrade, packages replaced in memory, prebuilt shell, checksum +synonyms: disk space, ccache size, free disk space used by the shell, stale lock + +### 8.1 Shell Not Visible After Install + +The shell only runs at **next login**. After the summary screen, the installer asks: *"Would you like to log out now? (y/N)"* + +If you chose not to log out: +1. Log out manually (`Super+Ctrl+Q` or KDE menu → Leave → Log Out) +2. Log back in +3. If the shell still doesn't appear, run: `caelestia shell -d` + +### 8.2 Installer Exited Prematurely (Marker Check) + +The outer `setup.sh` wrapper checks if `[installer] done (success)` appears in stderr: + +| Condition | Warning | +|---|---| +| Exit 0 but elapsed < 3 seconds without marker | **"INSTALLER EXITED PREMATURELY"** | +| Exit 0 but elapsed > 3 seconds without marker | **"INSTALLER EXITED UNEXPECTEDLY"** | + +### 8.3 CONFIRM_ARG Behavior + +The configuration menu sets `CONFIRM_ARG` as `true`/`false`. The installer converts it per-script context: +- Some scripts use `-n "$CONFIRM_ARG"` (non-empty = auto-confirm) +- The installer writes an `[installer] done (success)` marker line to its stderr log, and `setup.sh` greps that log for it to decide whether the install succeeded (see `scripts/setup.sh`). + +### 8.4 Stale Lock Files + +If the script is killed with **SIGKILL** (not SIGTERM), lock files may persist: + +| Lock File | Script | +|---|---| +| `${XDG_RUNTIME_DIR:-/tmp}/caelestia-setup.lock` | `setup.sh` | +| `${XDG_RUNTIME_DIR:-/tmp}/caelestia-update.lock` | `update.sh` | + +**Always use Ctrl+C (SIGINT)** which is handled gracefully. Remove stale locks: +```bash +rm -f "${XDG_RUNTIME_DIR:-/tmp}/caelestia-setup.lock" +rm -f "${XDG_RUNTIME_DIR:-/tmp}/caelestia-update.lock" +``` + +### 8.5 Update.sh Fails + +| Symptom | Cause | +|---|---| +| `git pull` fails | Uncommitted changes exist. The updater auto-stashes, but conflicts may remain. | +| Submodule update fails | Network issue or GitHub down. Retry later. | +| CMake configure fails | New dependencies added since last install. Check error output. | + +### 8.6 Installer Stops After a System Upgrade + +`00a-system-update.sh` upgrades the system first, and later steps compile and load the Caelestia +KWin plugin into the session that is **already running**. If the upgrade replaced `kwin`, +`plasma-workspace`, `libplasma`, `qt6-base` or `qt6-declarative`, the live session still holds the +old libraries in memory while the on-disk headers are new, so the installer stops and names the +packages that moved: + +``` +[ERR] The upgrade replaced packages the running session still has loaded in memory: +[ERR] had kwin 6.4.0-1 +[ERR] now kwin 6.4.1-1 +``` + +This is the partial-upgrade state Arch documents as "do not keep using the session", not a broken +install. Log out and back in (or reboot) and run the installer again: the upgrade is already +applied, so nothing is downloaded twice and the remaining steps run against a session that matches +the files on disk. + +Choosing **ignore** at the prompt continues anyway. The plugin build may then fail with Wayland or +ABI errors that look unrelated to the upgrade. + +### 8.7 Prebuilt Shell Download Is Rejected + +`08-build-shell.sh` extracts the release tarball straight over `$HOME`, so it first checks the +download against the `.sha256` published beside it: + +| Message | Meaning | +|---|---| +| `Prebuilt shell artifacts match the published checksum.` | Normal: the prebuilt archive is installed. | +| `No published checksum for ... - extracting without verification.` | The release predates checksums. The install continues. | +| `No prebuilt shell artifacts published for (Qt ) - falling back to a local build.` | The release carries no archive for this Qt feature version. The step builds locally instead. | +| `Checksum mismatch for ...` | The download was truncated or tampered with. The step falls back to building the shell locally. | + +A mismatch is not fatal: the installer builds from source instead, which takes longer but cannot +unpack a damaged tree into `~/.local/lib/qt6/qml`. + +The archive is also only used for the revision it was built from: `main` sitting on its remote +tip, or a checkout that is exactly the released tag (an update pinned to a version). A branch, a +stale `main`, or a checkout carrying commits of its own builds locally, because the archive would +replace that tree with the release's. `main` that has moved on since its last release cannot be +told apart from that release, so it is installed as the release its `version.env` names. diff --git a/plugins/caelestia-assistant/assistant/data/corpus/DOC-TS-09.md b/plugins/caelestia-assistant/assistant/data/corpus/DOC-TS-09.md new file mode 100755 index 0000000..c3023d2 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/data/corpus/DOC-TS-09.md @@ -0,0 +1,46 @@ +id: DOC-TS-09 +title: 9. Uninstall Issues +source: docs/TROUBLESHOOTING.md — section 9 (Uninstall Issues) +tags: uninstall, backups, konsave, restore, rc files, dependencies, input group, failed patches + +### 9.1 No Backups Available + +Backups are stored in `$BUNDLE_DIR/backups/YYYYMMDD_HHMMSS/`. If you moved or deleted the repository, backups are gone. + +### 9.2 konsave Restore Fails + +If the `.knsv` archive is corrupted or konsave can't be installed: +- Falls back to manual restore of individual config files +- If `python3 -m venv` fails (missing `python3-venv`), theme data can't be restored + +**Expected warning when restoring a Caelestia backup:** +> *"The selected backup contains Caelestia configurations. Restoring this backup will NOT revert to a clean KDE desktop!"* + +### 9.3 Shell RC Files Not Cleaned + +The uninstaller uses state files (`shellrc/bashrc.state`, etc.) to determine whether to restore or remove shell config files. If these are missing (older installer version), a fallback `sed` cleanup removes `QML2_IMPORT_PATH` and `CAELESTIA_LIB_DIR` lines. + +### 9.4 Package Removal Leaves Dependencies + +Package removal is optional. It uses `yay -Rns` / `dnf remove` which does NOT remove: +- Dependencies pulled in automatically (unless `-s` handles it) +- Packages installed outside the defined lists +- `base-devel` or build tools that existed before install + +### 9.5 Input Group Membership Persists + +The uninstaller runs `sudo gpasswd -d $USER input`. This only works if the user was added to the group during installation, and takes effect on next login. + +### 9.6 Failed Patches Tracking + +Failed patches are logged to: +```text +$XDG_CACHE_HOME/caelestia-kde/failed_patches.txt +``` + +Possible entries: +- `Caelestia CLI Hyprctl Mock Patch` +- `Caelestia CLI Record/Dolphin Patch` +- `Caelestia CLI Theme Sequence Patch` + +These are **cosmetic** — the shell works without them, but certain features (screenshot, recording, terminal colors) may be degraded. diff --git a/plugins/caelestia-assistant/assistant/data/corpus/DOC-TS-10.md b/plugins/caelestia-assistant/assistant/data/corpus/DOC-TS-10.md new file mode 100755 index 0000000..5d5559f --- /dev/null +++ b/plugins/caelestia-assistant/assistant/data/corpus/DOC-TS-10.md @@ -0,0 +1,27 @@ +id: DOC-TS-10 +title: 10. Update Issues +source: docs/TROUBLESHOOTING.md — section 10 (Update Issues) +tags: update, updater, update.sh, caelestia updater, re-clone, cache, install latest version + +### 10.1 Fixing caelestia updater (Recommended) + +By deleting the build cache and the update checker cache: + +```bash +rm -rf ~/.config/caelestia-update/repo ~/.cache/caelestia-update-repo +``` + +**Note:** This will have the updater clone the repo again which takes time according to your internet speed. Hence, the logs might seem stuck or tell you to restart the process, but just wait for it to finish. + +### 10.2 Using update.sh + +You can simply run `bash update.sh` in the cloned repo folder (~/caelestia-kde) to update to latest version. + +### 10.3 Install latest version from repo + +Run the following command to simply install the latest shell using installer. +```bash +curl -fsSL https://raw.githubusercontent.com/ladybug-me/caelestia-kde/main/install.sh | sh +``` + +- If it gives an error due to already present `~/caelestia-kde` directory in your pc, then remove that directory first and then run the above command. **Make sure to copy the `backups/` folder somewhere and then put it back here after installation completes.** diff --git a/plugins/caelestia-assistant/assistant/data/corpus/DOC-TS-11.md b/plugins/caelestia-assistant/assistant/data/corpus/DOC-TS-11.md new file mode 100755 index 0000000..7f6efa3 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/data/corpus/DOC-TS-11.md @@ -0,0 +1,85 @@ +id: DOC-TS-11 +title: 11. Diagnostic Commands Reference +source: docs/TROUBLESHOOTING.md — section 11 (Diagnostic Commands Reference) +tags: diagnostics, diagnostic commands, reference, journalctl, systemctl status, debug mode, system state checks, kde cache refresh, kbuildsycoca6, logs + +### System State Checks + +```bash +# KWin reconfigure +qdbus6 org.kde.KWin /KWin reconfigure + +# Check user services +systemctl --user list-units | grep -E 'caelestia|quickshell' + +# Check KWin plugins +kwriteconfig6 --file kwinrc --group Plugins --key list + +# Verify QML imports +qml6 -p ~/.config/quickshell/caelestia/shell.qml 2>&1 | head -30 +``` + +### Caelestia-Specific Diagnostics + +```bash +# Check if the shell binary was built +ls -la ~/.local/lib/qt6/qml/Caelestia/ + +# Check installed wallpaper plugin +kpackagetool6 --list -t Plasma/Wallpaper + +# Read lock screen config +kreadconfig6 --file kscreenlockerrc --group Greeter --key WallpaperPlugin + +# View failed packages log +cat $XDG_CACHE_HOME/caelestia-kde/failed_packages.txt 2>/dev/null + +# View failed patches log +cat $XDG_CACHE_HOME/caelestia-kde/failed_patches.txt 2>/dev/null + +# View installer build log +cat /tmp/caelestia_build.log 2>/dev/null | tail -60 + +# View installer stderr log +cat /tmp/caelestia_installer_err.log 2>/dev/null +``` + +### Network Diagnostics + +```bash +# Test submodule availability +git ls-remote https://github.com/ladybug-me/caelestia-kde.git HEAD + +# Test AUR access +curl -sI https://aur.archlinux.org/rpc/?v=5\&type=info\&arg[]=quickshell-git | head -5 +``` + +### KDE Cache Refresh + +```bash +# Rebuild desktop file cache +kbuildsycoca6 --noincremental + +# Refresh desktop database +update-desktop-database ~/.local/share/applications/ + +# Restart Plasma shell (affects current session) +systemctl --user restart plasma-plasmashell +``` + +--- + +## Quick Reference: Common Fixes + +| Problem | Quick Fix | +|---|---| +| Shell won't start | `quickshell -d -n -p ~/.config/quickshell/caelestia/shell.qml` | +| Lock screen not active | `kwriteconfig6 --file plasmashellrc --group "Shell" --key "ShellPackage" "caelestia.desktop"` | +| Stale lock file | `rm -f "${XDG_RUNTIME_DIR:-/tmp}/caelestia-setup.lock"` | +| Missing QML module | `export QML2_IMPORT_PATH="$HOME/.local/lib/qt6/qml"` | +| No window thumbnails | `kbuildsycoca6 --noincremental && qdbus6 org.kde.KWin /KWin reconfigure` | +| Git submodule error | `git submodule update --init --recursive src/dots` | +| Colors not updating | Run `caelestia scheme set -n dynamic`, and check that `plasma-apply-colorscheme --list-schemes` names Matugen | +| Installer compiles but flashes/exits | Check `/tmp/caelestia_installer_err.log` | +| Recording not working | Verify `gpu-screen-recorder` is installed | +| Screenshot not working | Verify `spectacle` is installed | diff --git a/plugins/caelestia-assistant/assistant/data/corpus/ISS-006.md b/plugins/caelestia-assistant/assistant/data/corpus/ISS-006.md new file mode 100755 index 0000000..76c492e --- /dev/null +++ b/plugins/caelestia-assistant/assistant/data/corpus/ISS-006.md @@ -0,0 +1,23 @@ +id: ISS-006 +title: Bluetooth not working +source: issue #6 (CLOSED, stateReason COMPLETED) https://github.com/ladybug-me/caelestia-kde/issues/6 +tags: bluetooth, bluez, bluez-utils, pairing, bluetooth.service, turns on then off, cachyos +synonyms: bluetooth widget does nothing, bt pairing fails, bluetooth toggle flips back + +# ISS-006 — Bluetooth not working + +State: CLOSED, stateReason COMPLETED · opened 2026-06-26 by Kyedae. + +## Problem (original report, condensed) + +Enabling bluetooth via quickshell widget, or the kde system settings does nothing, it turns on then turns off, nothing pairs. + + - CachyOS + - Plasma Version 6.7 + +## Resolution + +Participants' positions (paraphrased): the maintainers' and collaborators' points are summarized in the curated notes and tags on this page; the original wording lives at the source URL below. +## Thread summary (paraphrased) + +9 comments by ladybug-me, planck4 between 2026-06-26 and 2026-09-09. Decisions and scope notes are reflected in the curated notes above; the full history lives at https://github.com/ladybug-me/caelestia-kde/issues/6. diff --git a/plugins/caelestia-assistant/assistant/data/corpus/ISS-014.md b/plugins/caelestia-assistant/assistant/data/corpus/ISS-014.md new file mode 100755 index 0000000..500ff31 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/data/corpus/ISS-014.md @@ -0,0 +1,31 @@ +id: ISS-014 +title: kde colour scheme auto sets to material you dark +source: issue #14 (CLOSED, stateReason COMPLETED) https://github.com/ladybug-me/caelestia-kde/issues/14 +tags: kde-material-you-colors, material you dark, color scheme, setup.sh, systemd user service, logout +synonyms: colors change on their own, scheme resets to material you, screen flash stutters + +# ISS-014 — kde colour scheme auto sets to material you dark + +State: CLOSED, stateReason COMPLETED · opened 2026-06-28 by 26heij. + +## Problem (original report, condensed) + +After running the setup.sh and prompting to keep my existing theme the colour scheme still changed to Material You Dark. I changed it to custom theme i use in system settings and reran the setup.sh to check if it was an actual bug and again the colour schema changed to material you dark. i changed it to my custom once again and did a **reboot and it changed again**. +I checked it with a logout and it aslo setted the colour scheme to material you dark. +Then i changed the colur scheme to material you Light and did a log out , login and again i was on material you Dark. then i tried with other material you colors and and other colors and they were also replaced by Material You Dark after a logout login. + +- Basically everytime **quickshell is being reloaded** (logout/in , reboot, running setup.sh) the the color ik kde is seted to **Material You Dark** color automatically. + +- Also for every setup.sh run, that many material you colors are being installed. + 3 run = 3 set of material you dark , light , dark(darker titlebar) , light(darker titlebar) +[image] + + - Fedora 44 + - KDE Plasma 6.7.1 + +## Resolution + +Participants' positions (paraphrased): the maintainers' and collaborators' points are summarized in the curated notes and tags on this page; the original wording lives at the source URL below. +## Thread summary (paraphrased) + +13 comments by 26heij, ladybug-me between 2026-06-28 and 2026-06-29. Decisions and scope notes are reflected in the curated notes above; the full history lives at https://github.com/ladybug-me/caelestia-kde/issues/14. diff --git a/plugins/caelestia-assistant/assistant/data/corpus/ISS-120.md b/plugins/caelestia-assistant/assistant/data/corpus/ISS-120.md new file mode 100755 index 0000000..6b2e073 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/data/corpus/ISS-120.md @@ -0,0 +1,85 @@ +id: ISS-120 +title: Feat: AI-Powered Natural Language Settings Assistant +source: issue #120 (OPEN) https://github.com/ladybug-me/caelestia-kde/issues/120 +tags: ai assistant, natural language, settings assistant, scope, ollama, caelestia-cli tools, apertus, model direction +synonyms: what can the assistant do, assistant scope, nl settings assistant, which model will the assistant use +repo_commit: f8760cb02c406fb74969a7b6003ffd583ad71a8d + +# ISS-120 — Feat: AI-Powered Natural Language Settings Assistant + +State: OPEN · opened 2026-07-11 by dr-strange15. + +This thread is OPEN: there is no resolution. It is part of the corpus because it defines what the on-device assistant itself may claim to do — no more, no less. + +## Proposal (original, condensed) + +I think Caelestia-kde-dots is in a unique position to make desktop customization much more approachable by allowing users to configure the shell using natural language. + +Instead of manually searching through Nexus or editing configuration files, users could simply describe what they want. + +Examples: + +- "Make my bar thinner." +- "Move the dock to the left." +- "Increase the blur." +- "Make everything feel more compact." +- "Give the desktop a minimal look." + +The assistant would interpret the request, convert it into structured configuration changes, and apply them through Caelestia's existing configuration system. + +--- + +After looking through the project, it feels like most of the pieces already exist. + +Caelestia already has: + +- AI Assistant +- Ollama integration +- `ConfigObject` architecture +- Live configuration updates +- Nexus settings application + +Right now these are mostly independent systems. + +Connecting them together could make Caelestia one of the easiest and most intituve desktop environments on whole of linux to customize without introducing an entirely new subsystem. + +--- + +The assistant should never modify configuration files directly. + +Instead, it should only request changes through a controlled API. + +The overall flow could look something like this: + +```text +User + │ + ▼ +AI Assistant + │ + ▼ +Intent Parser + │ + ▼ +Structured Tool Calls + │ + ▼ +ConfigObject / …[truncated] + +## Scope + +Maintainer (ladybug-me, paraphrased): the AI assistant already routes shell handling through caelestia-cli but that path was not working at the time; a few tools (screenshot, get_weather, web_search, read_wbpg) worked, the rest were pending updates. +Maintainer direction (2026-09-22, paraphrased): the issue was handed over to contributor 0x0nYx, who was pointed at the shell's predefined agentic tools as the integration path. +Corpus note (curated from this thread): the on-device assistant in this repo stays on the narrow side of this proposal — it retrieves documentation and past resolutions and prints inert suggestions; it never parses natural-language requests into config writes (the settings layer is a separate module behind an explicit --apply). +Corpus note (2026-09-23 direction, open thread): the maintainer handed the issue to contributor 0x0nYx and pointed at the shell's predefined agentic tools; collaborator 0xSolanaceae wants to explore the Apertus AI model family (https://www.apertus-ai.org/) for the assistant, says assets need cutting down, and invited a PR; the model would NOT ship bundled with the shell ("it'll have to be downloaded from the ui"), and 0x0nYx expects the model asset to be "gonna publish that on GitHub instead cuz it will be ofc greater than 500mbs". Per the collaborator on 2026-09-22, implementation "has fallen to the backlog bc of all the more important features and bugfixes we need to ship first". No model choice, bundling decision, or in-shell API is settled — the thread is OPEN, with the assistant work currently backlogged behind higher-priority features and bugfixes. + +## Thread summary (paraphrased) + +18 comments by 0x0nYx, 0xSolanaceae, ladybug-me between 2026-07-11 and 2026-09-25. Decisions and scope notes are reflected in the curated notes above; the full history lives at https://github.com/ladybug-me/caelestia-kde/issues/120. +## Fetch reconciliation (2026-09-28) + +Re-fetched live via the GitHub REST API (14 comments, issue still OPEN, unassigned, +labeled `feature`, last updated 2026-09-25T17:34:30Z). This corpus keeps only the +paraphrased summaries above; some early comments (including the handover discussion +of 2026-09-22, part of which the original author later deleted from the live thread) +are visible only in the issue's own history at the source URL. diff --git a/plugins/caelestia-assistant/assistant/data/corpus/ISS-333.md b/plugins/caelestia-assistant/assistant/data/corpus/ISS-333.md new file mode 100755 index 0000000..08d533a --- /dev/null +++ b/plugins/caelestia-assistant/assistant/data/corpus/ISS-333.md @@ -0,0 +1,25 @@ +id: ISS-333 +title: Shortcuts not working +source: issue #333 (CLOSED, stateReason COMPLETED) https://github.com/ladybug-me/caelestia-kde/issues/333 +tags: shortcuts not working, kglobalaccel, unrecognized pragma, defaultenv, qs_no_reload_popup, dev branch update +synonyms: keyboard shortcuts dead, keybinds do nothing, global shortcuts broken + +# ISS-333 — Shortcuts not working + +State: CLOSED, stateReason COMPLETED · opened 2026-07-29 by MayoNas3. + +## Problem (original report, condensed) + +none of the shortcuts are working, and i did read issue #5 as well as the troubleshooting guide. I'm not sure what went wrong. also, I'm not sure what info to include, so I'll just send whatever I'm asked for - sorry. + +```markdown +CachyOS +KDE Plasma 6.7.3 +``` + +## Resolution + +Participants' positions (paraphrased): the maintainers' and collaborators' points are summarized in the curated notes and tags on this page; the original wording lives at the source URL below. +## Thread summary (paraphrased) + +11 comments by 0xSolanaceae, MayoNas3 between 2026-07-29 and 2026-07-29. Decisions and scope notes are reflected in the curated notes above; the full history lives at https://github.com/ladybug-me/caelestia-kde/issues/333. diff --git a/plugins/caelestia-assistant/assistant/data/corpus/ISS-402.md b/plugins/caelestia-assistant/assistant/data/corpus/ISS-402.md new file mode 100755 index 0000000..84e3a34 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/data/corpus/ISS-402.md @@ -0,0 +1,42 @@ +id: ISS-402 +title: Error that causes Vesktop (discord) crash when using camera and/or screen share with audio +source: issue #402 (CLOSED, stateReason COMPLETED) https://github.com/ladybug-me/caelestia-kde/issues/402 +tags: vesktop, discord, screenshare, screen share, camera, freeze, zkde_screencast_unstable_v1, pipewire, nvidia +synonyms: vesktop freezes when i screenshare, discord crash camera, stream with audio freezes + +# ISS-402 — Error that causes Vesktop (discord) crash when using camera and/or screen share with audio + +State: CLOSED, stateReason COMPLETED · opened 2026-08-01 by R0XX133. + +## Problem (original report, condensed) + +Configuration: +GPU: Nvidia Geforce RTX 4060 +CPU: Intel Core i7-4790 (3.60hz) +OS: CachyOS +Kernel: 7.1.5-1-cachOS +RAM: 32GB + +I've been running into an issue when I use vesktop, + +if I stream with audio or turn on my camera, it'll freeze vesktop and I'm forced to restart the app. +If I stream without audio, it'll work fine sometimes +Issue seems to be only with Vesktop (haven't tried regular discord) since I tried it on the browser and worked flawlessly. + +it started once I downloaded caelestia + +1. Download vesktop +2. join a call +3. turn on camera or stream with audio + +v2.2.2 + +CachyOS + +## Resolution + +Closed by PR #586 (MERGED). +Participants' positions (paraphrased): the maintainers' and collaborators' points are summarized in the curated notes and tags on this page; the original wording lives at the source URL below. +## Thread summary (paraphrased) + +12 comments by 0xSolanaceae, Kyedae, R0XX133 between 2026-08-01 and 2026-08-04. Decisions and scope notes are reflected in the curated notes above; the full history lives at https://github.com/ladybug-me/caelestia-kde/issues/402. diff --git a/plugins/caelestia-assistant/assistant/data/corpus/ISS-409.md b/plugins/caelestia-assistant/assistant/data/corpus/ISS-409.md new file mode 100755 index 0000000..5ecc8ca --- /dev/null +++ b/plugins/caelestia-assistant/assistant/data/corpus/ISS-409.md @@ -0,0 +1,26 @@ +id: ISS-409 +title: Video wallpapers are not appearing +source: issue #409 (CLOSED, stateReason COMPLETED) https://github.com/ladybug-me/caelestia-kde/issues/409 +tags: video wallpaper, live wallpaper, pause video wallpaper, pipewire, audio endpoint, wallpaper flashing +synonyms: video wallpapers not appearing, live wallpaper duplicated, wallpaper does not play + +# ISS-409 — Video wallpapers are not appearing + +State: CLOSED, stateReason COMPLETED · opened 2026-08-03 by francisco-tato. + +## Problem (original report, condensed) + +Live wallpapers do not appear as the background (some are duplicated). + +v2.2.4 (5fc7d98d Dev) + +Garuda Linux + +[attachment] + +## Resolution + +Participants' positions (paraphrased): the maintainers' and collaborators' points are summarized in the curated notes and tags on this page; the original wording lives at the source URL below. +## Thread summary (paraphrased) + +11 comments by francisco-tato, ladybug-me between 2026-08-03 and 2026-08-04. Decisions and scope notes are reflected in the curated notes above; the full history lives at https://github.com/ladybug-me/caelestia-kde/issues/409. diff --git a/plugins/caelestia-assistant/assistant/data/corpus/ISS-416.md b/plugins/caelestia-assistant/assistant/data/corpus/ISS-416.md new file mode 100755 index 0000000..3916efc --- /dev/null +++ b/plugins/caelestia-assistant/assistant/data/corpus/ISS-416.md @@ -0,0 +1,24 @@ +id: ISS-416 +title: Launcher not opening on the correct screen and cant use alt tab when fullscreened on another monitor +source: issue #416 (CLOSED, stateReason COMPLETED) https://github.com/ladybug-me/caelestia-kde/issues/416 +tags: launcher wrong monitor, alt-tab, window switcher, fullscreen video, multi-monitor, input region +synonyms: launcher opens on wrong screen, cant alt tab when fullscreened, window switcher wrong monitor + +# ISS-416 — Launcher not opening on the correct screen and cant use alt tab when fullscreened on another monitor + +State: CLOSED, stateReason COMPLETED · opened 2026-08-04 by Kyedae. + +## Problem (original report, condensed) + +This happens randomly but it happens everytime you fullscreen a video on another monitor, then u go to another monitor it keeps trying to open the launcher on the monitor that has the fullscreened video (it doesnt even pop up until u unfullscreen the video so it never shows), you also cant alt tab either to use the window switcher, basically all functionality breaks on the other monitor if something is fullscreened + +Dev + +Cachyos + +## Resolution + +Participants' positions (paraphrased): the maintainers' and collaborators' points are summarized in the curated notes and tags on this page; the original wording lives at the source URL below. +## Thread summary (paraphrased) + +12 comments by Kyedae, WinTone01, ladybug-me between 2026-08-04 and 2026-08-04. Decisions and scope notes are reflected in the curated notes above; the full history lives at https://github.com/ladybug-me/caelestia-kde/issues/416. diff --git a/plugins/caelestia-assistant/assistant/data/corpus/ISS-418.md b/plugins/caelestia-assistant/assistant/data/corpus/ISS-418.md new file mode 100755 index 0000000..5803a81 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/data/corpus/ISS-418.md @@ -0,0 +1,26 @@ +id: ISS-418 +title: When quickshell crashes window switcher no longer shows windows, and if u have multiple monitors it doesnt open anything on the correct monitor anymore and it doesnt come back +source: issue #418 (CLOSED, stateReason COMPLETED) https://github.com/ladybug-me/caelestia-kde/issues/418 +tags: quickshell has crashed, kwinactivewindowbridge, window switcher empty, workspace icons, shell restart, clean reset +synonyms: quickshell crashed dialog, bar shows no window icons, restart shell after crash + +# ISS-418 — When quickshell crashes window switcher no longer shows windows, and if u have multiple monitors it doesnt open anything on the correct monitor anymore and it doesnt come back + +State: CLOSED, stateReason COMPLETED · opened 2026-08-05 by Kyedae. + +Curated note: the quickshell crash-dialog report was filed on 2026-08-05 (reporter Kyedae); the fix landed the same day and the issue was closed as completed. + +## Problem (original report, condensed) + +Title ^ + +Dev + +CachyOS + +## Resolution + +Participants' positions (paraphrased): the maintainers' and collaborators' points are summarized in the curated notes and tags on this page; the original wording lives at the source URL below. +## Thread summary (paraphrased) + +10 comments by Kyedae, ladybug-me between 2026-08-05 and 2026-08-05. Decisions and scope notes are reflected in the curated notes above; the full history lives at https://github.com/ladybug-me/caelestia-kde/issues/418. diff --git a/plugins/caelestia-assistant/assistant/data/corpus/ISS-461.md b/plugins/caelestia-assistant/assistant/data/corpus/ISS-461.md new file mode 100755 index 0000000..73f7147 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/data/corpus/ISS-461.md @@ -0,0 +1,29 @@ +id: ISS-461 +title: [CRITICAL] Weird crashing issue? need help indentifying +source: issue #461 (CLOSED, stateReason COMPLETED) https://github.com/ladybug-me/caelestia-kde/issues/461 +tags: random apps crash, chromium, spotify, discord, steam, memory usage, live previews, systemd-cgtop +synonyms: apps randomly crash, browsers crash after caelestia, memory leak quickshell + +# ISS-461 — [CRITICAL] Weird crashing issue? need help indentifying + +State: CLOSED, stateReason COMPLETED · opened 2026-08-12 by Kyedae. + +## Problem (original report, condensed) + +For some reason when im doing random things sometimes random apps crash, they primarily seem to be chromium apps, Helium, Spotify, Discord, Steam, they sometimes randomly crash when clicking or just interacting with things, its difficult to reproduce on the spot, but when i had codex scan my system for the crash issue it seems to be involving Caelestia and the apps are victims, ill attach images with information + +Latest Stable + +CachyOS + +[image] + +[image] + +## Resolution + +Closed by PR #462 (MERGED), #496 (MERGED). +Participants' positions (paraphrased): the maintainers' and collaborators' points are summarized in the curated notes and tags on this page; the original wording lives at the source URL below. +## Thread summary (paraphrased) + +11 comments by 0xSolanaceae, Kyedae between 2026-08-12 and 2026-08-12. Decisions and scope notes are reflected in the curated notes above; the full history lives at https://github.com/ladybug-me/caelestia-kde/issues/461. diff --git a/plugins/caelestia-assistant/assistant/data/corpus/ISS-528.md b/plugins/caelestia-assistant/assistant/data/corpus/ISS-528.md new file mode 100755 index 0000000..0638c41 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/data/corpus/ISS-528.md @@ -0,0 +1,26 @@ +id: ISS-528 +title: Quickshell does not open +source: issue #528 (CLOSED, stateReason COMPLETED) https://github.com/ladybug-me/caelestia-kde/issues/528 +tags: quickshell does not open, error after update, reinstall quickshell-git, paru, pacman, garuda +synonyms: quickshell wont start after update, shell broken after caelestia update, reinstall quickshell + +# ISS-528 — Quickshell does not open + +State: CLOSED, stateReason COMPLETED · opened 2026-08-24 by francisco-tato. + +## Problem (original report, condensed) + +I updated to the latest dev version and QuickShell gives an error when I open it. + +Last Dev + +Garuda Linux + +[image] + +## Resolution + +Participants' positions (paraphrased): the maintainers' and collaborators' points are summarized in the curated notes and tags on this page; the original wording lives at the source URL below. +## Thread summary (paraphrased) + +14 comments by WinTone01, francisco-tato, ladybug-me between 2026-08-24 and 2026-08-24. Decisions and scope notes are reflected in the curated notes above; the full history lives at https://github.com/ladybug-me/caelestia-kde/issues/528. diff --git a/plugins/caelestia-assistant/assistant/data/corpus/ISS-565.md b/plugins/caelestia-assistant/assistant/data/corpus/ISS-565.md new file mode 100644 index 0000000..3d80bd1 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/data/corpus/ISS-565.md @@ -0,0 +1,51 @@ +id: ISS-565 +title: Two independent update mechanisms share version-tracking state but pull from different repo checkouts +source: issue #565 (OPEN) https://github.com/ladybug-me/caelestia-kde/issues/565 +tags: dual updater, state desync, current_commit, update_branch, nexus install updates, update.sh, shadow clone, uncommitted changes lost, pending commit badge wrong +synonyms: pending commits wrong, nexus updates count mismatch, my local edits disappeared after update, updater overwrote my clone + +# ISS-565 — Dual-updater state desync + +State: OPEN (as of 2026-09-26). + +## Problem (condensed from the original report) + +Two independent updaters deploy to the same destinations but read from +different sources of truth: + +- `update.sh` (top-level, dev workflow) uses `BUNDLE_DIR` = wherever the + script physically lives — the user's real git clone. +- `src/bin/caelestia-update` (installed to `~/.local/bin`, driven by the + Nexus "Install Updates" button) maintains a private sparse-checkout + clone at `~/.config/caelestia-update/repo`, does + `git reset --hard`/`git clean -fdx` THERE, and deploys from that + unrelated checkout. + +Both paths end by writing +`~/.config/quickshell/caelestia/.current_commit` and `.update_branch` +from `git -C "$BUNDLE_DIR" rev-parse HEAD` — but `$BUNDLE_DIR` means a +different repository depending on which updater ran last. +`caelestia-check-updates` then diffs `.current_commit` against its own +bare mirror for the pending-commit badge, so alternating between the two +paths yields a commit hash that does not correspond to the user's real +clone — and the deploy from the shadow clone overwrites +`~/.config/quickshell/caelestia/*`, including discarding uncommitted +local edits in the real clone. + +## What users see (the symptom this rule fingerprints) + +- The Nexus Updates page reports a pending-commit count that does not + match `git -C ~/caelestia-dots-kde log` in the real clone. +- Uncommitted local changes in the real clone disappear after using + Nexus "Install Updates". +- `.current_commit` under `~/.config/quickshell/caelestia/` does not + match any commit in the user's own checkout. + +## Fix direction + +Pick ONE updater path and stick to it; commit or stash local edits +before any updater runs; verify the real clone with +`git -C rev-parse HEAD` against +`~/.config/quickshell/caelestia/.current_commit`. The issue is open +upstream — until it lands, users alternating between `update.sh` and the +Nexus button remain exposed to the desync. diff --git a/plugins/caelestia-assistant/assistant/data/corpus/ISS-616.md b/plugins/caelestia-assistant/assistant/data/corpus/ISS-616.md new file mode 100755 index 0000000..17e1818 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/data/corpus/ISS-616.md @@ -0,0 +1,33 @@ +id: ISS-616 +title: GPU usage and temperature are averaged across every /sys/class/drm/card* device, producing meaningless numbers on hybrid-graphics/multi-GPU systems +source: issue #616 (CLOSED, stateReason COMPLETED) https://github.com/ladybug-me/caelestia-kde/issues/616 +tags: gpu widget, gpu usage averaged, gpu_busy_percent, /sys/class/drm, multi-gpu, hybrid graphics, temperature +synonyms: gpu percent wrong, gpu shows half usage, two gpus averaged + +# ISS-616 — GPU usage and temperature are averaged across every /sys/class/drm/card* device, producing meaningless numbers on hybrid-graphics/multi-GPU systems + +State: CLOSED, stateReason COMPLETED · opened 2026-09-05 by 0x0nYx. + +## Problem (original report, condensed) + +On my Ryzen APU + discrete AMD GPU desktop, the GPU usage widget shows roughly half of what either GPU is actually doing under load — running a game that pegs the discrete card at 100% while the iGPU sits idle at 0% displays as ~50% in the bar/Nexus resource widgets. + +Root cause: `shell/plugin/src/Caelestia/Services/gpu.cpp`, `readGenericUsage()`: +```cpp +const QStringList paths = QDir("/sys/class/drm").entryList({"card*"}, QDir::Dirs | QDir::NoDotAndDotDot); +qreal sum = 0.0; int count = 0; +for (const QString& card : paths) { + QFile f(QString("/sys/class/drm/%1/device/gpu_busy_percent").arg(card)); + if (f.open(...)) { sum += f.readAll().trimmed().toDouble(&ok); ++count; } +} +const qreal newPerc = count > 0 ? sum / count / 100.0 : 0.0; +``` +This walks *every* `cardN` entry that exposes `gpu_busy_percent` and averages them into one number with no attempt to identify which card is the "real"/active GPU (discrete vs integrated, or primary vs secondary in a multi-GPU box). The type-detection script a few lines up (`kTypeDetectScript`) already treats "any card with `gpu_busy_percent`" as sufficient to classify the system as `GENERIC`, so this isn't a one-GPU-assumption edge case — it's the intended code path for any non-Nvidia system, and it breaks the moment there's more than one DRM card. The temperature path has the identical problem: `readGpuTemperature()` calls …[truncated] + +## Resolution + +Closed by PR #633 (CLOSED). +Participants' positions (paraphrased): the maintainers' and collaborators' points are summarized in the curated notes and tags on this page; the original wording lives at the source URL below. +## Thread summary (paraphrased) + +13 comments by 0x0nYx, ladybug-me between 2026-09-05 and 2026-09-05. Decisions and scope notes are reflected in the curated notes above; the full history lives at https://github.com/ladybug-me/caelestia-kde/issues/616. diff --git a/plugins/caelestia-assistant/assistant/data/corpus/ISS-629.md b/plugins/caelestia-assistant/assistant/data/corpus/ISS-629.md new file mode 100644 index 0000000..94a93a3 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/data/corpus/ISS-629.md @@ -0,0 +1,47 @@ +id: ISS-629 +title: Installer permanently enables ccache system-wide with no disclosure and no reversal on uninstall +source: issue #629 (CLOSED 2026-09-06) https://github.com/ladybug-me/caelestia-kde/issues/629 +tags: ccache, makepkg.conf, buildenv, aur builds, installer side effect, uninstall, system-wide change +synonyms: aur builds slow, ccache eating disk, makepkg.conf changed without consent, build cache misses + +# ISS-629 — Installer permanently flips ccache in /etc/makepkg.conf + +State: CLOSED (2026-09-06) · Severity: Medium. + +## Problem (condensed from the original report) + +Months after installing Caelestia the reporter traced unexpectedly long +AUR build times and ccache disk usage to `/etc/makepkg.conf` having +`ccache` enabled in `BUILDENV` — something they never enabled. + +Root cause (quoted in the issue): `scripts/01-ensure-prereqs.sh` ran + +```bash +sudo sed -i 's/!ccache/ccache/' /etc/makepkg.conf +``` + +during the one-time "Ensure prerequisites" step. That edits the +system-wide file governing every `makepkg`/AUR build on the machine — +silently, undocumented, and `uninstall.sh` never reverted it, so the +change outlived Caelestia entirely. + +## What users see (the symptom this rule fingerprints) + +- AUR/makepkg builds behave differently (ccache cache misses eating disk, + changed build output paths) on a machine where the user never enabled + ccache. +- `/etc/makepkg.conf` shows `ccache` (no `!`) in `BUILDENV` after a + Caelestia install. + +## Fix direction (as discussed in the issue) + +Check and re-disable if unwanted: + +```bash +grep BUILDENV /etc/makepkg.conf +sudo sed -i 's/^BUILDENV=(\([^)]*\)ccache /\1!ccache /' /etc/makepkg.conf +``` + +(distros package the exact syntax differently — inspect the file first). +The upstream fix removed the flip and disclosed the historical change; +users on older versions still carry the modified file. diff --git a/plugins/caelestia-assistant/assistant/data/corpus/ISS-641.md b/plugins/caelestia-assistant/assistant/data/corpus/ISS-641.md new file mode 100755 index 0000000..d8e0c1c --- /dev/null +++ b/plugins/caelestia-assistant/assistant/data/corpus/ISS-641.md @@ -0,0 +1,24 @@ +id: ISS-641 +title: Game fullscreen problem +source: issue #641 (CLOSED, stateReason COMPLETED) https://github.com/ladybug-me/caelestia-kde/issues/641 +tags: gamescope, game half screen, fullscreen, dodge windows, meta+shift+e, taskbar, games launch options +synonyms: game launches in half the screen, gamescope bottom of desktop visible, dodge windows toggle + +# ISS-641 — Game fullscreen problem + +State: CLOSED, stateReason COMPLETED · opened 2026-09-06 by AnubhavXP. + +## Problem (original report, condensed) + +I have some games that have gamescope in launch options for higher resolutions those games get launched in half of the screen bottom of the dekstop is still visible i tried hiding the taskbar it increased game window size but not fully.The game without gamescope code works fine .I dont know if its a bug .But i would like to know if there is a workaround to this + +v2.3.2 + +fedora + +## Resolution + +Participants' positions (paraphrased): the maintainers' and collaborators' points are summarized in the curated notes and tags on this page; the original wording lives at the source URL below. +## Thread summary (paraphrased) + +14 comments by AnubhavXP, WinTone01, ladybug-me between 2026-09-06 and 2026-09-06. Decisions and scope notes are reflected in the curated notes above; the full history lives at https://github.com/ladybug-me/caelestia-kde/issues/641. diff --git a/plugins/caelestia-assistant/assistant/data/corpus/ISS-738.md b/plugins/caelestia-assistant/assistant/data/corpus/ISS-738.md new file mode 100755 index 0000000..a0b12c6 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/data/corpus/ISS-738.md @@ -0,0 +1,25 @@ +id: ISS-738 +title: Ambient color mode +source: issue #738 (CLOSED, stateReason COMPLETED) https://github.com/ladybug-me/caelestia-kde/issues/738 +tags: ambient color mode, ambient glow, window previews, overview, dock popups, youtube ambilight, feature request +synonyms: ambient light from window colors, glow around windows like youtube, ambience from screen content +repo_commit: f8760cb02c406fb74969a7b6003ffd583ad71a8d + +# ISS-738 — Ambient color mode + +State: CLOSED, stateReason COMPLETED · opened 2026-09-15 by ladybug-me · closed 2026-09-22 (implemented). + +## Proposal (original, condensed) + +Feature request (label: feature), filed by the maintainer herself: + +> Implement YouTube like ambient color mode to appropriate parts of the shell like Window Info (overview) or Dock popups using colors from window previews. +> +> Algorithm: [Youtube-ambilight](https://github.com/Fefedu973/Youtube-ambilight) + +## Resolution + +Participants' positions (paraphrased): the maintainers' and collaborators' points are summarized in the curated notes and tags on this page; the original wording lives at the source URL below. +## Comment log + +- (no comments on this issue; the only timeline events are `labeled` 2026-09-15 and `closed` by ladybug-me 2026-09-22 10:13) diff --git a/plugins/caelestia-assistant/assistant/data/corpus/ISS-744.md b/plugins/caelestia-assistant/assistant/data/corpus/ISS-744.md new file mode 100755 index 0000000..3912d04 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/data/corpus/ISS-744.md @@ -0,0 +1,25 @@ +id: ISS-744 +title: Brightness slider shows a moon icon instead of a sun +source: issue #744 (CLOSED, stateReason COMPLETED) https://github.com/ladybug-me/caelestia-kde/issues/744 +tags: brightness slider, moon icon, sun icon, night light, right side panel, icon bug, quick settings +synonyms: brightness control shows a moon, wrong icon on the brightness slider, moon on brightness like night light +repo_commit: f8760cb02c406fb74969a7b6003ffd583ad71a8d + +# ISS-744 — Brightness slider shows a moon icon instead of a sun + +State: CLOSED, stateReason COMPLETED · opened 2026-09-16 by aroaxinping · closed 2026-09-21. + +## Problem (original report, condensed) + +> The brightness slider on the right side panel shows a moon icon instead of a sun icon. The moon is normally associated with night light, not brightness. The night light section in the settings panel already has its own toggle and temperature sliders, so having the moon on the brightness slider is confusing. +> +> Expected: the brightness slider should show a sun icon (or a brightness icon) to distinguish it from the night light controls. + +(Two screenshots of the side panel were attached; image content is not quoted.) + +## Resolution + +Participants' positions (paraphrased): the maintainers' and collaborators' points are summarized in the curated notes and tags on this page; the original wording lives at the source URL below. +## Thread summary (paraphrased) + +1 comment by 0xSolanaceae between 2026-09-21 and 2026-09-21. Decisions and scope notes are reflected in the curated notes above; the full history lives at https://github.com/ladybug-me/caelestia-kde/issues/744. diff --git a/plugins/caelestia-assistant/assistant/data/corpus/ISS-763.md b/plugins/caelestia-assistant/assistant/data/corpus/ISS-763.md new file mode 100755 index 0000000..b69f35e --- /dev/null +++ b/plugins/caelestia-assistant/assistant/data/corpus/ISS-763.md @@ -0,0 +1,28 @@ +id: ISS-763 +title: [Colors] color variant changes back to "Tonal Spot" afther restart. +source: issue #763 (CLOSED, stateReason COMPLETED) https://github.com/ladybug-me/caelestia-kde/issues/763 +tags: color variant reverts, tonal spot, after reboot, after login, automatic color scheme, color engine +synonyms: colors revert after reboot, variant changes back to tonal spot, scheme resets after login + +# ISS-763 — [Colors] color variant changes back to "Tonal Spot" afther restart. + +State: CLOSED, stateReason COMPLETED · opened 2026-09-17 by MITSIKU. + +## Problem (original report, condensed) + +when changing a color variant afther rebooting it quickly changes back to Tonal Spot when logged in. + +1. set color to any variant (e.g. vibrant) +2. reboot +3. login and you will see it briefly be vibrant before going back to being Tonal Spot + +V2.4.2 + +CachyOS + +## Resolution + +Participants' positions (paraphrased): the maintainers' and collaborators' points are summarized in the curated notes and tags on this page; the original wording lives at the source URL below. +## Thread summary (paraphrased) + +10 comments by MITSIKU, ladybug-me between 2026-09-17 and 2026-09-20. Decisions and scope notes are reflected in the curated notes above; the full history lives at https://github.com/ladybug-me/caelestia-kde/issues/763. diff --git a/plugins/caelestia-assistant/assistant/data/corpus/ISS-765.md b/plugins/caelestia-assistant/assistant/data/corpus/ISS-765.md new file mode 100755 index 0000000..f737309 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/data/corpus/ISS-765.md @@ -0,0 +1,25 @@ +id: ISS-765 +title: ~/.local/bin not in path for bash +source: issue #765 (CLOSED, stateReason COMPLETED) https://github.com/ladybug-me/caelestia-kde/issues/765 +tags: path, bash, local bin, install.sh, autostart.sh, session environment, tty +synonyms: local bin not on path, caelestia commands not found in bash, path only after autostart +repo_commit: f8760cb02c406fb74969a7b6003ffd583ad71a8d + +# ISS-765 — ~/.local/bin not in path for bash + +State: CLOSED, stateReason COMPLETED · opened 2026-09-17 by ladybug-me · closed 2026-09-20. + +## Problem (original report, condensed) + +Bug (label: bug), filed by the maintainer as a tracking issue: + +> Applicable only when installation done through `install.sh` + +(The issue title is the report: `~/.local/bin` is not in `PATH` for bash after an `install.sh` install.) + +## Resolution + +Participants' positions (paraphrased): the maintainers' and collaborators' points are summarized in the curated notes and tags on this page; the original wording lives at the source URL below. +## Thread summary (paraphrased) + +1 comment by ladybug-me between 2026-09-20 and 2026-09-20. Decisions and scope notes are reflected in the curated notes above; the full history lives at https://github.com/ladybug-me/caelestia-kde/issues/765. diff --git a/plugins/caelestia-assistant/assistant/data/corpus/ISS-773.md b/plugins/caelestia-assistant/assistant/data/corpus/ISS-773.md new file mode 100755 index 0000000..cda525a --- /dev/null +++ b/plugins/caelestia-assistant/assistant/data/corpus/ISS-773.md @@ -0,0 +1,26 @@ +id: ISS-773 +title: Different paths for installation +source: issue #773 (CLOSED, stateReason COMPLETED) https://github.com/ladybug-me/caelestia-kde/issues/773 +tags: install paths, install.sh, package install, quickshell config dir, usr bin, etc xdg, caelestia-kde package +synonyms: where does install.sh install to, package vs script install paths, aur package file locations +repo_commit: f8760cb02c406fb74969a7b6003ffd583ad71a8d + +# ISS-773 — Different paths for installation + +State: CLOSED, stateReason COMPLETED · opened 2026-09-18 by ladybug-me · closed 2026-09-19. + +## Problem (original report, condensed) + +Tracking issue filed by the maintainer (no label), asking to follow upstream behaviour: + +> Follow upstream behaviour. +> +> - by install.sh: ~/.config/quickshell/ & ~/.local/bin/ +> - by caelestia-kde: /usr/bin & /etc/xdg/quickshell/caelestia/ for shell (confirm this one with upstream) + +## Resolution + +Participants' positions (paraphrased): the maintainers' and collaborators' points are summarized in the curated notes and tags on this page; the original wording lives at the source URL below. +## Thread summary (paraphrased) + +1 comment by ladybug-me between 2026-09-19 and 2026-09-19. Decisions and scope notes are reflected in the curated notes above; the full history lives at https://github.com/ladybug-me/caelestia-kde/issues/773. diff --git a/plugins/caelestia-assistant/assistant/data/corpus/ISS-774.md b/plugins/caelestia-assistant/assistant/data/corpus/ISS-774.md new file mode 100755 index 0000000..efc7ee6 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/data/corpus/ISS-774.md @@ -0,0 +1,30 @@ +id: ISS-774 +title: [Color] Verfiy terminal sequences bleed into notification +source: issue #774 (CLOSED, stateReason COMPLETED) https://github.com/ladybug-me/caelestia-kde/issues/774 +tags: terminal sequences, escape sequences, notifications, test_color.sh, color engine, matugen, fedora, arch +synonyms: numbers in notifications, garbage escape codes in notification text, weird notifications with a lot of numbers +repo_commit: f8760cb02c406fb74969a7b6003ffd583ad71a8d + +# ISS-774 — [Color] Verfiy terminal sequences bleed into notification + +State: CLOSED, stateReason COMPLETED · opened 2026-09-18 by ladybug-me · closed 2026-09-20. + +## Problem (original report, condensed) + +Bug (label: blocked), filed by the maintainer as a verification tracking issue: + +> Earlier affected distro was fedora. +> +> Currently, seen "terminal sequences" string being written into terminals on arch distros. +> NOTE: this one is irrelevant cause it only happens when running `tests/test_color.sh` +> +> Was fixed for old color engine, requires same for new one + +(The symptom: color-engine terminal escape sequences bleeding into notification text — "weird notifications containing a lot of numbers" in the maintainer's words below. The old color-engine fix had to be redone for the new matugen engine.) + +## Resolution + +Participants' positions (paraphrased): the maintainers' and collaborators' points are summarized in the curated notes and tags on this page; the original wording lives at the source URL below. +## Thread summary (paraphrased) + +2 comments by ladybug-me between 2026-09-18 and 2026-09-20. Decisions and scope notes are reflected in the curated notes above; the full history lives at https://github.com/ladybug-me/caelestia-kde/issues/774. diff --git a/plugins/caelestia-assistant/assistant/data/corpus/ISS-788.md b/plugins/caelestia-assistant/assistant/data/corpus/ISS-788.md new file mode 100755 index 0000000..efba0a3 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/data/corpus/ISS-788.md @@ -0,0 +1,37 @@ +id: ISS-788 +title: [FR] (?) Show taskbar notification indicators +source: issue #788 (CLOSED, stateReason COMPLETED) https://github.com/ladybug-me/caelestia-kde/issues/788 +tags: app badges, dock badges, taskbar notification indicators, unread count badge, progress bar, urgency tint, Unity LauncherEntry, com.canonical.Unity, session bus, Electron apps, feature request, showBadges, v2.5.0 +synonyms: no unread badges on dock icons, apps do not show notification count on the taskbar, discord red dot missing on the dock, badge indicators on the dock, dock app badges not showing +repo_commit: 70ee7da115fde9012e28e393c73d274f55bd2dd7 + +# ISS-788 — [FR] (?) Show taskbar notification indicators + +State: CLOSED, stateReason COMPLETED · opened 2026-09-20 by probablyjassin · closed 2026-09-22 by 0xSolanaceae, 14 seconds after PR #808 merged. + +Capture note: this issue was still OPEN as of the corpus frontier at the +time (#805, closed 2026-09-22T16:03:41Z); 0xSolanaceae closed it as +completed at 2026-09-22T19:59:41Z. Captured live via the GitHub REST API, +and the landed feature is verified offline in this checkout (dev @ +70ee7da, v2.5.0) — see "Landed in dev" below. + +## Problem (original report, condensed) + +Participants' positions (paraphrased): the maintainers' and collaborators' points are summarized in the curated notes and tags on this page; the original wording lives at the source URL below. +## Resolution + +Participants' positions (paraphrased): the maintainers' and collaborators' points are summarized in the curated notes and tags on this page; the original wording lives at the source URL below. +## Thread summary (paraphrased) + +2 comments by 0xSolanaceae between 2026-09-21 and 2026-09-22. Decisions and scope notes are reflected in the curated notes above; the full history lives at https://github.com/ladybug-me/caelestia-kde/issues/788. +## Landed in dev + +Verified offline in this checkout (dev @ 70ee7da115fde9012e28e393c73d274f55bd2dd7, `.github/version.env` says `VERSION=v2.5.0`): + +- `shell/plugin/src/Caelestia/Services/launcherentry.{hpp,cpp}` — the new `LauncherEntry` QML singleton (`forApp` / `revision`), which registers the `com.canonical.Unity` name when nothing else owns it and watches the `com.canonical.Unity.LauncherEntry` `Update` signal (constants at launcherentry.cpp:18-19). +- `shell/plugin/src/Caelestia/Config/barconfig.hpp:173` — `CONFIG_PROPERTY(bool, showBadges, true)` inside `class BarDock` (per-bar, mounted via `CONFIG_SUBOBJECT(BarDock, dock)`). +- `shell/modules/nexus/pages/panels/taskbar/BarDock.qml:75-82` — the shipped Nexus `ToggleRow` "Show app badges" / "Show the count, progress and urgency an app publishes for its dock icon", bound to `Config.bar.dock.showBadges`. +- `shell/modules/bar/components/Dock.qml:630-634` — the `badge` reader (`Config.bar.dock.showBadges ?? true`, null when off) over `LauncherEntry.forApp(modelData.id)`, plus the urgency tint, count badge and progress bar visuals. +- `shell/modules/whatsnew/Entries.qml` — revision 24, id `dock_app_badges`, "Dock App Badges": "Dock icons can now display the count, progress, and urgency published by running applications. Configure it under Settings -> Panels -> Taskbar -> Dock." + +Prompt-injection screening: no text in the captured issue or comments addresses an AI or tries to issue instructions to one — no fenced-block quarantine needed. diff --git a/plugins/caelestia-assistant/assistant/data/corpus/ISS-790.md b/plugins/caelestia-assistant/assistant/data/corpus/ISS-790.md new file mode 100755 index 0000000..eefd181 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/data/corpus/ISS-790.md @@ -0,0 +1,23 @@ +id: ISS-790 +title: [Color] Check Vibrant color pallette +source: issue #790 (CLOSED, stateReason COMPLETED) https://github.com/ladybug-me/caelestia-kde/issues/790 +tags: vibrant palette, matugen, materialyoucolor, color engine, tonal elevation, material design 3, material you utilities, color intensity +synonyms: colors less vibrant after update, new engine washed out colors, vibrant variant weaker than before, color strength +repo_commit: f8760cb02c406fb74969a7b6003ffd583ad71a8d + +# ISS-790 — [Color] Check Vibrant color pallette + +State: CLOSED, stateReason COMPLETED · opened 2026-09-20 by ladybug-me · closed 2026-09-20. + +## Problem (original report, condensed) + +Filed by the maintainer as a check on the vibrant palette (the issue body is empty; the title is the report): does the `vibrant` color variant still look as strong as before the color-engine change? + +(Context from the linked threads: this grew out of #763, where a user noticed the `vibrant` variant looked less "strong" on the new color engine and asked whether the old engine could be kept; the maintainer's replies here are the answer.) + +## Resolution + +Participants' positions (paraphrased): the maintainers' and collaborators' points are summarized in the curated notes and tags on this page; the original wording lives at the source URL below. +## Thread summary (paraphrased) + +2 comments by ladybug-me between 2026-09-20 and 2026-09-20. Decisions and scope notes are reflected in the curated notes above; the full history lives at https://github.com/ladybug-me/caelestia-kde/issues/790. diff --git a/plugins/caelestia-assistant/assistant/data/corpus/ISS-791.md b/plugins/caelestia-assistant/assistant/data/corpus/ISS-791.md new file mode 100755 index 0000000..51fdd72 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/data/corpus/ISS-791.md @@ -0,0 +1,25 @@ +id: ISS-791 +title: Add color intensity slider +source: issue #791 (CLOSED, stateReason COMPLETED) https://github.com/ladybug-me/caelestia-kde/issues/791 +tags: color intensity, slider, feature request, matugen, advanced colors, vibrant +synonyms: intensity of colors control, boost color intensity slider, adjust how strong colors are +repo_commit: f8760cb02c406fb74969a7b6003ffd583ad71a8d + +# ISS-791 — Add color intensity slider + +State: CLOSED, stateReason COMPLETED · opened 2026-09-20 by ladybug-me · closed 2026-09-21 (implemented). + +## Proposal (original, condensed) + +Feature request (label: feature), filed by the maintainer: + +> Feature request as per #790 & conversation in #763 . + +(A control for how intense/saturated the generated colors are — the ask behind the "vibrant palette looks weaker on the new matugen engine" discussion in those threads.) + +## Resolution + +Participants' positions (paraphrased): the maintainers' and collaborators' points are summarized in the curated notes and tags on this page; the original wording lives at the source URL below. +## Thread summary (paraphrased) + +1 comment by 0xSolanaceae between 2026-09-21 and 2026-09-21. Decisions and scope notes are reflected in the curated notes above; the full history lives at https://github.com/ladybug-me/caelestia-kde/issues/791. diff --git a/plugins/caelestia-assistant/assistant/data/corpus/ISS-792.md b/plugins/caelestia-assistant/assistant/data/corpus/ISS-792.md new file mode 100755 index 0000000..c66e15b --- /dev/null +++ b/plugins/caelestia-assistant/assistant/data/corpus/ISS-792.md @@ -0,0 +1,26 @@ +id: ISS-792 +title: Crashes +source: issue #792 (CLOSED, stateReason COMPLETED) https://github.com/ladybug-me/caelestia-kde/issues/792 +tags: crash, fixed in dev, next release, qslog, report.txt, vague report +synonyms: caelestia crashes, shell keeps crashing, already fixed on dev branch +repo_commit: f8760cb02c406fb74969a7b6003ffd583ad71a8d + +# ISS-792 — Crashes + +State: CLOSED, stateReason COMPLETED · opened 2026-09-21 by tahaub · closed 2026-09-21. + +## Problem (original report, condensed) + +> I had crashes, I don't have that much information, I'm new into this and I don't now waht to say... +> +> [log.qslog.log](https://github.com/user-attachments/files/32479387/log.qslog.log) +> [report.txt](https://github.com/user-attachments/files/32479388/report.txt) + +(The report is intentionally vague — no pasted error text, only the two attached files. The maintainer's reply below did not quote any specific line from them either, so this doc deliberately records no signature beyond "crashes".) + +## Resolution + +Participants' positions (paraphrased): the maintainers' and collaborators' points are summarized in the curated notes and tags on this page; the original wording lives at the source URL below. +## Thread summary (paraphrased) + +1 comment by ladybug-me between 2026-09-21 and 2026-09-21. Decisions and scope notes are reflected in the curated notes above; the full history lives at https://github.com/ladybug-me/caelestia-kde/issues/792. diff --git a/plugins/caelestia-assistant/assistant/data/corpus/ISS-802.md b/plugins/caelestia-assistant/assistant/data/corpus/ISS-802.md new file mode 100755 index 0000000..0d285ab --- /dev/null +++ b/plugins/caelestia-assistant/assistant/data/corpus/ISS-802.md @@ -0,0 +1,26 @@ +id: ISS-802 +title: ai model integration +source: issue #802 (CLOSED) https://github.com/ladybug-me/caelestia-kde/issues/802 +tags: ai assistant, narrow ai, scope, troubleshooting, cleaning, issue reporting, training data +synonyms: what can the assistant do, narrow assistant, assistant limitations + +# ISS-802 — ai model integration + +State: CLOSED · opened 2026-09-22 by 0x0nYx · closed 2026-09-22 (redirected to #120 by the maintainer). + +This thread is CLOSED: the outcome is the maintainer's redirect to #120, where the contributor asked to continue ("mention me in a comment in the #120"). It stays in the corpus because it defines what the on-device assistant itself may claim to do — no more, no less. + +## Proposal (original, condensed) + +i m quite experienced in building llms and ai models, since for many users the model will be resource heavy, it has to be narrow ai, not like an LLM but still like that that means it will be narrow ai not like an LLM but still like that that means it will be quite good at solving easy to intermediate prblms on linux shell, any kde specific prblms, folder organisations, cleaning, issue reportings to repo directly etc. + +already told why it will be useful + +## Scope + +Maintainer (ladybug-me): "Why don't you create & train a small model for #120 ?" — i.e. any assistant work is scoped against the #120 feature thread. +Corpus note (curated from this thread): the on-device assistant claims only narrow troubleshooting help (docs + resolved issues), folder-size reporting guidance, and issue drafting. It does not claim general LLM abilities and does not act on its own. + +## Thread summary (paraphrased) + +3 comments by 0x0nYx, ladybug-me between 2026-09-22 and 2026-09-22. Decisions and scope notes are reflected in the curated notes above; the full history lives at https://github.com/ladybug-me/caelestia-kde/issues/802. diff --git a/plugins/caelestia-assistant/assistant/data/corpus/ISS-805.md b/plugins/caelestia-assistant/assistant/data/corpus/ISS-805.md new file mode 100755 index 0000000..2abd51e --- /dev/null +++ b/plugins/caelestia-assistant/assistant/data/corpus/ISS-805.md @@ -0,0 +1,50 @@ +id: ISS-805 +title: Lock screen fallback issue +source: issue #805 (CLOSED, stateReason COMPLETED) https://github.com/ladybug-me/caelestia-kde/issues/805 +tags: lock screen, fallback, built-in lock screen, kscreenlocker, kreadconfig6, ShellPackage, caelestia.desktop, QML2_IMPORT_PATH, environment variables, plasma-workspace env, sddm, CachyOS, v2.4.3 +synonyms: lock screen falls back to the built-in one, lock screen not caelestia after update, caelestia services module not found in kscreenlocker journal, kscreenlocker_greet testing works but real lock does not +repo_commit: f8760cb02c406fb74969a7b6003ffd583ad71a8d + +# ISS-805 — Lock screen fallback issue + +State: CLOSED, stateReason COMPLETED · opened 2026-09-22 by Refiichi · closed 2026-09-22 (fix confirmed by the reporter). + +Capture note: this issue was created and resolved after the corpus was +first assembled — it was still OPEN when the tracker was next snapshotted, +and the maintainer closed it as completed shortly after, before this +corpus doc was written. The state above is the state at capture time. + +## Problem (original report, condensed) + +> I just recently updated Caelestia KDE to the recent version v2.4.3 and I have encountered an issue where the lock screen falls back to the built-in lock screen despite the command `kreadconfig6 --file plasmashellrc --group "Shell" --key "ShellPackage"` outputs correctly as "caelestia.desktop" and the `/usr/lib/kscreenlocker_greet --testing` actually shows the caelestia lock screen. +> +> I checked errors related to kscreenlocker in journalctl and found that the module 'Caelestia.Services" is not found. +> +> Aside from that, I couldn't see the caelestia SDDM theme, not sure if I did something wrong even though the installer's full log says its OK + +Troubleshooting the reporter had already done (condensed): re-setting `ShellPackage` via `kwriteconfig6` (reads back correctly), reinstalling v2.4.3 (was working on v2.4.2), `kscreenlocker_greet --testing` works, reboot/relogin does not help. Caelestia version v2.4.3, distro CachyOS. + +## Resolution + +Participants' positions (paraphrased): the maintainers' and collaborators' points are summarized in the curated notes and tags on this page; the original wording lives at the source URL below. +## Thread summary (paraphrased) + +3 comments by Refiichi, ladybug-me between 2026-09-22 and 2026-09-22. Decisions and scope notes are reflected in the curated notes above; the full history lives at https://github.com/ladybug-me/caelestia-kde/issues/805. +## Landed in dev + +Both halves of the maintainer's fix landed in dev via PR #806 (the upstream +2.5.0 port, merged 2026-09-22T16:43:44Z as f2f95ac2) — verbatim subjects from +`git log f8760cb0..f2f95ac2 --format='%h %s'` (verifiable offline in any dev +checkout): + +- `33e4541f` fix: ensure caelestia env variables when systemd does not start the session +- `50278414` fix: sddm theme did not install when plasmalogin binary present too + +Concretely, `scripts/08-build-shell.sh` now also writes the Plasma session +environment to `~/.config/plasma-workspace/env/caelestia.sh` (sourced by KDE +Plasma on session startup for KWin, `kscreenlocker_greet`, and graphical +applications), and TROUBLESHOOTING.md §3.2 documents both locations; the +login-screen detection table (§7.6) now tells Plasma Login from SDDM by +whether `plasmalogin.service` / `sddm.service` is active/enabled rather than +by the `command -v` probe. The maintainer's startscript snippet above remains +byte-verbatim. diff --git a/plugins/caelestia-assistant/assistant/data/index/bm25.json b/plugins/caelestia-assistant/assistant/data/index/bm25.json new file mode 100755 index 0000000..d74f8c9 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/data/index/bm25.json @@ -0,0 +1 @@ +{"avgdl":306.390243902439,"df":{"006":1,"00a":2,"01":2,"014":1,"02":2,"02a":1,"03":2,"04":3,"05":2,"06":4,"07":2,"08":11,"09":19,"0x0nyx":3,"0xsolanaceae":8,"10":6,"100":1,"101418":1,"11":5,"12":3,"120":2,"127":2,"13":3,"139":1,"14":5,"15":1,"16":1,"16px":1,"17":2,"173":1,"1793d1":1,"18":4,"19":2,"1d99f3":1,"20":7,"2026":26,"21":4,"22":5,"22t16":2,"22t19":1,"23":1,"24":2,"25":1,"25t17":1,"26":2,"26heij":1,"26px":1,"28":2,"29":2,"2fcaelestia":1,"30":1,"30z":1,"32479387":1,"32479388":1,"32gb":1,"333":1,"33e4541f":1,"34":2,"38b24e7f":1,"402":1,"4060":1,"409":1,"416":1,"418":1,"41z":1,"42px":1,"43":1,"43db":1,"44":1,"44z":1,"461":1,"462":1,"4790":1,"496":1,"50":1,"500mbs":1,"50278414":1,"51a2da":1,"528":1,"55":1,"565":1,"586":1,"59":1,"5fc7d98d":1,"5g":1,"60":1,"60hz":1,"616":1,"629":1,"630":1,"633":1,"634":1,"64":2,"641":1,"70ee7da":1,"70ee7da115fde9012e28e393c73d274f55bd2dd7":1,"738":1,"744":1,"75":1,"763":3,"765":1,"773":1,"774":1,"788":1,"790":2,"791":1,"792":1,"80":1,"802":1,"805":2,"806":1,"808":1,"82":1,"872b":1,"8c0ac23a44fd":1,"95":1,"9bd0cc":1,"abi":1,"abilities":1,"abort":1,"aborting":1,"aborts":1,"above":25,"aboverule":1,"absent":1,"accelerated":1,"acceleration":1,"accent":1,"access":2,"according":1,"account":2,"across":4,"act":1,"action":3,"activated":1,"activation":1,"active":8,"activeid":1,"activeoutputname":1,"activewindow":1,"acts":1,"actual":1,"actually":3,"adapting":1,"add":2,"added":2,"address":1,"addresses":1,"adds":1,"adjacent":1,"adjust":1,"advanced":2,"af":1,"affected":1,"affects":1,"afther":1,"against":4,"agentic":1,"ai":3,"air":1,"album":1,"algorithm":1,"align":1,"allowing":1,"allows":1,"alongside":1,"already":11,"alt":3,"alternating":1,"always":2,"ambience":1,"ambient":1,"ambilight":1,"amd":1,"animated":1,"animations":1,"another":7,"ansi":1,"answer":2,"answers":1,"anubhavxp":1,"anymore":1,"anything":3,"anyway":1,"apart":1,"apertus":1,"api":4,"app":6,"app2unit":1,"appear":3,"appearance":1,"appearing":2,"appears":4,"appid":1,"applet":1,"applicable":1,"application":1,"applications":4,"applied":3,"applies":3,"apply":7,"applying":2,"approach":1,"approachable":1,"appropriate":1,"apps":4,"apt":1,"apu":1,"arch":6,"architectural":1,"architecture":5,"archive":2,"archlinux":2,"arg":3,"aroaxinping":1,"around":2,"array":1,"arriving":1,"art":1,"artifacts":2,"aside":1,"ask":1,"asked":3,"asking":1,"asks":1,"aslo":1,"assembled":1,"asset":3,"assets":3,"assistant":2,"associated":1,"assumption":1,"atim":1,"attach":1,"attached":2,"attachment":1,"attachments":2,"attempt":1,"attempted":1,"aubio":1,"audio":3,"aur":6,"authentication":1,"authenticator":1,"author":1,"auto":5,"automatic":1,"automatically":5,"autostart":4,"availability":1,"available":2,"avatar":2,"averaged":1,"averages":1,"avoid":1,"avoids":1,"back":14,"backed":1,"backend":3,"background":4,"backgrounds":1,"backlog":1,"backlogged":1,"backup":1,"backups":2,"backward":1,"bad":1,"badge":4,"badges":1,"bali10050":1,"bar":6,"barconfig":1,"bardock":1,"bare":2,"base":3,"based":4,"bash":12,"bashrc":1,"basically":2,"bc":1,"beginning":1,"behave":1,"behavior":1,"behaviour":1,"behind":6,"belongs":1,"below":22,"beside":1,"between":25,"beyond":1,"bgmargin":1,"bgradius":1,"bin":5,"binary":4,"binding":2,"bindings":3,"binds":1,"bitbucket":1,"blank":1,"bleed":1,"bleeding":3,"blinker":1,"block":1,"blocked":1,"blocking":2,"bluetooth":1,"bluez":1,"blur":2,"blurred":1,"blurring":1,"body":1,"bool":2,"boolean":1,"boost":1,"boot":1,"bottlenecks":1,"bottom":1,"bound":1,"box":1,"branch":6,"breaks":2,"breeze":4,"bridge":2,"briefly":2,"brightness":1,"brings":2,"broken":4,"browse":1,"browser":1,"browsers":1,"brycensranch":1,"bt":1,"bug":7,"bugfixes":1,"build":9,"buildenv":1,"building":2,"builds":5,"built":5,"bundle":3,"bundled":1,"bundling":1,"bus":2,"busy":1,"button":1,"byte":1,"cache":8,"cachos":1,"cachy":1,"cachyos":9,"caelestia":40,"caelestiafetch":1,"caelestiafetchcard":1,"call":1,"calls":4,"camera":2,"cannot":4,"canonical":1,"cant":1,"capabilities":1,"capture":3,"captured":1,"card":2,"cardn":1,"cardradius":1,"cargo":1,"carries":2,"carry":1,"carrying":1,"case":1,"cat":4,"categories":1,"categorized":1,"cause":9,"causes":2,"causing":1,"ccache":3,"celestelove":2,"center":2,"centered":2,"central":2,"certain":1,"cgtop":1,"change":6,"changed":3,"changes":7,"changing":1,"chart":1,"cheatsheet":1,"check":9,"checked":2,"checker":1,"checkout":5,"checkouts":1,"checks":4,"checksum":1,"checksums":1,"choice":1,"choose":1,"choosing":1,"chose":1,"chosen":1,"chromium":1,"ci":1,"claim":2,"claims":1,"class":3,"classify":1,"clean":4,"cleaned":1,"cleaning":1,"cleans":1,"cleanup":1,"cli":6,"clicking":1,"client":1,"clients":1,"clip":2,"clipboard":2,"clipped":1,"clock":1,"clockwidget":1,"clone":3,"cloned":1,"close":1,"closed":25,"closes":1,"closewindow":1,"clue":1,"cmake":2,"cmakelists":2,"code":2,"codes":1,"codex":1,"collaborator":1,"collaborators":22,"collision":2,"collisions":1,"color":9,"colors":10,"colorscheme":2,"colour":1,"column":1,"colur":1,"com":27,"combinations":1,"combos":1,"come":3,"command":7,"commands":4,"comment":7,"comments":19,"commit":1,"commits":2,"common":1,"communicates":2,"compact":1,"compatibility":1,"compilation":1,"compile":2,"compiled":1,"compiler":1,"compiles":2,"completed":22,"completes":1,"component":3,"components":4,"compositing":1,"compositor":1,"compositors":1,"concentric":1,"concerned":1,"concretely":1,"condensed":26,"condition":2,"conf":4,"config":17,"configobject":1,"configuration":5,"configurations":1,"configure":4,"configured":4,"configures":1,"configuring":1,"confirm":2,"confirmed":1,"conflict":3,"conflicts":4,"confusing":1,"connecting":1,"consent":1,"const":2,"constants":2,"container":1,"containing":2,"contains":2,"content":3,"contents":2,"context":3,"continue":1,"continues":3,"continuously":1,"contributor":2,"control":2,"controlled":1,"controls":2,"conversation":1,"convert":1,"converts":1,"coordinator":1,"copied":2,"copr":3,"copy":3,"core":2,"corner":1,"corpus":4,"correct":3,"correctly":1,"correspond":1,"corrupted":3,"cosmetic":1,"couldn":1,"count":5,"covered":1,"covers":1,"cp":2,"cpp":3,"cpu":2,"crash":7,"crashed":2,"crashes":4,"crashing":2,"create":2,"created":2,"creates":2,"createworkspace":1,"credits":1,"critical":2,"crlf":1,"cross":1,"ctrl":2,"curated":24,"curl":3,"current":5,"currently":4,"custom":2,"customization":1,"customizations":1,"customize":1,"customshortcut":2,"cutting":1,"cuz":1,"cvds7sfgajh3wihln72p8wzuoqt2k2f71zocgl":1,"cxx":1,"daemon":2,"damaged":1,"dark":2,"darker":1,"darkly":3,"dashboard":1,"data":5,"database":1,"date":3,"day":1,"db":1,"dbus":1,"dcmake":1,"dead":1,"debian":2,"debug":3,"debugging":1,"decide":1,"decided":1,"decision":1,"decisions":23,"declarative":2,"declared":2,"declares":1,"decoration":1,"decorations":1,"decoupled":1,"default":3,"defaultenv":1,"defaults":2,"defined":2,"defines":2,"defining":1,"degraded":1,"dekstop":1,"delete":3,"deleted":3,"deletes":3,"deleting":1,"deliberately":1,"dependencies":3,"dependency":3,"depending":1,"deploy":3,"deployed":1,"deployment":2,"deploys":1,"derive":1,"derives":1,"describe":1,"description":1,"design":3,"desktop":13,"desktopid":1,"desktops":3,"despite":1,"destinations":1,"desync":1,"detail":1,"detailed":1,"details":1,"detected":2,"detection":3,"detects":1,"determine":1,"dev":12,"devel":2,"developer":2,"device":3,"diagnostic":2,"diagnostics":1,"dialog":3,"dialogs":1,"didn":2,"diff":1,"different":4,"differently":1,"difficult":1,"diffs":1,"dimmed":1,"dir":7,"direct":1,"direction":3,"directly":6,"directory":6,"dirn":1,"dirs":1,"disable":4,"disabled":1,"disables":2,"disagree":1,"disappear":1,"disappeared":1,"disappears":1,"discarding":1,"discards":1,"disclosed":1,"disclosure":1,"discord":3,"discrete":1,"discussed":1,"discussion":2,"disk":4,"display":2,"displays":2,"distinguish":1,"distro":5,"distros":2,"div":1,"dnf":4,"doc":2,"dock":4,"docs":3,"doctor":1,"document":3,"documentation":2,"documents":2,"dodge":1,"doesn":4,"doesnt":2,"dolphin":1,"don":4,"done":3,"dont":1,"dos2unix":1,"dot":2,"dotfiles":1,"dots":6,"double":1,"download":2,"downloaded":3,"downloads":2,"dr":1,"drafting":1,"drive":1,"driven":1,"drives":2,"drm":1,"dual":1,"due":1,"duplicated":1,"dynamic":3,"dynamically":1,"e95420":1,"earlier":1,"early":1,"easiest":1,"easily":1,"easy":1,"eating":1,"edge":2,"editing":2,"edits":2,"effect":4,"effects":1,"either":3,"elapsed":1,"electron":1,"element":1,"elevation":1,"eliminating":1,"else":1,"elsewhere":1,"emoji":1,"empty":5,"enable":2,"enabled":4,"enables":4,"enabling":1,"encountered":1,"end":2,"ending":1,"endings":1,"endpoint":1,"engine":4,"enough":1,"ensure":3,"enter":1,"entirely":3,"entries":4,"entry":2,"entrylist":1,"env":4,"environment":5,"environments":1,"err":4,"error":10,"errornointernet":1,"errors":4,"escape":2,"etc":6,"even":2,"events":1,"every":7,"everything":1,"everytime":2,"evolution":1,"exact":1,"exactly":3,"examples":1,"executing":1,"exist":4,"existed":1,"existing":4,"exists":1,"exit":4,"exited":1,"exits":1,"expandable":1,"expected":4,"expects":1,"experienced":1,"explicit":1,"explore":1,"export":3,"exposed":2,"exposes":2,"external":1,"extra":1,"extracting":1,"extracts":1,"f2f95ac2":1,"f8760cb0":1,"face":2,"fail":5,"failed":7,"fails":9,"failure":2,"failures":2,"fake":1,"fallback":4,"fallen":1,"falling":1,"falls":7,"false":4,"family":1,"far":1,"fastblur":1,"fatal":3,"favor":1,"fdd9":1,"fdx":1,"feat":1,"feature":6,"features":4,"fedora":7,"fedoraproject":1,"feeds":1,"feel":1,"feels":1,"fefedu973":1,"fenced":1,"fetch":3,"fetched":2,"fetches":1,"ffmpeg":1,"fields":1,"file":12,"filed":7,"files":11,"finally":1,"find":1,"fine":2,"fingerprint":1,"fingerprints":2,"finish":1,"first":7,"fix":10,"fixed":2,"fixes":3,"fixing":1,"flash":1,"flashes":2,"flashing":1,"flawlessly":1,"flickers":1,"flip":1,"flips":2,"floating":1,"flow":1,"focus":1,"focused":3,"focuses":1,"focuswindow":1,"folder":3,"follow":2,"followed":1,"following":2,"fonts":1,"forapp":1,"force":1,"forced":3,"forces":1,"forecast":1,"fork":1,"format":1,"formatted":2,"found":4,"four":1,"fr":1,"fractional":1,"francisco":2,"free":1,"freedesktop":1,"freeze":2,"freezes":2,"fresh":1,"friendly":1,"front":1,"frontend":1,"frontier":1,"frosted":1,"fssl":2,"full":26,"fullscreen":3,"fullscreened":1,"fully":1,"functionality":1,"fusion":1,"game":2,"games":1,"gamescope":1,"gapped":1,"garbage":1,"garbled":1,"garuda":2,"gave":1,"gcc":1,"geforce":1,"general":3,"generated":2,"generates":2,"generic":1,"gesture":1,"gestures":1,"get":2,"getting":1,"git":7,"github":28,"githubusercontent":2,"gitmodules":1,"give":1,"given":1,"gives":3,"glass":1,"global":3,"globalshortcut":3,"globalshortcutdispatcher":2,"glow":1,"go":2,"going":1,"gone":2,"gonna":1,"good":1,"google":1,"governing":1,"gpasswd":1,"gpl":1,"gpu":6,"gpus":1,"grace":1,"gracefully":2,"grants":1,"graphical":2,"graphics":1,"greater":1,"greet":4,"greeter":4,"greeters":1,"greeting":1,"greetingpill":1,"grep":3,"greps":1,"grew":1,"group":7,"groups":3,"gtk":1,"gui":1,"guidance":1,"guide":1,"guidelines":1,"guides":1,"gunuqnte3ey14fx":1,"h264":1,"haidir":1,"half":2,"halves":1,"hand":3,"handed":2,"handle":1,"handled":2,"handles":4,"handling":2,"handover":1,"hangs":1,"happening":1,"happens":2,"hard":2,"hardware":1,"harmless":1,"hash":1,"haven":1,"head":3,"headers":1,"heals":1,"heavily":1,"heavy":1,"height":2,"helium":1,"help":3,"helper":1,"helpers":1,"hence":1,"herself":1,"hgfs":1,"hhmmss":1,"hiding":1,"high":1,"higher":2,"historical":1,"history":24,"holds":2,"home":9,"hood":1,"hook":1,"hops":1,"horz":1,"hotkey":1,"hour":1,"hovering":1,"hpp":2,"href":1,"http":1,"https":28,"hub":1,"hybrid":1,"hyprctl":2,"hyprland":3,"i7":1,"icon":4,"icons":3,"icture":1,"id":3,"identical":2,"identify":1,"idle":1,"ignore":1,"ignored":1,"igpu":1,"ik":1,"ill":1,"im":1,"image":8,"images":1,"img":1,"immediately":4,"implement":1,"implementation":2,"implemented":2,"import":4,"important":2,"imports":1,"inactive":1,"include":2,"including":2,"increase":2,"increased":1,"indentifying":1,"independent":2,"index":3,"indexed":1,"indexes":1,"indicators":1,"individual":1,"individually":1,"inert":1,"info":4,"information":4,"init":2,"initially":1,"inject":1,"injection":3,"injects":1,"inline":1,"inner":1,"input":4,"inside":3,"inspect":1,"inspects":1,"install":14,"installation":9,"installed":11,"installer":14,"installing":1,"instance":1,"instead":6,"instructions":1,"instructs":1,"int":2,"integer":1,"integrated":1,"integration":5,"intel":1,"intended":1,"intense":1,"intensity":2,"intent":1,"intentionally":1,"interact":1,"interacting":1,"interactive":1,"interface":3,"interfaces":2,"interim":1,"intermediate":1,"internals":1,"internet":1,"interpret":1,"interrupted":1,"intituve":1,"introducing":1,"introspect":1,"introspectable":1,"invited":1,"invokables":1,"involved":1,"involving":1,"io":1,"ipc":1,"irrelevant":1,"isn":2,"iss":26,"issue":18,"issues":34,"item":1,"join":1,"journal":1,"journalctl":3,"js":1,"json":7,"kbuildsycoca6":2,"kde":38,"kdecoration2":1,"kdeglobals":3,"keep":3,"keeps":7,"kept":3,"kernel":1,"key":9,"keybind":1,"keybinds":4,"keybindsdefaults":1,"keybindsmodel":2,"keyboard":4,"keyd":1,"keys":3,"keystrokes":1,"kf6":1,"kf6windowsystem":1,"kglobalaccel":5,"kglobalacceld":1,"killed":2,"kmixrc":1,"kmy":1,"know":1,"known":1,"knsv":1,"konsave":1,"konsole":1,"kpackage":1,"kpackagestructure":1,"kpackagetool6":2,"kpipewire":1,"kreadconfig6":4,"krohnkite":2,"krohnkiteenabled":1,"kscreen":1,"kscreenlocker":4,"kscreenlockerrc":3,"kservice":1,"ktypedetectscript":1,"kwin":10,"kwinactivewindowbridge":2,"kwindowsystem":1,"kwinrc":3,"kwinrulesrc":1,"kwinworkspacestate":1,"kwriteconfig6":6,"kyedae":5,"la":3,"label":6,"labelcolor":1,"labeled":2,"ladybug":27,"lagging":1,"landed":3,"lands":1,"landscape":1,"language":2,"last":6,"later":4,"latest":3,"launch":1,"launched":2,"launcher":2,"launcherentry":1,"launches":1,"launching":1,"layer":1,"layout":2,"layouts":1,"ldd":1,"lead":1,"leak":2,"leave":2,"leaves":2,"left":6,"leftover":1,"legacy":3,"legend":1,"leloubil":1,"lens":1,"less":3,"level":2,"lib":10,"libcava":2,"libkwin":1,"libpam":1,"libpipewire":1,"libplasma":1,"libpulse":1,"libqalculate":1,"libraries":2,"library":2,"libs":1,"license":1,"light":4,"like":8,"likely":2,"limitations":1,"line":4,"lines":2,"link":1,"linked":2,"linux":6,"list":7,"listed":1,"listened":1,"lists":5,"live":7,"livepreviews":1,"lives":25,"ll":3,"llm":1,"llms":1,"lm":1,"load":4,"loaded":5,"loading":3,"loads":5,"loadscript":1,"local":11,"locally":1,"located":1,"locations":3,"lock":5,"lockbg":1,"locked":1,"locking":1,"locks":2,"lockscreen":2,"lockscreenui":2,"log":12,"logged":3,"logic":2,"login":8,"logo":2,"logocolor":1,"logout":2,"logs":4,"long":1,"longer":3,"look":4,"lookandfeeltool":1,"looked":1,"looking":1,"looks":2,"loop":1,"loops":1,"lost":1,"lot":1,"ls":3,"m3":1,"machine":1,"main":5,"maintainer":11,"maintainers":22,"maintains":1,"maintenance":1,"make":4,"makepkg":3,"makes":1,"manage":2,"management":2,"manager":6,"managers":1,"manages":4,"manifest":1,"manual":4,"manually":6,"many":3,"map":1,"mapped":1,"markdown":1,"markdownlint":1,"marker":1,"masked":1,"match":3,"matches":3,"matching":1,"material":4,"materialyou":1,"materialyoucolor":1,"matugen":6,"maximized":1,"maximizes":1,"maximizewindow":1,"maximum":1,"may":8,"mayonas3":1,"md":3,"md034":1,"meaning":1,"meaningless":1,"means":5,"mechanisms":1,"media":2,"mediacard":1,"medium":1,"membership":1,"memory":2,"mention":1,"menu":3,"merged":4,"merges":1,"message":2,"meta":3,"metadata":3,"meters":1,"methods":1,"mid":1,"might":1,"minimal":1,"minimizes":1,"minimizewindow":1,"minute":1,"mirror":2,"mirrors":1,"misc":1,"mismatch":3,"misses":1,"missing":9,"mitsiku":1,"mkdir":1,"mnt":1,"mocha":1,"mock":2,"mode":3,"model":2,"modeldata":1,"models":1,"modern":1,"modes":1,"modified":1,"modify":1,"module":4,"modules":3,"moment":1,"monitor":4,"monitors":2,"monochrome":1,"months":1,"moon":1,"mostly":1,"mounted":2,"move":1,"moved":2,"moves":1,"mp4":1,"mpris":1,"much":3,"multi":3,"multiple":1,"name":3,"named":1,"names":4,"narrow":2,"native":6,"natively":1,"natural":1,"need":3,"needed":4,"needs":3,"neither":1,"nested":1,"network":4,"never":6,"new":10,"newer":1,"newperc":1,"next":10,"nextdesktop":1,"nexus":8,"nfi4jxcozai26mlgx2jeashmrd1pis09clm":1,"night":1,"nl":1,"noconfirm":1,"nodotanddotdot":1,"noincremental":2,"non":5,"none":3,"nopasswd":1,"normal":3,"normalization":1,"normally":2,"note":9,"notes":25,"nothing":6,"noticed":1,"notifdock":1,"notification":4,"notifications":1,"null":3,"number":3,"numbered":1,"numbers":2,"nvidia":3,"ofc":1,"offline":3,"offset":2,"ok":2,"old":5,"older":4,"ollama":1,"one":11,"onto":2,"opacity":1,"opacityinactive":1,"opacityinactiverule":1,"opacitymask":1,"open":10,"opencv":1,"opened":24,"opening":1,"opens":1,"optimized":1,"optional":3,"options":1,"order":1,"org":8,"organisations":1,"organizes":1,"original":28,"os":1,"osd":1,"others":1,"otherwise":1,"ours":1,"outcome":1,"outer":2,"outlines":1,"outlived":1,"output":6,"outputname":1,"outputs":1,"outside":1,"overall":1,"overhead":1,"overridden":1,"override":2,"overrides":2,"overview":5,"overwrites":1,"overwrote":1,"owns":1,"package":10,"packaged":2,"packages":7,"pacman":5,"padding":1,"page":23,"pages":1,"pairing":1,"pairs":1,"palette":5,"palettes":1,"pallette":1,"pam":2,"panel":2,"panels":2,"paraphrased":24,"parse":1,"parser":1,"parses":1,"part":1,"partial":3,"participants":22,"parts":1,"party":1,"paru":1,"password":1,"passwordpill":1,"past":2,"pasted":1,"patch":3,"patches":3,"path":8,"paths":4,"pause":1,"pc":1,"pegs":1,"pending":2,"pentagon":1,"per":7,"percent":2,"percentage":1,"performance":1,"performed":1,"permanently":2,"persist":2,"persistence":2,"persists":1,"pgrep":1,"physically":1,"pick":1,"picker":1,"picks":1,"picture":4,"pictures":1,"pid":1,"pidof":1,"pieces":1,"pill":1,"pills":1,"pinned":2,"pip":1,"pipeline":2,"pipewire":3,"pkg":1,"pkgbuild":1,"place":1,"placement":1,"placementrule":1,"places":1,"plain":1,"planck4":1,"plasma":13,"plasmaapplicationwallpaper":1,"plasmalogin":2,"plasmanotifyrc":1,"plasmarc":1,"plasmashell":3,"plasmashellrc":4,"plasmawindows":1,"play":1,"playback":1,"player":2,"plugin":9,"plugins":4,"plus":3,"png":1,"point":1,"pointed":1,"pointing":1,"points":23,"policy":1,"poll":1,"pop":1,"popup":1,"popups":1,"port":4,"portal":2,"portals":1,"portrait":1,"position":1,"positions":22,"positives":1,"possible":1,"post":1,"posthook":1,"powerdevilrc":1,"powered":1,"pp":1,"pr":7,"pragma":1,"prblms":1,"prebuilt":4,"predates":1,"predefined":1,"preferences":1,"prefers":1,"prefix":1,"prematurely":1,"prereqs":1,"prerequisites":1,"present":4,"preserved":1,"preventing":1,"previews":3,"previous":1,"previousdesktop":1,"previously":1,"primarily":1,"primary":1,"print":1,"prints":2,"prioritizes":1,"priority":2,"private":1,"privileged":1,"probablyjassin":1,"probe":1,"problem":25,"proceed":1,"process":3,"processes":1,"producing":1,"profile":2,"profileavatar":1,"profiles":1,"progress":2,"project":2,"promise":1,"prompt":3,"prompting":1,"prone":1,"properly":1,"properties":1,"property":2,"proposal":4,"protocol":2,"protocols":1,"provided":1,"provides":3,"providing":1,"proxies":1,"proxy":2,"publish":1,"published":2,"publishes":1,"pull":2,"pulled":1,"pulseaudio":1,"pure":1,"purpose":1,"pushing":1,"put":1,"py":2,"python":3,"python3":1,"qabstractlistmodel":1,"qdbus6":5,"qdir":1,"qfile":1,"qlocalsocket":1,"qml":10,"qml2":4,"qml6":1,"qmldir":1,"qprocess":1,"qreal":1,"qs":3,"qslog":1,"qstring":2,"qstringlist":1,"qt":4,"qt6":4,"qtdeclarative":1,"qtquick":1,"qtshadertools":1,"qtwayland":1,"quarantine":1,"question":1,"questions":1,"quick":3,"quickly":1,"quickshell":12,"quite":1,"quote":1,"quoted":2,"qvariantlist":1,"qvariantmap":1,"r0xx133":1,"radii":1,"radius":1,"raises":1,"raisewindow":1,"ram":2,"ran":3,"random":1,"randomly":2,"ranking":1,"ranks":1,"rarely":1,"rate":1,"rather":4,"raw":2,"rc":1,"re":11,"reach":1,"read":8,"readall":1,"reader":2,"readgenericusage":1,"readgputemperature":1,"readme":1,"reads":2,"real":4,"reason":1,"rebind":2,"reboot":5,"rebooting":1,"rebuild":2,"rebuilds":2,"recent":1,"recently":1,"recognition":1,"recognized":1,"recommended":1,"reconciliation":1,"reconfigure":4,"record":2,"recorded":1,"recorder":4,"recording":4,"records":3,"recovery":2,"recursive":2,"red":2,"redirect":1,"redirected":1,"redo":1,"redone":1,"reference":2,"refiichi":1,"reflected":23,"reflector":1,"refresh":3,"refreshes":1,"refreshwindows":1,"refuses":1,"region":1,"regions":1,"register":1,"registered":1,"registering":1,"registers":3,"registration":1,"regular":1,"reinstall":1,"reinstalling":1,"reinstalls":1,"rejected":1,"related":1,"relay":1,"release":4,"released":1,"releases":1,"reliability":1,"reliable":1,"relied":1,"relinked":1,"reload":3,"reloaded":1,"relogin":1,"relying":1,"remain":3,"remaining":1,"remains":2,"remote":2,"removal":2,"remove":6,"removed":3,"removes":4,"removeworkspace":1,"rendering":1,"reopened":1,"repaints":1,"repeating":1,"replace":1,"replaced":2,"replacement":1,"replaces":1,"replies":1,"reply":1,"repo":5,"report":22,"reporter":3,"reporting":2,"reportings":1,"reports":5,"repos":1,"repositories":1,"repository":4,"representing":1,"reproduce":1,"request":4,"requests":2,"required":3,"requirement":1,"requirements":1,"requires":3,"reran":1,"reset":6,"resets":4,"resides":1,"residue":1,"resolution":25,"resolutions":2,"resolved":2,"resolves":1,"resource":3,"resources":1,"resourcescard":1,"responsive":1,"rest":2,"restart":7,"restarts":2,"restoration":1,"restore":3,"restored":1,"restores":1,"restoring":2,"restricted":1,"retries":1,"retrieves":1,"retry":1,"returning":1,"rev":1,"reversal":1,"revert":4,"reverted":1,"reverting":1,"reverts":1,"revision":2,"rewrites":2,"rewriting":1,"rf":3,"rgba":1,"rhythm":1,"right":3,"ripped":1,"rm":6,"rn":1,"rns":1,"root":3,"roughly":2,"rounded":1,"routes":1,"routine":1,"routing":1,"rpc":1,"rpm":1,"rtx":1,"rule":3,"rules":2,"run":11,"running":12,"runs":7,"runtime":5,"ryzen":1,"safe":1,"safely":1,"safety":1,"saturated":1,"save":1,"saved":1,"saves":1,"saving":1,"say":1,"says":3,"scaled":1,"scaling":1,"scan":1,"schema":1,"scheme":7,"schemes":3,"scope":23,"scoped":1,"screen":14,"screencast":2,"screening":1,"screenlocker":1,"screenshare":2,"screenshot":5,"screenshots":3,"script":10,"scripting":1,"scripts":11,"sddm":2,"sdk":1,"sealed":1,"seamless":1,"seamlessly":1,"search":1,"searching":1,"second":2,"secondary":1,"seconds":2,"section":1,"sections":1,"sed":2,"see":10,"seem":2,"seems":2,"seen":1,"select":1,"selected":1,"selection":1,"selector":1,"selects":1,"self":1,"semicolon":1,"send":1,"sensor":1,"sensors":1,"sensorslib":1,"separate":2,"separated":1,"sequence":3,"sequences":2,"server":1,"service":7,"services":4,"session":9,"set":9,"setactiveoutputname":1,"setdesktop":1,"seted":1,"setfullscreen":1,"setmaximized":1,"sets":3,"setted":1,"setting":3,"settings":10,"settled":1,"setup":7,"setups":1,"setwindowdesktop":1,"setwindowproperty":1,"several":1,"severity":1,"sh":18,"sha256":1,"shader":1,"shadereffectsource":1,"shadertools":1,"shadow":1,"shapes":1,"share":7,"shared":3,"sharing":1,"shell":23,"shellpackage":4,"shellrc":1,"shells":2,"shields":1,"shift":2,"ship":1,"shipped":2,"shortcut":4,"shortcuts":5,"shortly":1,"show":5,"showbadges":1,"showing":3,"shows":9,"si":3,"side":3,"sidebar":1,"sigint":1,"sigkill":1,"signal":2,"signals":1,"signature":1,"sigsegv":1,"sigterm":1,"silently":4,"simplified":1,"simply":3,"since":3,"single":1,"singleton":3,"singletons":1,"sits":1,"sitting":1,"size":3,"skip":2,"skipped":2,"skips":1,"slider":2,"sliders":1,"slideshow":1,"slightly":1,"slow":2,"slower":1,"small":2,"smart":1,"snapshotted":1,"snippet":1,"socket":1,"sockets":1,"software":1,"solution":1,"solving":1,"something":6,"sometimes":2,"somewhere":1,"soramanew":1,"sorry":1,"source":29,"sourced":2,"sources":2,"sourcing":1,"space":1,"sparse":1,"spawned":1,"specific":5,"specified":1,"spectacle":3,"speed":1,"speeding":1,"spot":3,"spotify":1,"src":8,"srcset":1,"ssl":1,"stable":3,"stack":1,"stacked":1,"stacking":1,"stale":5,"standard":1,"standardizes":1,"star":1,"starship":1,"start":6,"started":1,"starts":1,"startscript":1,"startup":4,"stash":1,"stashes":1,"state":31,"statereason":22,"states":1,"static":1,"stats":1,"status":3,"stays":4,"stderr":3,"steal":1,"stealing":1,"steals":2,"steam":1,"step":8,"steps":2,"stick":1,"still":14,"stock":3,"stole":1,"stolen":3,"stop":1,"stopped":1,"stops":2,"store":1,"stored":1,"straight":1,"strange15":1,"stream":1,"strength":1,"string":2,"strips":1,"strong":2,"structure":1,"structured":1,"stuck":2,"stutters":2,"style":2,"subjects":1,"submodule":3,"submodules":2,"subobject":1,"subsystem":2,"succeeded":1,"success":1,"sudo":4,"sudoers":1,"sufficient":1,"suggestions":1,"sum":1,"summaries":1,"summarized":22,"summary":24,"sun":1,"super":2,"support":2,"sure":3,"surface":1,"svg":1,"swipe":2,"swipeoffset":1,"swiping":1,"switch":2,"switcher":2,"switches":2,"switchto":1,"sy":2,"symbols":1,"symptom":8,"symptoms":1,"sync":2,"syntax":1,"sys":1,"sysinfo":1,"system":18,"systemctl":4,"systemd":5,"systems":4,"syu":1,"tab":3,"table":1,"tag":1,"tags":22,"tahaub":1,"tail":1,"take":1,"takes":4,"tampered":1,"tarball":1,"taskbar":3,"tasks":1,"tato":2,"technique":1,"tell":2,"tells":1,"temp":1,"temperature":2,"temperatures":1,"templates":1,"temporarily":1,"temporary":2,"terminal":5,"terminals":1,"test":4,"testing":3,"tests":2,"text":11,"textures":1,"theft":1,"theme":10,"themes":3,"things":1,"think":1,"thinner":1,"third":1,"though":1,"thread":23,"threads":2,"three":1,"thumbnails":2,"tiling":1,"time":9,"timeline":1,"times":1,"tint":1,"tip":1,"title":5,"titlebar":1,"tmp":3,"todouble":1,"together":1,"toggle":4,"togglerow":1,"toggles":1,"token":1,"told":4,"tonal":3,"tool":3,"tools":4,"top":3,"traced":1,"track":2,"tracker":3,"tracking":7,"trackpad":1,"trackpads":1,"tracks":2,"train":1,"training":1,"translucent":1,"treats":1,"tree":1,"tried":3,"tries":2,"trigger":1,"trimmed":1,"troubleshooting":4,"true":3,"truncated":3,"truth":1,"try":1,"trying":1,"tty":1,"tui":2,"turn":1,"turns":2,"tweak":1,"tweaks":1,"twice":1,"two":6,"txt":6,"type":4,"typo":1,"ubuntu":1,"udev":1,"ui":4,"uinput":1,"unassigned":1,"unavailable":1,"unchanged":1,"uncommitted":2,"undocumented":1,"unexpectedly":2,"unfullscreen":1,"uninstall":5,"uninstallation":1,"uninstaller":3,"uninstalling":1,"union":1,"unique":1,"unit":1,"units":1,"unity":1,"unless":1,"unpack":1,"unread":1,"unrecognized":1,"unrelated":2,"unsets":1,"unstable":2,"unwanted":1,"update":16,"updated":4,"updater":3,"updaters":1,"updates":4,"updating":2,"upgrade":1,"upgrades":2,"upstream":5,"urgency":1,"url":25,"urls":1,"usage":3,"use":10,"used":4,"useful":1,"user":16,"userimage":1,"users":6,"uses":9,"using":11,"usr":6,"usually":1,"utilities":1,"utility":1,"utilizing":1,"utils":1,"uuid":1,"v1":2,"v2":6,"vague":1,"value":1,"variables":3,"variant":2,"various":1,"ve":1,"vendored":1,"venv":1,"verbatim":1,"verfiy":1,"verifiable":1,"verification":2,"verified":1,"verifies":1,"verify":6,"version":10,"versions":2,"vert":1,"vertical":1,"vesktop":2,"via":8,"vibrant":3,"victims":1,"video":4,"view":1,"virtual":2,"visible":5,"visuals":1,"vlecn0vbvygrzdn9kp8sqn7nt2xpneilgrmzywtzgdqygskadmgophakmy6r6lufqj8ifjy":1,"void":1,"vs":3,"waht":1,"wait":1,"walks":1,"wallpaper":8,"wallpaperplugin":2,"wallpapers":3,"want":2,"wants":1,"warning":3,"washed":1,"watch":1,"watches":1,"way":2,"wayland":5,"waylandclient":1,"wbpg":1,"weaker":2,"weather":2,"weathercard":1,"web":1,"weird":2,"well":1,"went":1,"whatever":1,"whatsnew":1,"whenever":1,"wherever":1,"whether":5,"whichever":1,"white":1,"whole":1,"whose":2,"wide":2,"widget":3,"widgets":3,"width":2,"window":12,"windowlist":1,"windows":6,"wins":2,"wintone01":3,"withdrawn":1,"within":1,"without":10,"wl":1,"won":3,"wont":1,"wording":22,"words":1,"work":6,"workaround":1,"worked":2,"workflow":1,"workflows":1,"working":7,"works":5,"workspace":6,"workspaces":2,"wrapper":4,"wrapping":1,"wraps":1,"writable":1,"writes":6,"writing":1,"written":4,"wrong":8,"wrymt":1,"www":2,"xdg":8,"xe":1,"xoy8evpwlwta0acy3kok0nis1":1,"yay":2,"ydotool":1,"ydotoold":1,"yet":1,"yields":1,"yourself":1,"youtube":1,"yyyymmdd":1,"zkde":2},"docs":[{"dl":714,"id":"DOC-ARCH-KWIN","path":"DOC-ARCH-KWIN.md","sentences":["This document covers the C++ plugin backend and the API available to QML components.","---","## 1. Architectural Evolution: The Native Backend","### The Legacy Approach","Previously, the KDE port relied on a \"fake Hyprland\" wrapper architecture:","1. **KWin JS Script** (`main.js`): Ran continuously in KWin, pushing window data over D-Bus.","2. **Python Daemon** (`qs-kwin-bridge.py`): A background service that listened to these D-Bus signals.","3. **Mock `hyprctl`**: A fake Python mock returning JSON formatted exactly like Hyprland's native output.","**The Problem**: This involved too many IPC hops, was prone to lagging, required a background daemon, and heavily restricted the shell from using KDE's native capabilities.","### The Interim Port","Initially, the port ripped out the Python daemon and used decoupled `QProcess` tasks executing `qdbus6` to inject temporary KWin scripts and manage windows. While more reliable, it still relied heavily on D-Bus and external processes.","### The Current Native Wayland Approach","The current architecture communicates directly with KWin and Wayland via native **C++ Quickshell Plugins**, utilizing pure Wayland protocols and optimized IPC for maximum performance and reliability:","1. **`KWinActiveWindowBridge` (C++ / Wayland Protocol)**","- Binds directly to the `plasma-window-management` Wayland protocol via `PlasmaWindows`.","- Tracks active windows, global window lists, and manages window states natively without D-Bus overhead or KWin script injection.","2. **`KWinWorkspaceState` (C++ / D-Bus & Local Sockets)**","- Interfaces with KDE Plasma's Virtual Desktop Manager over optimized D-Bus calls.","- Handles **Workspace Swipe Tracking** for trackpads via a native `QLocalSocket` tracking server (`caelestia-workspace-tracker`).","3. **`GlobalShortcut` (C++)**","- Standardizes system-wide keyboard shortcuts in C++, routing through KDE's `kglobalaccel` seamlessly.","---","## 2. Developer API Reference (QML)","The following native C++ singletons and components are exposed to QML to interact with KDE natively.","### `KWinActiveWindowBridge` (Singleton)","Provides real-time information about active windows, monitors, and the global window list natively via Plasma Window Management.","**Properties:**","* `activeWindow` (`QVariantMap`): The currently focused window.","* Fields: `address` (String uuid), `title` (String), `class` (String appId), `fullscreen` (Boolean), `maximized` (Boolean).","* `activeOutputName` (`QString`): The name of the monitor/output where the active window resides.","* `windowList` (`QVariantList` of `QVariantMap`): An array containing all active windows across the system.","* Each map contains: `address`, `title`, `class`, `floating`, `fullscreen`, `x`, `y`, `width`, `height`.","**Methods (Invokables):**","* `void focusWindow(const QString &address)`: Brings the specified window to the front and focuses it.","* `void closeWindow(const QString &address)`: Gracefully requests the specified window to close.","* `void minimizeWindow(const QString &address)`: Minimizes the specified window.","* `void maximizeWindow(const QString &address, bool horz = true, bool vert = true)`: Maximizes the window.","* `void setMaximized(const QString &address, bool maximized)`: Sets or unsets the maximized state.","* `void setFullscreen(const QString &address, bool fullscreen)`: Sets or unsets the fullscreen state.","* `void raiseWindow(const QString &address)`: Raises the window to the top of the stack.","* `void setWindowProperty(const QString &address, const QString &property, bool enable)`: Toggles legacy states.","* `void setWindowDesktop(const QString &address, int desktopId)`: Moves window to desktop (-1 for current, -2 for all).","* `void setActiveOutputName(const QString &outputName)`: Manually sets the active output tracker.","* `void refreshWindows()`: Kept for backward compatibility.","### `KWinWorkspaceState` (Singleton)","Provides real-time tracking of KDE Plasma virtual desktops (workspaces) and trackpad swipe gestures.","**Properties:**","* `activeId` (`int`): The ID of the currently active virtual desktop (1-indexed).","* `workspaces` (`QVariantList` of `QVariantMap`): A list of all virtual desktops.","* Each map contains: `id` (String UUID), `name` (String), `index` (Integer 1-based), `active` (Boolean).","* `swipeOffset` (`double`): Real-time fractional offset representing a trackpad swipe in progress (for animations).","**Methods (Invokables):**","* `void switchTo(const QString& id)`: Switches the active workspace to the provided desktop UUID, ID, or name.","* `void createWorkspace(const QString& name = \"\")`: Creates a new virtual desktop.","* `void removeWorkspace(const QString& id)`: Removes the specified virtual desktop.","* `void setDesktop(int desktopId)`: Switches the current desktop workspace by 1-based index.","* `void nextDesktop()`: Switches to the next adjacent desktop, wrapping around at the end.","* `void previousDesktop()`: Switches to the previous adjacent desktop, wrapping around at the beginning.","### `GlobalShortcut` (Component)","A QML component used to register global keyboard shortcuts through KDE's native `kglobalaccel` system.","**Properties:** `name`, `key` (semicolon-separated multi-key), `description`","**Signal:** `activated()`","### `KeybindsModel` & `GlobalShortcutDispatcher` (Singletons)","- **`GlobalShortcutDispatcher`**: Singleton relay for cross-instance signals and the central **collision index** (`key → friendly label`), backed by `stolen-shortcuts.json`.","- **`KeybindsModel`**: `QAbstractListModel` singleton that loads defaults, merges user overrides from `~/.config/caelestia/keybinds.json`, and drives the Nexus shortcut manager UI.","> **Full documentation** — shortcut theft, conflict resolution, crash-safe recovery, the diff-based update logic, and the Nexus UI integration are all covered in detail in **[`docs/shortcut_architecture.md`](shortcut_architecture.md)**.","---","## 3. How Shortcuts are Loaded (`Shortcuts.qml`)","All keyboard shortcuts in Caelestia are declared inside `Shortcuts.qml` under `shell/modules/` using the `CustomShortcut` QML wrapper under `shell/components/misc/`.","The `CustomShortcut` wrapper dynamically inspects the environment at startup:","- **Hyprland**: loads `Quickshell.Hyprland.GlobalShortcut`; bindings come from `hyprland.conf`.","- **KDE (KWin)**: loads `Caelestia.GlobalShortcut`, registering directly with KDE's global shortcut daemon.","See [`docs/shortcut_architecture.md`](shortcut_architecture.md) for full details on the shortcut loading pipeline, Nexus manager, and user override persistence."],"source":"docs/architecture/kwin_port_architecture.md","title":"KWin port architecture (native backend)"},{"dl":608,"id":"DOC-ARCH-LOCKSCREEN","path":"DOC-ARCH-LOCKSCREEN.md","sentences":["This document outlines the architecture, component structure, design system, and developer guidelines for the native Caelestia lock screen implementation in KDE Plasma 6 / KWin.","---","## 1. Overview & Architecture","In KDE Plasma 6, `kscreenlocker_greet` manages the lock screen session and authentication. Rather than relying on third-party Wayland proxies or nested compositors, Caelestia provides a **native Plasma Shell package** (`caelestia.desktop`).","### How It Works","- **Native Shell Package:** The greeter is packaged as a `Plasma/Shell` KPackage located at `~/.local/share/plasma/shells/caelestia.desktop/`.","- **KDE Greeter Registration:** In `~/.config/plasmashellrc`, setting `[Shell]` -> `ShellPackage=caelestia.desktop` instructs `kscreenlocker_greet` to load Caelestia's lockscreen interface directly instead of the stock Plasma desktop shell.","- **Hardware-Accelerated Rendering:** Rendering is performed directly within QtQuick and KWin's compositor using hardware GPU acceleration, eliminating the CPU software-compositing bottlenecks of nested Wayland proxies.","- **Direct Authentication:** The greeter interfaces directly with KDE's ScreenLocker authentication backend (`authenticator`), providing seamless PAM authentication, error handling, grace locks, and fingerprint reader integration.","---","## 2. Component Structure","The lock screen greeter source is located in `src/kde/shells/caelestia.desktop/`:","```","src/kde/shells/caelestia.desktop/","├── metadata.json # KPackage manifest required by kpackagetool6 / plasmashell.","│ # Declares KPackageStructure=Plasma/Shell so the package is","│ # recognized as a greeter shell, not a plugin or applet.","└── contents/","└── lockscreen/","├── LockScreen.qml # Main shell entry wrapper (exposes `locked` to kscreenlocker)","├── LockScreenUi.qml # Root UI layout, scaling, wallpaper blur, & palette","├── components/","│ ├── ClockWidget.qml # Stacked hour/minute clock & formatted date","│ ├── GreetingPill.qml # Time-based greeting pill with weather/time icon","│ ├── ProfileAvatar.qml # ~/.face avatar with M3 pentagon clip and fallback","│ ├── PasswordPill.qml # Password input with animated M3 shapes & fingerprint icon","│ ├── WeatherCard.qml # Weather forecast, temperatures, and condition icon","│ ├── CaelestiafetchCard.qml # System information card with Caelestia logo & palette dots","│ ├── MediaCard.qml # MPRIS media player with rounded album art and playback controls","│ ├── ResourcesCard.qml # CPU, RAM, and Disk resource meters with live temp badge","│ └── NotifDock.qml # Categorized notification dock with expandable groups","└── scripts/","└── sysinfo.py # system info fetch script","```","---","## 3. Design constants","The Caelestia lock screen brings the Quickshell lock screen design into native KDE Plasma 6:","1. **Frosted-Glass Blur Textures:**","- Because KWin Wayland does not apply compositor background blur to out-of-process greeter windows, Caelestia uses KDE's greeter wallpaper blurring technique by sourcing the in-process `wallpaper` item directly through `FastBlur` (radius 64).","- The blurred wallpaper is mapped onto the lockscreen container (`lockBg`) and layout regions using a live `ShaderEffectSource` clipped with `OpacityMask` matching the container's corner radius (`bgRadius`).","- Card widgets use translucent surface backgrounds (`Qt.rgba(..., 0.55)`).","2. **Concentric Corner Radii:**","- Outer background container radius: `bgRadius = 42px` (scaled with screen height).","- Inner container padding: `bgMargin = 16px`.","- Card widget corner radius: `cardRadius = bgRadius - bgMargin = 26px`.","3. **Avatar Priority:**","- [`ProfileAvatar.qml`](../../src/kde/shells/caelestia.desktop/contents/lockscreen/components/ProfileAvatar.qml) prioritizes `~/.face` directly from the user's home directory.","- Automatically falls back to the system account picture (`kscreenlocker_userImage`) and the Material Symbols user icon if `~/.face` is absent.","4. **Responsive Layouts:**","- **Landscape (Default):** 3-column layout (Left: Weather, Caelestiafetch, Media | Center: Clock, Avatar, Password Pill | Right: Resources, Notification Dock).","- **Portrait:** Centered vertical column adapting automatically on vertical displays.","---","## 4. Deployment, Testing, and Uninstallation","### Deployment","The lock screen greeter is deployed automatically by the installer in Step 5 ([`scripts/02-packages.sh`](../../scripts/02-packages.sh)) and updated during shell builds ([`scripts/08-build-shell.sh`](../../scripts/08-build-shell.sh)):","```bash","# Manual installation / deployment:","mkdir -p ~/.local/share/plasma/shells/","cp -r src/kde/shells/caelestia.desktop ~/.local/share/plasma/shells/","kwriteconfig6 --file plasmashellrc --group \"Shell\" --key \"ShellPackage\" \"caelestia.desktop\"","```","### Interactive Testing","You can test the lock screen UI safely in a non-blocking test window without locking your desktop session:","```bash","/usr/lib/kscreenlocker_greet --testing","```","### Uninstallation & Reverting","To revert back to the stock KDE Breeze lock screen:","```bash","# Reset shell package back to KDE default","kwriteconfig6 --file plasmashellrc --group \"Shell\" --key \"ShellPackage\" --delete","# Restore default Breeze greeter theme","kwriteconfig6 --file kscreenlockerrc --group \"Greeter\" --key \"Theme\" \"org.kde.breeze.desktop\"","# (Optional) Remove local shell files","rm -rf ~/.local/share/plasma/shells/caelestia.desktop","```","This is also handled automatically when running [`./uninstall.sh`](../../uninstall.sh)."],"source":"docs/architecture/lockscreen_architecture.md","title":"Lock screen architecture"},{"dl":344,"id":"DOC-ARCH-SHORTCUT","path":"DOC-ARCH-SHORTCUT.md","sentences":["This document provides a simplified overview of how the Caelestia shortcut system works, from the backend C++ components to the QML frontend.","---","## 1. High-Level Overview","```text","[ QML UI (Shortcuts.qml, Nexus) ]","│","▼","[ GlobalShortcut (C++ / QML) ]","│ registers keys & handles conflicts","▼","[ GlobalShortcutDispatcher ] <── [ KeybindsModel ]","(Tracks stolen keys) (Loads user settings)","```","- **`GlobalShortcut`**: Registers a single shortcut.","- **`GlobalShortcutDispatcher`**: A central hub that tracks shortcut collisions.","- **`KeybindsModel`**: Manages user-configured overrides and default bindings.","---","## 2. Core Components","### `GlobalShortcut`","This handles binding a hotkey (like `Meta+P`) to an action. It uses KDE's `kglobalaccel` under the hood.","**Key Features:**","- **Key Conflict Resolution:** If you try to use a shortcut that another KDE app is already using (like Spectacle using `Print`), Caelestia will temporarily \"steal\" it.","- **Smart Restoration:** If you change or remove a Caelestia shortcut, any stolen shortcuts are automatically given back to their original KDE apps.","### `GlobalShortcutDispatcher`","A singleton that acts as the central coordinator.","- **Collision Index:** It keeps track of which keys are currently \"stolen\" from other apps.","- This allows the UI to easily show a warning (like a red dot) if a shortcut conflicts with another app.","### `KeybindsModel`","Manages saving and loading your shortcut preferences.","1. Loads defaults from `keybindsdefaults.hpp`.","2. Applies user customizations from `~/.config/caelestia/keybinds.json`.","3. Communicates with the UI to update the list of active shortcuts.","---","## 3. Crash Recovery (Safety First)","If the shell crashes or is force-killed, we don't want your KDE shortcuts to be permanently broken because we stole them and never gave them back.","**How it works:**","1. Whenever Caelestia steals a shortcut, it immediately writes this to a recovery file: `~/.config/caelestia/stolen-shortcuts.json`.","2. When the shell closes normally, it restores the shortcuts and deletes the file.","3. If the shell crashes, the file remains on disk. On the **next startup**, Caelestia reads this file, restores all the stolen shortcuts, and cleans up.","---","## 4. User Interface (QML)","### Defining Shortcuts (`Shortcuts.qml`)","Shortcuts are defined using a `CustomShortcut` component. It automatically detects if you are running KDE (KWin) or Hyprland and uses the correct backend.","### Nexus Shortcut Manager","The Nexus settings panel is where users manage their shortcuts:","- **Groups:** Organizes shortcuts into categories (Shell, Apps, etc.).","- **Collision Blinker:** Shows a red warning dot if a key sequence conflicts with an existing KDE app. Hovering shows which app was overridden.","- **Editing:** Users can capture new keystrokes or reset back to default settings.","---","## 5. Important Files","| File | Purpose |","|---|---|","| `globalshortcut.hpp / .cpp` | Core logic for binding, stealing, and restoring shortcuts. |","| `keybindsmodel.hpp / .cpp` | Manages user settings and feeds data to the UI. |","| `keybindsdefaults.hpp` | The default key combinations. |","| `Shortcuts.qml` | Where all shell shortcuts are declared. |","| `keybinds.json` | Where user overrides are saved. |","| `stolen-shortcuts.json` | Crash recovery file. |"],"source":"docs/architecture/shortcut_architecture.md","title":"Shortcut system architecture"},{"dl":735,"id":"DOC-README","path":"DOC-README.md","sentences":["
","\"Caelestia","# caelestia-kde","[![Arch Linux](https://img.shields.io/badge/Arch_Linux-1793d1?logo=arch-linux&logoColor=white&style=for-the-badge&labelColor=101418)](https://archlinux.org)","[![Fedora](https://img.shields.io/badge/Fedora-51A2DA?logo=fedora&logoColor=white&style=for-the-badge&labelColor=101418)](https://fedoraproject.org)","[![Ubuntu](https://img.shields.io/badge/Ubuntu-E95420?logo=ubuntu&logoColor=white&style=for-the-badge&labelColor=101418)](https://ubuntu.com)","[![KDE Plasma](https://img.shields.io/badge/Plasma_6-1D99F3?logo=kde&logoColor=white&style=for-the-badge&labelColor=101418)](https://kde.org/plasma-desktop)","[![License: GPL-3.0-or-later](https://img.shields.io/badge/License-GPL--3.0--or--later-9bd0cc?style=for-the-badge&labelColor=101418)](LICENSE)","
","","https://github.com/user-attachments/assets/38b24e7f-fdd9-43db-872b-8c0ac23a44fd","> [!NOTE]","> This repo is the KDE Plasma port of [`caelestia-dots/shell`](https://github.com/caelestia-dots/shell).","> Upstream runs on Hyprland; the port runs the same shell on KWin and Plasma. For the original","> Hyprland dotfiles, see [`caelestia-dots/caelestia`](https://github.com/caelestia-dots/caelestia).","## Installation","**Requirements:** Arch-based, Fedora, or Debian/Ubuntu - KDE Plasma 6 on Wayland, Qt 6.9+","```bash","curl -fsSL https://raw.githubusercontent.com/ladybug-me/caelestia-kde/main/install.sh | sh","```","### Updating","- **Installer TUI:** run the installer and choose *Update*","- **GUI:** Nexus -> Updates -> select branch -> Install Updates","- **CLI:** `bash update.sh` and choose `main` (stable) or `dev` (bleeding edge)","Shell settings are preserved across updates.","### Uninstalling","Choose *Uninstall* from the installer TUI, or run:","```bash","bash ./uninstall.sh","```","## Keybinds","| Shortcut | Action |","| --- | --- |","| `Super` | App launcher |","| `Super + /` | Keybind cheatsheet |","| `Super + Enter` | Terminal |","| `Super + Tab` | Overview |","| `Super + 1-5` | Switch workspace |","| `Super + B` | Notification sidebar |","| `Super + V` | Clipboard history |","| `Super + Shift + S` | Screenshot |","| `Super + Shift + A` | Google Lens |","| `Super + Shift + D` | Text recognition |","| `Super + Ctrl + S` | Screen recorder |","| `Super + Shift + C` | Color picker |","| `Super + Shift + V` | Emoji selector |","## Configuring","Open Nexus (`Super`, then `>Settings`).","- Appearance: wallpaper, colors, fonts, and the wallpaper slideshow","- Panels: every bar element, dashboard, launcher, sidebar and overview","- Desktop: window rules, the context menu, Krohnkite","- Shortcuts: rebind any built-in shortcut, or add a command shortcut","- Plugins: browse the store, or install a plugin you built yourself","Set the wallpaper from Appearance. The stock KDE wallpaper manager does not drive","the color scheme, so using it leaves the shell on stale colors.","Settings are written to `~/.config/caelestia/shell.json`.","## Troubleshooting","| Problem | Fix |","| --- | --- |","| Widgets not appearing | Log out and back in, or run `caelestia shell -d` |","| Colors not applying | Run `caelestia scheme set -n dynamic`, or `caelestia wallpaper -f `. See [TROUBLESHOOTING.md](docs/TROUBLESHOOTING.md#34-colors-not-applying) |","| Install failed mid-way | Re-run `bash ./scripts/setup.sh` |","| Full reset needed | See [TROUBLESHOOTING.md](docs/TROUBLESHOOTING.md) |","For detailed logs, enable Debug Mode in Nexus -> About -> Advanced, then run","`caelestia shell -l`. Bug reports and questions go to","[GitHub Issues](https://github.com/ladybug-me/caelestia-kde/issues).","## Repository layout","```","installer/ TUI installer and the per-distro package lists","tui/ C++ TUI source and its CMakeLists","data/ menu.json, theme.json, tui.version","distro/ per-distro package installation (arch, debian, fedora)","scripts/ install/update pipeline: the numbered steps and their shared lib/","src/ files copied onto the system, plus the vendored submodules","shell/ the QML shell and its C++ QML plugin","docs/ guides, plus design notes under docs/architecture/","tests/ bash tests for the step-script helpers","tools/ repo maintenance scripts, never shipped","assets/ the logo and screenshots used by the docs",".github/ workflows, issue and PR templates, CI checks","```","","","","","\"Star","","","## Credits","- [caelestia-dots/shell](https://github.com/caelestia-dots/shell) and the [Caelestia dotfiles](https://github.com/caelestia-dots/caelestia) by [@soramanew](https://github.com/soramanew) - the design language, shell and dotfiles this port is built on","- [ladybug-me](https://github.com/ladybug-me) - KDE port lead","- [0xSolanaceae](https://github.com/0xSolanaceae) - Head maintainer","- [Bali10050](https://github.com/Bali10050/Darkly) - Darkly Qt","- [wrymt](https://github.com/wrymt/darkly-gtk) - Darkly GTK","- [Haidir](https://bitbucket.org/dirn-typo/yet-another-monochrome-icon-set) - icon set","## License","GPL-3.0-or-later - see [LICENSE](LICENSE)."],"source":"README.md","title":"caelestia-kde README"},{"dl":442,"id":"DOC-TS-01","path":"DOC-TS-01.md","sentences":["### 1.1 C++ Installer Compilation Fails","The installer compiles the `caelestia-install` TUI binary during `setup.sh`. The CMake project requires **C++20** (`CMAKE_CXX_STANDARD 20`).","| Symptom | Likely Cause | Fix |","|---|---|---|","| `g++: command not found` | Build tools not installed | Arch: `sudo pacman -S base-devel` — Fedora: `sudo dnf install gcc-c++` |","| `cmake: command not found` | CMake missing | Auto-installer handles this if `BASE_DISTRO` is detected; otherwise install manually |","| `[FATAL] Failed to build the Caelestia installer` | General CMake/make error | Read build log: `cat /tmp/caelestia_build.log` |","| Compiler error about modern C++ features | GCC older than 10 | Ensure GCC 10+ is installed: `g++ --version` |","| Exit 139 (SIGSEGV) at runtime | C++ bug in the TUI | Check stderr log at `/tmp/caelestia_installer_err.log` |","| Exit 127 at runtime | Missing shared library | Run `ldd` on the binary to find missing `.so` files |","### 1.2 Shell / Plugin Compilation Fails","The shell build (`08-build-shell.sh`) requires **Qt 6.9+** and several system libraries. The CMake project in `shell/CMakeLists.txt` uses `qt_standard_project_setup(REQUIRES 6.9)`.","#### Qt / QML Dependencies","| Missing Dependency | CMake Error Clue | Arch Package | Fedora Package |","|---|---|---|---|","| Qt6::Qml / Qt6::Quick | `find_package` failed | `qt6-declarative` | `qt6-qtdeclarative-devel` |","| Qt6::ShaderTools | Shader tool config | `qt6-shadertools` | `qt6-qtshadertools-devel` |","| Qt6::WaylandClient | Wayland client plugin | `qt6-wayland` | `qt6-qtwayland-devel` |","| KF6WindowSystem | KWindowSystem not found | `kwindowsystem` | `kf6-kwindowsystem-devel` |","| KGlobalAccel | kglobalaccel not found | `kglobalaccel` | `kf6-kglobalaccel-devel` |","| KPipeWire | pipewire integration | `kpipewire` | `kf6-kpipewire-devel` |","#### Library Dependencies (pkg_check_modules)","| Library | Arch Package | Fedora Package |","|---|---|---|","| `libqalculate` | `libqalculate` | `libqalculate-devel` |","| `libpipewire-0.3` | `pipewire` | `pipewire-devel` |","| `aubio` | `aubio` | `aubio-devel` |","| `libcava` | Prebuilt release asset / `libcava` | Prebuilt release asset / `celestelove/libcava` (COPR) |","| `libpulse` | `libpulse` | `pulseaudio-libs-devel` |","| `libpam` | `pam` | `pam-devel` |","| `lm_sensors` (Fedora) | not needed | `lm_sensors-devel` |","**Fedora note:** The custom `cmake/sensorslib.cmake` module loads `lm_sensors`. If it's missing, the build may silently skip sensor support.","### 1.3 \"Missing QML Module Metadata\" After Build","```text","[ERR] Missing QML module metadata: $HOME/.local/lib/qt6/qml/Caelestia/Config/qmldir","```","This means the CMake install step didn't copy required `qmldir` or `.so` files properly.","**Causes & fixes:**","- **Install prefix mismatch:** The build uses `-DCMAKE_INSTALL_PREFIX=$HOME/.local`. If Qt6 looks for QML modules elsewhere, the module won't load.","- **Stale build artifacts:** Run `rm -rf shell/build shell/plugin/build` before re-running","- **Partial installation:** If CMake install was interrupted, files may be missing. Re-run `08-build-shell.sh`","### 1.4 ccache Not Speeding Up Rebuilds","The project enables ccache in both `installer/CMakeLists.txt` and `shell/CMakeLists.txt`. If rebuilds are still slow:","- Check ccache stats: `ccache -s`","- The cache directory (`~/.cache/ccache`) may be too small — increase it: `ccache -M 5G`","- Debug builds (`-DCMAKE_BUILD_TYPE=Debug`) are much slower; the installer uses `Release`"],"source":"docs/TROUBLESHOOTING.md — section 1 (Build & Compilation Issues)","title":"1. Build & Compilation Issues"},{"dl":285,"id":"DOC-TS-02","path":"DOC-TS-02.md","sentences":["### 2.1 Arch Linux / yay Failures","| Issue | Cause |","|---|---|","| `yay` fails to install | Network issues, AUR down, or PKGBUILD changes. The script (`installer/distro/arch/packages.sh`) retries individually and falls back to `makepkg -si`. |","| `pacman` errors during install | The script uses `-Sy --noconfirm` (refresh DB) then `-S --needed --noconfirm`. If the system update step (`00a-system-update.sh`) was skipped, partial upgrades can cause conflicts. |","**AUR packages used by Caelestia:**","| AUR Package | Failure Symptoms |","|---|---|","| `quickshell-git` | Shell won't start; autostart fails with exit 127 |","| `matugen` | `caelestia wallpaper` and `caelestia scheme` fail with \"matugen is not installed\". It is in Arch's `extra`, so it is not an AUR package; it is listed here because nothing themes without it. |","| `darkly` | KDE theme won't apply |","### 2.2 Fedora / COPR Failures","| Package | COPR / Source | Known Issues |","|---|---|---|","| `quickshell-git` | `errornointernet/quickshell` | COPR may be out of date |","| `gpu-screen-recorder` | `brycensranch/gpu-screen-recorder-git` | May need `ffmpeg` from RPM Fusion |","| `app2unit` | `celestelove/app2unit` | Falls back to `make install` |","| `libcava` | Prebuilt release asset / `celestelove/libcava` | Downloads prebuilt SDK from release; falls back to COPR |","| `starship` | `atim/starship` | Stable, rarely fails |","| `wl-clip-persist` | `leloubil/wl-clip-persist` | Needed for clipboard persistence |","**RPM Fusion requirement:** `ffmpeg` with H264 support requires RPM Fusion. The script auto-enables it, but this may fail behind a proxy or on air-gapped systems.","**matugen on Fedora:** there is no package for it, and it is what generates the palette. The installer reports it when it is missing; `cargo install matugen` fixes it.","### 2.3 CRLF / dos2unix Failure","If CRLF line endings are detected and `dos2unix` auto-install fails, the installer **aborts** with:","```text","[FATAL] Line ending normalization step failed. Aborting installer.","```","**Fix:** Install `dos2unix` manually, or answer `n` to the CRLF prompt to skip normalization.","### 2.4 Failed Packages Log","Failed packages are logged to:","```text","$XDG_CACHE_HOME/caelestia-kde/failed_packages.txt","```","The installer does **not** abort on package failure — it logs and continues. Check this file after installation if something doesn't work."],"source":"docs/TROUBLESHOOTING.md — section 2 (Dependency & Package Issues)","title":"2. Dependency & Package Issues"},{"dl":1002,"id":"DOC-TS-03","path":"DOC-TS-03.md","sentences":["### 3.1 Shell Doesn't Start After Login","The shell starts from the systemd user unit `caelestia-shell.service`, which `caelestia install` enables once.","The environment the shell needs is set by `~/.local/bin/caelestia-autostart.sh` for a source install, and by `/usr/bin/caelestia-autostart` for a packaged one; the unit runs whichever belongs to that install.","| Symptom | Likely Cause |","|---|---|","| Blank screen at login | Shell binary launched but crashed immediately. Check `journalctl --user -xe`. |","| Plasma desktop visible, no shell | The unit didn't start. `systemctl --user status caelestia-shell.service`, and `systemctl --user is-enabled caelestia-shell.service` for whether it is on at all. |","| Shell appears briefly then disappears | Quickshell crashed. Run manually from a terminal. |","| `quickshell: command not found` | Quickshell not in PATH at login. The wrapper the unit runs resolves the binary path. |","**Manual start for debugging:**","```bash","export QML2_IMPORT_PATH=\"$HOME/.local/lib/qt6/qml\"","export CAELESTIA_LIB_DIR=\"$HOME/.local/lib/caelestia\"","quickshell -d -n -p ~/.config/quickshell/caelestia/shell.qml","```","### 3.2 Environment Variables Not Set On Login","They live in two locations:","1. `~/.config/environment.d/caelestia.conf`: read by systemd for every session process and for the user manager the shell's unit runs under.","2. `~/.config/plasma-workspace/env/caelestia.sh`: sourced by KDE Plasma on session startup for KWin, `kscreenlocker_greet`, and graphical applications.","```bash","QML2_IMPORT_PATH=$HOME/.local/lib/qt6/qml:$HOME/.config/quickshell/caelestia","CAELESTIA_LIB_DIR=$HOME/.local/lib/caelestia","CAELESTIA_BIN_DIR=$HOME/.local/bin","CAELESTIA_SHELL_CONFIG=$HOME/.config/quickshell/caelestia/shell.qml","```","**If they are missing:** re-run `scripts/08-build-shell.sh`, then log out and back","in. `systemctl --user show-environment` lists what the systemd user manager has.","### 3.3 Window Thumbnails / Screencast Not Working","KWin only grants `zkde_screencast_unstable_v1` to clients whose `.desktop` file lists the protocol.","**Fix:**","```bash","# Verify the desktop file exists","cat ~/.local/share/applications/quickshell.desktop","# Rebuild KService cache","kbuildsycoca6 --noincremental","# Reload KWin","qdbus6 org.kde.KWin /KWin reconfigure","```","If the desktop file is missing, re-run `scripts/10-autostart.sh`.","### 3.3.1 Screen Sharing / Camera Freezes Vesktop (or other apps)","Some NVIDIA + KWin setups cannot handle two separate clients using KWin's","privileged `zkde_screencast_unstable_v1` protocol at the same time. Caelestia","uses this protocol for live taskbar/overview/alt-tab window thumbnails, which","can conflict with another app's screencast (e.g. Vesktop screen share with","audio, or camera) using the same KWin subsystem via xdg-desktop-portal-kde,","causing that app to freeze or crash.","**Fix:** Disable live window previews:","- Nexus -> Taskbar -> \"Live window previews\" toggle, or","- Set `\"bar\": { \"livePreviews\": false }` in `shell.json` and reload","This falls back to static app icons for thumbnails instead of live video and","avoids Caelestia's use of the protocol entirely.","### 3.4 Colors Not Applying","| Symptom | Fix |","|---|---|","| Colors do not change with the wallpaper | `caelestia wallpaper -f ` generates and applies the palette. If Plasma stays on the old one, check that `plasma-apply-colorscheme --list-schemes` names `Matugen`. |","| Two Material You entries in System Settings | Expected: `Matugen` and `Matugen Alt`. `plasma-apply-colorscheme` does nothing when handed the scheme already in effect, so the palette is applied under whichever of the two is not current. |","| A leftover accent color wins over the palette | Plasma rewrites the focus, link and selection colors from `kdeglobals`' accent, so the palette is applied with that key removed.","If it is set again - System Settings, or a theme tool of your own - the colors it drives will follow it.","|","| Colors come back as the built-in default (Mocha) | The CLI derives dynamic colors from the wallpaper it was last told about.","When it has none it writes nothing, and the shell keeps its own default palette.","The shell re-derives from the wallpaper it is showing at every start.","|","| Konsole keeps its own colors | The command writes `~/.local/share/konsole/Matugen.colorscheme` and points the profiles that exist at it.","Konsole's built-in default profile is not a file, so a fresh account has nothing to point: create a profile once and the next change themes it.","|","| The desktop flickers between two palettes | A `kde-material-you-colors` unit from an older install is still applying a scheme of its own. See 3.7. |","There is no service to restart. A palette is generated and applied by the command the shell calls, so","the way to redo it by hand is:","```bash","caelestia scheme set -n dynamic # re-derive from the wallpaper on screen","caelestia wallpaper -f ~/Pictures/Wallpapers/one.png","```","### 3.5 Screen Recording Issues","| Symptom | Cause |","|---|---|","| Recording appears stuck | `gpu-screen-recorder` not installed or not in PATH |","| Portal dialog doesn't appear | The `caelestia-record` wrapper restarts `plasma-xdg-desktop-portal-kde` and `xdg-desktop-portal` before launching `gpu-screen-recorder`.","If the portal still doesn't appear, restart them manually: `systemctl --user restart plasma-xdg-desktop-portal-kde xdg-desktop-portal`.","|","| Recording doesn't start | `caelestia-record` wraps `gpu-screen-recorder` directly with KDE-specific monitor detection (via `kscreen-doctor`) and portal management. No Python/OpenCV dependency. |","The recorder now verifies both `pidof gpu-screen-recorder` AND that `recording.mp4` exists, preventing false positives from stale PID matches.","### 3.6 Screenshot Issues","The screenshot tool uses `spectacle` (KDE's native screenshot utility) via the `caelestia-screenshot` wrapper.","- If `spectacle` isn't installed, screenshots silently fail","- Full-screen screenshots save to `~/Pictures/Screenshots/` by default","### 3.7 Screen Flashes and the Shell Stutters Every Second","The screen flashes, colors look briefly wrong and the shell hangs for about a","second, repeating on a rhythm of roughly one second.","That was `kde-material-you-colors` getting stuck. It decided on every loop that","the palette had changed, applied an identical scheme again and spawned","`plasma-apply-colorscheme` each time, and every apply rewrites `kdeglobals` and","repaints every window. Nothing here runs it any more: it is not installed, the","installer removes its unit, and the palette is applied once per change rather than","once per poll.","If it is still happening, a unit from an older install is behind it:","```bash","systemctl --user status kde-material-you-colors # active means it is still applying","systemctl --user disable --now kde-material-you-colors","pgrep -af plasma-apply-colorscheme # a new pid every second means something still loops","```","`bash scripts/10-autostart.sh` stops that unit and deletes it, if you would rather","not do it by hand. It also removes the `MaterialYou*.colors` files KMY left in","System Settings.","Applying once when the wallpaper or theme changes is expected and does not","trigger any of this.","---","### 3.8 Workspace Tracker Effect Stops Loading After a KDE Update","The workspace pills show the focused screen's desktop on every screen, swiping","does not track the gesture, and the shell reports that the workspace tracker","effect is not running.","`kwin_workspace_tracker` is a compiled KWin effect, and KWin makes no promise","that a binary effect keeps working across releases: it is linked against","libkwin's internals and has to be relinked when KDE updates them. KWin then","refuses the stale binary, so per-output desktops and the swipe offset stop","arriving. A routine `pacman -Syu` is enough to cause it; nothing in Caelestia is","corrupted.","Rebuild it by re-running the installer or `update.sh`, then log out and back in -","KWin only loads effects at startup:","```bash","bash update.sh # rebuilds and reinstalls the effect","qdbus6 org.kde.KWin /Caelestia/Workspaces org.freedesktop.DBus.Introspectable.Introspect","```","The last command prints the effect's interface once it is loaded again, and","fails while it is not. `bash shell/scripts/check-workspace-tracker.sh` answers the","same question with an exit status (3 means enabled but not loaded)."],"source":"docs/TROUBLESHOOTING.md — section 3 (Runtime Issues — Shell)","title":"3. Runtime Issues — Shell"},{"dl":235,"id":"DOC-TS-04","path":"DOC-TS-04.md","sentences":["### 4.1 Lock Screen Greeter Diagnostic","The Caelestia lock screen runs as a native KDE Plasma 6 shell package (`caelestia.desktop`), loaded directly by KDE's `kscreenlocker_greet`.","**Diagnostic commands:**","```bash","# Verify Caelestia shell package is configured","kreadconfig6 --file plasmashellrc --group \"Shell\" --key \"ShellPackage\"","# Expected output: caelestia.desktop","# Verify greeter files exist in local plasma shells directory","ls -la ~/.local/share/plasma/shells/caelestia.desktop/contents/lockscreen/LockScreenUi.qml","# Test and run the greeter in a window (non-blocking test)","/usr/lib/kscreenlocker_greet --testing","```","| Symptom | Cause | Solution |","|---|---|---|","| Stock Breeze lock screen appears | `ShellPackage` reset after KDE update or theme switch.","| Caelestia autostart (`caelestia-autostart.sh`) automatically self-heals this at next login if `caelestia.desktop` is present.","To restore immediately in session: `kwriteconfig6 --file plasmashellrc --group \"Shell\" --key \"ShellPackage\" \"caelestia.desktop\" && kwriteconfig6 --file kscreenlockerrc --group \"Greeter\" --key \"Theme\" --delete`.","|","| Lock screen fails or crashes | Greeter files missing or corrupted in `~/.local/share/plasma/shells/`. | Re-deploy via `BUNDLE_DIR=. ./scripts/02-packages.sh` or `cp -r src/kde/shells/caelestia.desktop ~/.local/share/plasma/shells/`. |","| Lock screen shows wallpaper error | Legacy `PlasmaApplicationWallpaper` left in `kscreenlockerrc`. | Reset WallpaperPlugin: `kwriteconfig6 --file kscreenlockerrc --group Greeter --key WallpaperPlugin \"org.kde.image\"`. |","| Profile picture missing | `~/.face` does not exist and no system user avatar set. | Place your avatar image at `~/.face` or configure an avatar in KDE System Settings → Users. |"],"source":"docs/TROUBLESHOOTING.md — section 4 (Runtime Issues — Lock Screen)","title":"4. Runtime Issues — Lock Screen"},{"dl":271,"id":"DOC-TS-05","path":"DOC-TS-05.md","sentences":["### 5.1 Darkly Theme Not Applied","| Symptom | Cause |","|---|---|","| Plasma style unchanged | `APPLY_DARKLY` was set to `false` in the configuration menu |","| Window decorations missing | The installer tries `org.kde.darkly` library, falls back silently to `org.kde.breeze` |","| `lookandfeeltool --apply \"Darkly\"` failed | The `darkly` package may not be installed (AUR/COPR/prebuilt packages) |","**Manual apply:**","```bash","kwriteconfig6 --file kwinrc --group \"org.kde.kdecoration2\" --key \"library\" \"org.kde.darkly\"","kwriteconfig6 --file kwinrc --group \"org.kde.kdecoration2\" --key \"theme\" \"@darkly\"","qdbus6 org.kde.KWin /KWin reconfigure","```","### 5.2 KDE OSD Still Showing","The tweak script disables OSD in `plasmarc`, `kdeglobals`, `plasmanotifyrc`, `powerdevilrc`, and `kmixrc`. If OSD still appears:","```bash","systemctl --user restart plasma-plasmashell","```","Some KDE versions (6.1 vs 6.2) may use slightly different config keys.","### 5.3 Wrong Number of Virtual Desktops","The installer configures exactly **5 desktops**. If you had a different count before:","- Re-run `scripts/09-system-tweaks.sh` to re-apply","- The uninstaller resets desktop count to `1`","### 5.4 Keyboard Shortcut Conflicts","Caelestia's `GlobalShortcut` system uses `kglobalacceld`. When it registers a shortcut that conflicts with another app, it \"steals\" the binding and records it in:","```text","~/.config/caelestia/stolen-shortcuts.json","```","**If shortcuts are missing or wrong:**","```bash","rm -f ~/.config/caelestia/stolen-shortcuts.json","systemctl --user status plasma-kglobalaccel.service","```","If `keyd` is active and manages Meta+1..5, the tweak script skips KWin bindings for those combos to avoid conflicts.","### 5.5 Terminal Sequence Bleeding (Garbled Output)","If ANSI escape sequences leak from the `caelestia` CLI into your terminal:","```bash","cat $XDG_CACHE_HOME/caelestia-kde/failed_patches.txt","```","If `Caelestia CLI Theme Sequence Patch` appears in the failed list, re-run:","```bash","bash scripts/09-system-tweaks.sh","```"],"source":"docs/TROUBLESHOOTING.md — section 5 (Configuration Issues)","title":"5. Configuration Issues"},{"dl":305,"id":"DOC-TS-06","path":"DOC-TS-06.md","sentences":["### 6.1 Pacman Mirror Ranking Fails","On CachyOS, the installer uses the native `cachyos-rate-mirrors` command, which ranks both Arch and CachyOS repositories.","Other Arch-based systems use `reflector` as a fallback.","Fedora refreshes its configured DNF metadata and Debian-based systems refresh their configured APT indexes; neither needs mirror-list rewriting during installation.","Failure modes:","- **Offline:** Mirror ranking fails and the existing mirror lists are kept","- **cachyos-rate-mirrors unavailable:** CachyOS mirror ranking is skipped and the existing mirror lists are kept","- **reflector not installed:** On non-Cachy Arch systems, it is auto-installed via `pacman -Sy reflector`; if that fails, ranking is skipped","- **DNF or APT refresh fails:** Fedora/Debian package installation continues and reports the package-manager error later if the configured sources remain unavailable","### 6.2 Git / Submodule Failures","The submodule `src/dots` is critical. If it cannot be fetched:","```text","[ERR] src/dots is still empty, and the installer cannot deploy without it.","```","Step 02a checks the submodule has content and fetches it again by other means before reporting this: a normal update, then a sync of the recorded URL followed by another update, then a forced update, and finally a plain clone of the URL `.gitmodules` records.","So this message means all four were attempted and every one failed, which is usually a network that cannot reach GitHub or a checkout that cannot be written to.","This is a **hard failure** - the installer cannot proceed past config deployment. Fetch it by hand and re-run the step:","```bash","git -C ~/caelestia-kde submodule update --init --recursive src/dots","bash ~/caelestia-kde/scripts/02a-submodules.sh","```","The shared folder mounted at `/mnt/hgfs/` is read-only, so an install run from there cannot fetch anything: clone the repository to a writable directory first.","**Behind a proxy?**","```bash","git config --global http.proxy http://proxy:port","git config --global https.proxy http://proxy:port","export GIT_SSL_NO_VERIFY=1","```","### 6.3 AUR Builds Fail Behind Proxy","`makepkg -si` downloads sources from various URLs. Set proxy environment variables before running `setup.sh`:","```bash","export http_proxy=http://proxy:port","export https_proxy=http://proxy:port","export ALL_PROXY=http://proxy:port","```"],"source":"docs/TROUBLESHOOTING.md — section 6 (Network & Proxy Issues)","title":"6. Network & Proxy Issues"},{"dl":737,"id":"DOC-TS-07","path":"DOC-TS-07.md","sentences":["### 7.1 Legacy qs-kwin-bridge Service","The old `qs-kwin-bridge` Python daemon is now **disabled** in favor of native C++ plugins. If you see it running:","```bash","systemctl --user disable --now qs-kwin-bridge.service","```","### 7.2 xdg-desktop-portal-kde","The recording patch restarts `plasma-xdg-desktop-portal-kde` before each recording. This may fail if:","- The portal service is masked","- The user's systemd session is in a bad state","### 7.3 ydotoold (On-Screen Keyboard)","`ydotoold` needs access to `/dev/uinput`. The installer:","1. Creates `/etc/udev/rules.d/80-uinput.rules`","2. Adds user to `input` group","3. Creates sudoers NOPASSWD rule","**If ydotoold doesn't work:**","- Re-login (group changes take effect on next login)","- Verify: `groups $USER` should include `input`","- Verify: `ls -la /run/user/$(id -u)/.ydotool_socket`","### 7.4 Krohnkite Tiling Disabled on Uninstall","The uninstaller disables `krohnkiteEnabled` in `kwinrc`. If you don't have the Krohnkite KWin script installed, this setting is simply ignored.","### 7.5 KWin Script Injection Fails","The plugin injects a temporary KWin script for window tracking. If KWin scripting is disabled:","```bash","qdbus6 org.kde.KWin /Scripting org.kde.kwin.Scripting.loadScript","```","### 7.6 The Login Screen (Plasma Login and SDDM)","Plasma 6.6 and newer boot into Plasma Login, KDE's fork of SDDM. The two are","configured in different places, and the installer picks a branch at install time:","| | Plasma Login | SDDM |","|---|---|---|","| How to tell | `plasmalogin.service` is active/enabled | `sddm.service` is active/enabled |","| Theme | none: its greeter is a Plasma shell, and it loads no SDDM theme | `/usr/share/sddm/themes/caelestia` |","| Wallpaper | `[Greeter][Wallpaper][org.kde.image][General] Image` in `/etc/plasmalogin.conf`, pointing at a copy under the `plasmalogin` user's `wallpapers/` | `assets/background` inside the theme |","| Colors | the `plasmalogin` user's own `~/.config/kdeglobals` plus the scheme files in its `~/.local/share/color-schemes/` | `theme.conf` inside the theme |","| Sync helper | `/usr/local/bin/caelestia-greeter-sync` | `/usr/share/sddm/themes/caelestia/scripts/sync.sh` |","The greeter runs as its own system user, which cannot read your home directory, so","anything it shows has to be copied to it. That is what the sync helper does, and it","runs after every wallpaper or color change through the posthook in","`~/.config/caelestia/cli.json`. An install that switches display managers replaces","its hook rather than stacking a second one.","**The login screen shows Breeze colors or no background:**","```bash","# Which display manager is actually installed","command -v plasmalogin sddm","# Plasma Login: what the greeter is told to show","kreadconfig6 --file /etc/plasmalogin.conf --group Greeter --group Wallpaper \\","--group org.kde.image --group General --key Image","# SDDM: which theme each config source selects, last one read wins","grep -rn \"Current=\" /etc/sddm.conf /etc/sddm.conf.d/ /usr/lib/sddm/sddm.conf.d/ 2>/dev/null","ls /usr/share/sddm/themes/caelestia/theme.conf","# Re-copy the wallpaper and the scheme, then log out","sudo /usr/local/bin/caelestia-greeter-sync # Plasma Login","sudo /usr/share/sddm/themes/caelestia/scripts/sync.sh # SDDM","```","Both greeters read their configuration when they start, so a change is visible at","the next logout rather than immediately.","### 7.7 Installer Window Rules","The installer writes three groups into `~/.config/kwinrulesrc`. `caelestia-opacity`","gives normal windows and dialogs an inactive opacity of 95 percent,","`caelestia-dialogs` forces centered placement on dialogs, and `caelestia-pip` keeps","windows whose title matches `Picture(-| )in(-| )[Pp]icture` above others. Opacity is","a per-activation-state key, so a window is dimmed only while it is not focused, and","the dialog rule is the one that can disagree with a placement policy chosen in","System Settings.","A group only takes effect if the index names it. `[General] rules=` is the list KWin","loads its rule groups from, and a group that is present in the file but missing from","that list is never loaded, and is removed the next time KWin saves the file. The","installer writes the list as the union of the entries that were already in it, every","group the file holds and its own three names, with `count` set to the number of","entries, so the user's own rules are named alongside ours and keep their order.","To read a value back:","```bash","kreadconfig6 --file kwinrulesrc --group caelestia-opacity --key opacityinactive","kreadconfig6 --file kwinrulesrc --group caelestia-dialogs --key placement","kreadconfig6 --file kwinrulesrc --group caelestia-pip --key above","kreadconfig6 --file kwinrulesrc --group General --key rules","```","To remove the rules, delete the three `[caelestia-...]` sections out of the file, or","delete the key that switches each group on. A group that is deleted has to leave the","index with it, or the list keeps a name whose group is gone and `count` no longer","matches it. `uninstall.sh` removes the keys, strips the three names out of the list,","rewrites `count`, and deletes both index keys once no name is left. KWin does not","watch kwinrulesrc, so the reload is not optional:","```bash","kwriteconfig6 --file kwinrulesrc --group caelestia-opacity \\","--key opacityinactiverule --delete","kwriteconfig6 --file kwinrulesrc --group caelestia-dialogs \\","--key placementrule --delete","kwriteconfig6 --file kwinrulesrc --group caelestia-pip --key aboverule --delete","qdbus6 org.kde.KWin /KWin reconfigure","```","Those commands delete each group's `*rule` key, which is the action. The match keys","are left behind, and a group that matches but carries no action is empty as far as","KWin is concerned: it discards such a rule once a window it matches has been","withdrawn, so the residue is harmless.","A window that is already open keeps what a rule forced on it. Opacity and keep-above","are set on the window itself, so an open window stays dimmed or pinned after the rules","are gone, until it is closed and reopened or another rule forces the value back. Only","windows created after the removal start clean.","The installer always applies the rules; `APPLY_WINDOW_RULES=false` is an override","for running the step by hand (`APPLY_WINDOW_RULES=false bash ./scripts/setup.sh`).","`WINDOW_OPACITY` changes the percentage the opacity rule writes."],"source":"docs/TROUBLESHOOTING.md — section 7 (KDE & Plasma Specific Issues)","title":"7. KDE & Plasma Specific Issues"},{"dl":515,"id":"DOC-TS-08","path":"DOC-TS-08.md","sentences":["### 8.1 Shell Not Visible After Install","The shell only runs at **next login**. After the summary screen, the installer asks: *\"Would you like to log out now? (y/N)\"*","If you chose not to log out:","1. Log out manually (`Super+Ctrl+Q` or KDE menu → Leave → Log Out)","2. Log back in","3. If the shell still doesn't appear, run: `caelestia shell -d`","### 8.2 Installer Exited Prematurely (Marker Check)","The outer `setup.sh` wrapper checks if `[installer] done (success)` appears in stderr:","| Condition | Warning |","|---|---|","| Exit 0 but elapsed < 3 seconds without marker | **\"INSTALLER EXITED PREMATURELY\"** |","| Exit 0 but elapsed > 3 seconds without marker | **\"INSTALLER EXITED UNEXPECTEDLY\"** |","### 8.3 CONFIRM_ARG Behavior","The configuration menu sets `CONFIRM_ARG` as `true`/`false`. The installer converts it per-script context:","- Some scripts use `-n \"$CONFIRM_ARG\"` (non-empty = auto-confirm)","- The installer writes an `[installer] done (success)` marker line to its stderr log, and `setup.sh` greps that log for it to decide whether the install succeeded (see `scripts/setup.sh`).","### 8.4 Stale Lock Files","If the script is killed with **SIGKILL** (not SIGTERM), lock files may persist:","| Lock File | Script |","|---|---|","| `${XDG_RUNTIME_DIR:-/tmp}/caelestia-setup.lock` | `setup.sh` |","| `${XDG_RUNTIME_DIR:-/tmp}/caelestia-update.lock` | `update.sh` |","**Always use Ctrl+C (SIGINT)** which is handled gracefully. Remove stale locks:","```bash","rm -f \"${XDG_RUNTIME_DIR:-/tmp}/caelestia-setup.lock\"","rm -f \"${XDG_RUNTIME_DIR:-/tmp}/caelestia-update.lock\"","```","### 8.5 Update.sh Fails","| Symptom | Cause |","|---|---|","| `git pull` fails | Uncommitted changes exist. The updater auto-stashes, but conflicts may remain. |","| Submodule update fails | Network issue or GitHub down. Retry later. |","| CMake configure fails | New dependencies added since last install. Check error output. |","### 8.6 Installer Stops After a System Upgrade","`00a-system-update.sh` upgrades the system first, and later steps compile and load the Caelestia","KWin plugin into the session that is **already running**. If the upgrade replaced `kwin`,","`plasma-workspace`, `libplasma`, `qt6-base` or `qt6-declarative`, the live session still holds the","old libraries in memory while the on-disk headers are new, so the installer stops and names the","packages that moved:","```","[ERR] The upgrade replaced packages the running session still has loaded in memory:","[ERR] had kwin 6.4.0-1","[ERR] now kwin 6.4.1-1","```","This is the partial-upgrade state Arch documents as \"do not keep using the session\", not a broken","install. Log out and back in (or reboot) and run the installer again: the upgrade is already","applied, so nothing is downloaded twice and the remaining steps run against a session that matches","the files on disk.","Choosing **ignore** at the prompt continues anyway. The plugin build may then fail with Wayland or","ABI errors that look unrelated to the upgrade.","### 8.7 Prebuilt Shell Download Is Rejected","`08-build-shell.sh` extracts the release tarball straight over `$HOME`, so it first checks the","download against the `.sha256` published beside it:","| Message | Meaning |","|---|---|","| `Prebuilt shell artifacts match the published checksum.` | Normal: the prebuilt archive is installed. |","| `No published checksum for ... - extracting without verification.` | The release predates checksums. The install continues. |","| `No prebuilt shell artifacts published for (Qt ) - falling back to a local build.` | The release carries no archive for this Qt feature version. The step builds locally instead. |","| `Checksum mismatch for ...` | The download was truncated or tampered with. The step falls back to building the shell locally. |","A mismatch is not fatal: the installer builds from source instead, which takes longer but cannot","unpack a damaged tree into `~/.local/lib/qt6/qml`.","The archive is also only used for the revision it was built from: `main` sitting on its remote","tip, or a checkout that is exactly the released tag (an update pinned to a version). A branch, a","stale `main`, or a checkout carrying commits of its own builds locally, because the archive would","replace that tree with the release's. `main` that has moved on since its last release cannot be","told apart from that release, so it is installed as the release its `version.env` names."],"source":"docs/TROUBLESHOOTING.md — section 8 (Post-Install Issues)","title":"8. Post-Install Issues"},{"dl":208,"id":"DOC-TS-09","path":"DOC-TS-09.md","sentences":["### 9.1 No Backups Available","Backups are stored in `$BUNDLE_DIR/backups/YYYYMMDD_HHMMSS/`. If you moved or deleted the repository, backups are gone.","### 9.2 konsave Restore Fails","If the `.knsv` archive is corrupted or konsave can't be installed:","- Falls back to manual restore of individual config files","- If `python3 -m venv` fails (missing `python3-venv`), theme data can't be restored","**Expected warning when restoring a Caelestia backup:**","> *\"The selected backup contains Caelestia configurations. Restoring this backup will NOT revert to a clean KDE desktop!\"*","### 9.3 Shell RC Files Not Cleaned","The uninstaller uses state files (`shellrc/bashrc.state`, etc.) to determine whether to restore or remove shell config files.","If these are missing (older installer version), a fallback `sed` cleanup removes `QML2_IMPORT_PATH` and `CAELESTIA_LIB_DIR` lines.","### 9.4 Package Removal Leaves Dependencies","Package removal is optional. It uses `yay -Rns` / `dnf remove` which does NOT remove:","- Dependencies pulled in automatically (unless `-s` handles it)","- Packages installed outside the defined lists","- `base-devel` or build tools that existed before install","### 9.5 Input Group Membership Persists","The uninstaller runs `sudo gpasswd -d $USER input`. This only works if the user was added to the group during installation, and takes effect on next login.","### 9.6 Failed Patches Tracking","Failed patches are logged to:","```text","$XDG_CACHE_HOME/caelestia-kde/failed_patches.txt","```","Possible entries:","- `Caelestia CLI Hyprctl Mock Patch`","- `Caelestia CLI Record/Dolphin Patch`","- `Caelestia CLI Theme Sequence Patch`","These are **cosmetic** — the shell works without them, but certain features (screenshot, recording, terminal colors) may be degraded."],"source":"docs/TROUBLESHOOTING.md — section 9 (Uninstall Issues)","title":"9. Uninstall Issues"},{"dl":144,"id":"DOC-TS-10","path":"DOC-TS-10.md","sentences":["### 10.1 Fixing caelestia updater (Recommended)","By deleting the build cache and the update checker cache:","```bash","rm -rf ~/.config/caelestia-update/repo ~/.cache/caelestia-update-repo","```","**Note:** This will have the updater clone the repo again which takes time according to your internet speed. Hence, the logs might seem stuck or tell you to restart the process, but just wait for it to finish.","### 10.2 Using update.sh","You can simply run `bash update.sh` in the cloned repo folder (~/caelestia-kde) to update to latest version.","### 10.3 Install latest version from repo","Run the following command to simply install the latest shell using installer.","```bash","curl -fsSL https://raw.githubusercontent.com/ladybug-me/caelestia-kde/main/install.sh | sh","```","- If it gives an error due to already present `~/caelestia-kde` directory in your pc, then remove that directory first and then run the above command.","**Make sure to copy the `backups/` folder somewhere and then put it back here after installation completes.**"],"source":"docs/TROUBLESHOOTING.md — section 10 (Update Issues)","title":"10. Update Issues"},{"dl":349,"id":"DOC-TS-11","path":"DOC-TS-11.md","sentences":["### System State Checks","```bash","# KWin reconfigure","qdbus6 org.kde.KWin /KWin reconfigure","# Check user services","systemctl --user list-units | grep -E 'caelestia|quickshell'","# Check KWin plugins","kwriteconfig6 --file kwinrc --group Plugins --key list","# Verify QML imports","qml6 -p ~/.config/quickshell/caelestia/shell.qml 2>&1 | head -30","```","### Caelestia-Specific Diagnostics","```bash","# Check if the shell binary was built","ls -la ~/.local/lib/qt6/qml/Caelestia/","# Check installed wallpaper plugin","kpackagetool6 --list -t Plasma/Wallpaper","# Read lock screen config","kreadconfig6 --file kscreenlockerrc --group Greeter --key WallpaperPlugin","# View failed packages log","cat $XDG_CACHE_HOME/caelestia-kde/failed_packages.txt 2>/dev/null","# View failed patches log","cat $XDG_CACHE_HOME/caelestia-kde/failed_patches.txt 2>/dev/null","# View installer build log","cat /tmp/caelestia_build.log 2>/dev/null | tail -60","# View installer stderr log","cat /tmp/caelestia_installer_err.log 2>/dev/null","```","### Network Diagnostics","```bash","# Test submodule availability","git ls-remote https://github.com/ladybug-me/caelestia-kde.git HEAD","# Test AUR access","curl -sI https://aur.archlinux.org/rpc/?v=5\\&type=info\\&arg[]=quickshell-git | head -5","```","### KDE Cache Refresh","```bash","# Rebuild desktop file cache","kbuildsycoca6 --noincremental","# Refresh desktop database","update-desktop-database ~/.local/share/applications/","# Restart Plasma shell (affects current session)","systemctl --user restart plasma-plasmashell","```","---","## Quick Reference: Common Fixes","| Problem | Quick Fix |","|---|---|","| Shell won't start | `quickshell -d -n -p ~/.config/quickshell/caelestia/shell.qml` |","| Lock screen not active | `kwriteconfig6 --file plasmashellrc --group \"Shell\" --key \"ShellPackage\" \"caelestia.desktop\"` |","| Stale lock file | `rm -f \"${XDG_RUNTIME_DIR:-/tmp}/caelestia-setup.lock\"` |","| Missing QML module | `export QML2_IMPORT_PATH=\"$HOME/.local/lib/qt6/qml\"` |","| No window thumbnails | `kbuildsycoca6 --noincremental && qdbus6 org.kde.KWin /KWin reconfigure` |","| Git submodule error | `git submodule update --init --recursive src/dots` |","| Colors not updating | Run `caelestia scheme set -n dynamic`, and check that `plasma-apply-colorscheme --list-schemes` names Matugen |","| Installer compiles but flashes/exits | Check `/tmp/caelestia_installer_err.log` |","| Recording not working | Verify `gpu-screen-recorder` is installed |","| Screenshot not working | Verify `spectacle` is installed |"],"source":"docs/TROUBLESHOOTING.md — section 11 (Diagnostic Commands Reference)","title":"11. Diagnostic Commands Reference"},{"dl":125,"id":"ISS-006","path":"ISS-006.md","sentences":["# ISS-006 — Bluetooth not working","State: CLOSED, stateReason COMPLETED · opened 2026-06-26 by Kyedae.","## Problem (original report, condensed)","Enabling bluetooth via quickshell widget, or the kde system settings does nothing, it turns on then turns off, nothing pairs.","- CachyOS","- Plasma Version 6.7","## Resolution","Participants' positions (paraphrased): the maintainers' and collaborators' points are summarized in the curated notes and tags on this page; the original wording lives at the source URL below.","## Thread summary (paraphrased)","9 comments by ladybug-me, planck4 between 2026-06-26 and 2026-09-09. Decisions and scope notes are reflected in the curated notes above; the full history lives at https://github.com/ladybug-me/caelestia-kde/issues/6."],"source":"issue #6 (CLOSED, stateReason COMPLETED) https://github.com/ladybug-me/caelestia-kde/issues/6","title":"Bluetooth not working"},{"dl":236,"id":"ISS-014","path":"ISS-014.md","sentences":["# ISS-014 — kde colour scheme auto sets to material you dark","State: CLOSED, stateReason COMPLETED · opened 2026-06-28 by 26heij.","## Problem (original report, condensed)","After running the setup.sh and prompting to keep my existing theme the colour scheme still changed to Material You Dark.","I changed it to custom theme i use in system settings and reran the setup.sh to check if it was an actual bug and again the colour schema changed to material you dark.","i changed it to my custom once again and did a **reboot and it changed again**.","I checked it with a logout and it aslo setted the colour scheme to material you dark.","Then i changed the colur scheme to material you Light and did a log out , login and again i was on material you Dark.","then i tried with other material you colors and and other colors and they were also replaced by Material You Dark after a logout login.","- Basically everytime **quickshell is being reloaded** (logout/in , reboot, running setup.sh) the the color ik kde is seted to **Material You Dark** color automatically.","- Also for every setup.sh run, that many material you colors are being installed.","3 run = 3 set of material you dark , light , dark(darker titlebar) , light(darker titlebar)","[image]","- Fedora 44","- KDE Plasma 6.7.1","## Resolution","Participants' positions (paraphrased): the maintainers' and collaborators' points are summarized in the curated notes and tags on this page; the original wording lives at the source URL below.","## Thread summary (paraphrased)","13 comments by 26heij, ladybug-me between 2026-06-28 and 2026-06-29. Decisions and scope notes are reflected in the curated notes above; the full history lives at https://github.com/ladybug-me/caelestia-kde/issues/14."],"source":"issue #14 (CLOSED, stateReason COMPLETED) https://github.com/ladybug-me/caelestia-kde/issues/14","title":"kde colour scheme auto sets to material you dark"},{"dl":476,"id":"ISS-120","path":"ISS-120.md","sentences":["# ISS-120 — Feat: AI-Powered Natural Language Settings Assistant","State: OPEN · opened 2026-07-11 by dr-strange15.","This thread is OPEN: there is no resolution. It is part of the corpus because it defines what the on-device assistant itself may claim to do — no more, no less.","## Proposal (original, condensed)","I think Caelestia-kde-dots is in a unique position to make desktop customization much more approachable by allowing users to configure the shell using natural language.","Instead of manually searching through Nexus or editing configuration files, users could simply describe what they want.","Examples:","- \"Make my bar thinner.\"","- \"Move the dock to the left.\"","- \"Increase the blur.\"","- \"Make everything feel more compact.\"","- \"Give the desktop a minimal look.\"","The assistant would interpret the request, convert it into structured configuration changes, and apply them through Caelestia's existing configuration system.","---","After looking through the project, it feels like most of the pieces already exist.","Caelestia already has:","- AI Assistant","- Ollama integration","- `ConfigObject` architecture","- Live configuration updates","- Nexus settings application","Right now these are mostly independent systems.","Connecting them together could make Caelestia one of the easiest and most intituve desktop environments on whole of linux to customize without introducing an entirely new subsystem.","---","The assistant should never modify configuration files directly.","Instead, it should only request changes through a controlled API.","The overall flow could look something like this:","```text","User","│","▼","AI Assistant","│","▼","Intent Parser","│","▼","Structured Tool Calls","│","▼","ConfigObject / …[truncated]","## Scope","Maintainer (ladybug-me, paraphrased): the AI assistant already routes shell handling through caelestia-cli but that path was not working at the time; a few tools (screenshot, get_weather, web_search, read_wbpg) worked, the rest were pending updates.","Maintainer direction (2026-09-22, paraphrased): the issue was handed over to contributor 0x0nYx, who was pointed at the shell's predefined agentic tools as the integration path.","Corpus note (curated from this thread): the on-device assistant in this repo stays on the narrow side of this proposal — it retrieves documentation and past resolutions and prints inert suggestions; it never parses natural-language requests into config writes (the settings layer is a separate module behind an explicit --apply).","Corpus note (2026-09-23 direction, open thread): the maintainer handed the issue to contributor 0x0nYx and pointed at the shell's predefined agentic tools; collaborator 0xSolanaceae wants to explore the Apertus AI model family (https://www.apertus-ai.org/) for the assistant, says assets need cutting down, and invited a PR; the model would NOT ship bundled with the shell (\"it'll have to be download","Per the collaborator on 2026-09-22, implementation \"has fallen to the backlog bc of all the more important features and bugfixes we need to ship first\".","No model choice, bundling decision, or in-shell API is settled — the thread is OPEN, with the assistant work currently backlogged behind higher-priority features and bugfixes.","## Thread summary (paraphrased)","18 comments by 0x0nYx, 0xSolanaceae, ladybug-me between 2026-07-11 and 2026-09-25. Decisions and scope notes are reflected in the curated notes above; the full history lives at https://github.com/ladybug-me/caelestia-kde/issues/120.","## Fetch reconciliation (2026-09-28)","Re-fetched live via the GitHub REST API (14 comments, issue still OPEN, unassigned,","labeled `feature`, last updated 2026-09-25T17:34:30Z). This corpus keeps only the","paraphrased summaries above; some early comments (including the handover discussion","of 2026-09-22, part of which the original author later deleted from the live thread)","are visible only in the issue's own history at the source URL."],"source":"issue #120 (OPEN) https://github.com/ladybug-me/caelestia-kde/issues/120","title":"Feat: AI-Powered Natural Language Settings Assistant"},{"dl":136,"id":"ISS-333","path":"ISS-333.md","sentences":["# ISS-333 — Shortcuts not working","State: CLOSED, stateReason COMPLETED · opened 2026-07-29 by MayoNas3.","## Problem (original report, condensed)","none of the shortcuts are working, and i did read issue #5 as well as the troubleshooting guide. I'm not sure what went wrong. also, I'm not sure what info to include, so I'll just send whatever I'm asked for - sorry.","```markdown","CachyOS","KDE Plasma 6.7.3","```","## Resolution","Participants' positions (paraphrased): the maintainers' and collaborators' points are summarized in the curated notes and tags on this page; the original wording lives at the source URL below.","## Thread summary (paraphrased)","11 comments by 0xSolanaceae, MayoNas3 between 2026-07-29 and 2026-07-29. Decisions and scope notes are reflected in the curated notes above; the full history lives at https://github.com/ladybug-me/caelestia-kde/issues/333."],"source":"issue #333 (CLOSED, stateReason COMPLETED) https://github.com/ladybug-me/caelestia-kde/issues/333","title":"Shortcuts not working"},{"dl":219,"id":"ISS-402","path":"ISS-402.md","sentences":["# ISS-402 — Error that causes Vesktop (discord) crash when using camera and/or screen share with audio","State: CLOSED, stateReason COMPLETED · opened 2026-08-01 by R0XX133.","## Problem (original report, condensed)","Configuration:","GPU: Nvidia Geforce RTX 4060","CPU: Intel Core i7-4790 (3.60hz)","OS: CachyOS","Kernel: 7.1.5-1-cachOS","RAM: 32GB","I've been running into an issue when I use vesktop,","if I stream with audio or turn on my camera, it'll freeze vesktop and I'm forced to restart the app.","If I stream without audio, it'll work fine sometimes","Issue seems to be only with Vesktop (haven't tried regular discord) since I tried it on the browser and worked flawlessly.","it started once I downloaded caelestia","1. Download vesktop","2. join a call","3. turn on camera or stream with audio","v2.2.2","CachyOS","## Resolution","Closed by PR #586 (MERGED).","Participants' positions (paraphrased): the maintainers' and collaborators' points are summarized in the curated notes and tags on this page; the original wording lives at the source URL below.","## Thread summary (paraphrased)","12 comments by 0xSolanaceae, Kyedae, R0XX133 between 2026-08-01 and 2026-08-04. Decisions and scope notes are reflected in the curated notes above; the full history lives at https://github.com/ladybug-me/caelestia-kde/issues/402."],"source":"issue #402 (CLOSED, stateReason COMPLETED) https://github.com/ladybug-me/caelestia-kde/issues/402","title":"Error that causes Vesktop (discord) crash when using camera and/or screen share with audio"},{"dl":130,"id":"ISS-409","path":"ISS-409.md","sentences":["# ISS-409 — Video wallpapers are not appearing","State: CLOSED, stateReason COMPLETED · opened 2026-08-03 by francisco-tato.","## Problem (original report, condensed)","Live wallpapers do not appear as the background (some are duplicated).","v2.2.4 (5fc7d98d Dev)","Garuda Linux","[attachment]","## Resolution","Participants' positions (paraphrased): the maintainers' and collaborators' points are summarized in the curated notes and tags on this page; the original wording lives at the source URL below.","## Thread summary (paraphrased)","11 comments by francisco-tato, ladybug-me between 2026-08-03 and 2026-08-04. Decisions and scope notes are reflected in the curated notes above; the full history lives at https://github.com/ladybug-me/caelestia-kde/issues/409."],"source":"issue #409 (CLOSED, stateReason COMPLETED) https://github.com/ladybug-me/caelestia-kde/issues/409","title":"Video wallpapers are not appearing"},{"dl":200,"id":"ISS-416","path":"ISS-416.md","sentences":["# ISS-416 — Launcher not opening on the correct screen and cant use alt tab when fullscreened on another monitor","State: CLOSED, stateReason COMPLETED · opened 2026-08-04 by Kyedae.","## Problem (original report, condensed)","This happens randomly but it happens everytime you fullscreen a video on another monitor, then u go to another monitor it keeps trying to open the launcher on the monitor that has the fullscreened video (it doesnt even pop up until u unfullscreen the video so it never shows), you also cant alt tab either to use the window switcher, basically all functionality breaks on the other monitor if somethi","Dev","Cachyos","## Resolution","Participants' positions (paraphrased): the maintainers' and collaborators' points are summarized in the curated notes and tags on this page; the original wording lives at the source URL below.","## Thread summary (paraphrased)","12 comments by Kyedae, WinTone01, ladybug-me between 2026-08-04 and 2026-08-04. Decisions and scope notes are reflected in the curated notes above; the full history lives at https://github.com/ladybug-me/caelestia-kde/issues/416."],"source":"issue #416 (CLOSED, stateReason COMPLETED) https://github.com/ladybug-me/caelestia-kde/issues/416","title":"Launcher not opening on the correct screen and cant use alt tab when fullscreened on another monitor"},{"dl":202,"id":"ISS-418","path":"ISS-418.md","sentences":["# ISS-418 — When quickshell crashes window switcher no longer shows windows, and if u have multiple monitors it doesnt open anything on the correct monitor anymore and it doesnt come back","State: CLOSED, stateReason COMPLETED · opened 2026-08-05 by Kyedae.","Curated note: the quickshell crash-dialog report was filed on 2026-08-05 (reporter Kyedae); the fix landed the same day and the issue was closed as completed.","## Problem (original report, condensed)","Title ^","Dev","CachyOS","## Resolution","Participants' positions (paraphrased): the maintainers' and collaborators' points are summarized in the curated notes and tags on this page; the original wording lives at the source URL below.","## Thread summary (paraphrased)","10 comments by Kyedae, ladybug-me between 2026-08-05 and 2026-08-05. Decisions and scope notes are reflected in the curated notes above; the full history lives at https://github.com/ladybug-me/caelestia-kde/issues/418."],"source":"issue #418 (CLOSED, stateReason COMPLETED) https://github.com/ladybug-me/caelestia-kde/issues/418","title":"When quickshell crashes window switcher no longer shows windows, and if u have multiple monitors it doesnt open anything on the correct monitor anymore and it doesnt come back"},{"dl":187,"id":"ISS-461","path":"ISS-461.md","sentences":["# ISS-461 — [CRITICAL] Weird crashing issue? need help indentifying","State: CLOSED, stateReason COMPLETED · opened 2026-08-12 by Kyedae.","## Problem (original report, condensed)","For some reason when im doing random things sometimes random apps crash, they primarily seem to be chromium apps, Helium, Spotify, Discord, Steam, they sometimes randomly crash when clicking or just interacting with things, its difficult to reproduce on the spot, but when i had codex scan my system for the crash issue it seems to be involving Caelestia and the apps are victims, ill attach images w","Latest Stable","CachyOS","[image]","[image]","## Resolution","Closed by PR #462 (MERGED), #496 (MERGED).","Participants' positions (paraphrased): the maintainers' and collaborators' points are summarized in the curated notes and tags on this page; the original wording lives at the source URL below.","## Thread summary (paraphrased)","11 comments by 0xSolanaceae, Kyedae between 2026-08-12 and 2026-08-12. Decisions and scope notes are reflected in the curated notes above; the full history lives at https://github.com/ladybug-me/caelestia-kde/issues/461."],"source":"issue #461 (CLOSED, stateReason COMPLETED) https://github.com/ladybug-me/caelestia-kde/issues/461","title":"[CRITICAL] Weird crashing issue? need help indentifying"},{"dl":129,"id":"ISS-528","path":"ISS-528.md","sentences":["# ISS-528 — Quickshell does not open","State: CLOSED, stateReason COMPLETED · opened 2026-08-24 by francisco-tato.","## Problem (original report, condensed)","I updated to the latest dev version and QuickShell gives an error when I open it.","Last Dev","Garuda Linux","[image]","## Resolution","Participants' positions (paraphrased): the maintainers' and collaborators' points are summarized in the curated notes and tags on this page; the original wording lives at the source URL below.","## Thread summary (paraphrased)","14 comments by WinTone01, francisco-tato, ladybug-me between 2026-08-24 and 2026-08-24. Decisions and scope notes are reflected in the curated notes above; the full history lives at https://github.com/ladybug-me/caelestia-kde/issues/528."],"source":"issue #528 (CLOSED, stateReason COMPLETED) https://github.com/ladybug-me/caelestia-kde/issues/528","title":"Quickshell does not open"},{"dl":321,"id":"ISS-565","path":"ISS-565.md","sentences":["# ISS-565 — Dual-updater state desync","State: OPEN (as of 2026-09-26).","## Problem (condensed from the original report)","Two independent updaters deploy to the same destinations but read from","different sources of truth:","- `update.sh` (top-level, dev workflow) uses `BUNDLE_DIR` = wherever the","script physically lives — the user's real git clone.","- `src/bin/caelestia-update` (installed to `~/.local/bin`, driven by the","Nexus \"Install Updates\" button) maintains a private sparse-checkout","clone at `~/.config/caelestia-update/repo`, does","`git reset --hard`/`git clean -fdx` THERE, and deploys from that","unrelated checkout.","Both paths end by writing","`~/.config/quickshell/caelestia/.current_commit` and `.update_branch`","from `git -C \"$BUNDLE_DIR\" rev-parse HEAD` — but `$BUNDLE_DIR` means a","different repository depending on which updater ran last.","`caelestia-check-updates` then diffs `.current_commit` against its own","bare mirror for the pending-commit badge, so alternating between the two","paths yields a commit hash that does not correspond to the user's real","clone — and the deploy from the shadow clone overwrites","`~/.config/quickshell/caelestia/*`, including discarding uncommitted","local edits in the real clone.","## What users see (the symptom this rule fingerprints)","- The Nexus Updates page reports a pending-commit count that does not","match `git -C ~/caelestia-dots-kde log` in the real clone.","- Uncommitted local changes in the real clone disappear after using","Nexus \"Install Updates\".","- `.current_commit` under `~/.config/quickshell/caelestia/` does not","match any commit in the user's own checkout.","## Fix direction","Pick ONE updater path and stick to it; commit or stash local edits","before any updater runs; verify the real clone with","`git -C rev-parse HEAD` against","`~/.config/quickshell/caelestia/.current_commit`. The issue is open","upstream — until it lands, users alternating between `update.sh` and the","Nexus button remain exposed to the desync."],"source":"issue #565 (OPEN) https://github.com/ladybug-me/caelestia-kde/issues/565","title":"Two independent update mechanisms share version-tracking state but pull from different repo checkouts"},{"dl":350,"id":"ISS-616","path":"ISS-616.md","sentences":["# ISS-616 — GPU usage and temperature are averaged across every /sys/class/drm/card* device, producing meaningless numbers on hybrid-graphics/multi-GPU systems","State: CLOSED, stateReason COMPLETED · opened 2026-09-05 by 0x0nYx.","## Problem (original report, condensed)","On my Ryzen APU + discrete AMD GPU desktop, the GPU usage widget shows roughly half of what either GPU is actually doing under load — running a game that pegs the discrete card at 100% while the iGPU sits idle at 0% displays as ~50% in the bar/Nexus resource widgets.","Root cause: `shell/plugin/src/Caelestia/Services/gpu.cpp`, `readGenericUsage()`:","```cpp","const QStringList paths = QDir(\"/sys/class/drm\").entryList({\"card*\"}, QDir::Dirs | QDir::NoDotAndDotDot);","qreal sum = 0.0; int count = 0;","for (const QString& card : paths) {","QFile f(QString(\"/sys/class/drm/%1/device/gpu_busy_percent\").arg(card));","if (f.open(...)) { sum += f.readAll().trimmed().toDouble(&ok); ++count; }","}","const qreal newPerc = count > 0 ? sum / count / 100.0 : 0.0;","```","This walks *every* `cardN` entry that exposes `gpu_busy_percent` and averages them into one number with no attempt to identify which card is the \"real\"/active GPU (discrete vs integrated, or primary vs secondary in a multi-GPU box).","The type-detection script a few lines up (`kTypeDetectScript`) already treats \"any card with `gpu_busy_percent`\" as sufficient to classify the system as `GENERIC`, so this isn't a one-GPU-assumption edge case — it's the intended code path for any non-Nvidia system, and it breaks the moment there's more than one DRM card.","The temperature path has the identical problem: `readGpuTemperature()` calls …[truncated]","## Resolution","Closed by PR #633 (CLOSED).","Participants' positions (paraphrased): the maintainers' and collaborators' points are summarized in the curated notes and tags on this page; the original wording lives at the source URL below.","## Thread summary (paraphrased)","13 comments by 0x0nYx, ladybug-me between 2026-09-05 and 2026-09-05. Decisions and scope notes are reflected in the curated notes above; the full history lives at https://github.com/ladybug-me/caelestia-kde/issues/616."],"source":"issue #616 (CLOSED, stateReason COMPLETED) https://github.com/ladybug-me/caelestia-kde/issues/616","title":"GPU usage and temperature are averaged across every /sys/class/drm/card* device, producing meaningless numbers on hybrid-graphics/multi-GPU systems"},{"dl":242,"id":"ISS-629","path":"ISS-629.md","sentences":["# ISS-629 — Installer permanently flips ccache in /etc/makepkg.conf","State: CLOSED (2026-09-06) · Severity: Medium.","## Problem (condensed from the original report)","Months after installing Caelestia the reporter traced unexpectedly long","AUR build times and ccache disk usage to `/etc/makepkg.conf` having","`ccache` enabled in `BUILDENV` — something they never enabled.","Root cause (quoted in the issue): `scripts/01-ensure-prereqs.sh` ran","```bash","sudo sed -i 's/!ccache/ccache/' /etc/makepkg.conf","```","during the one-time \"Ensure prerequisites\" step. That edits the","system-wide file governing every `makepkg`/AUR build on the machine —","silently, undocumented, and `uninstall.sh` never reverted it, so the","change outlived Caelestia entirely.","## What users see (the symptom this rule fingerprints)","- AUR/makepkg builds behave differently (ccache cache misses eating disk,","changed build output paths) on a machine where the user never enabled","ccache.","- `/etc/makepkg.conf` shows `ccache` (no `!`) in `BUILDENV` after a","Caelestia install.","## Fix direction (as discussed in the issue)","Check and re-disable if unwanted:","```bash","grep BUILDENV /etc/makepkg.conf","sudo sed -i 's/^BUILDENV=(\\([^)]*\\)ccache /\\1!ccache /' /etc/makepkg.conf","```","(distros package the exact syntax differently — inspect the file first).","The upstream fix removed the flip and disclosed the historical change;","users on older versions still carry the modified file."],"source":"issue #629 (CLOSED 2026-09-06) https://github.com/ladybug-me/caelestia-kde/issues/629","title":"Installer permanently enables ccache system-wide with no disclosure and no reversal on uninstall"},{"dl":163,"id":"ISS-641","path":"ISS-641.md","sentences":["# ISS-641 — Game fullscreen problem","State: CLOSED, stateReason COMPLETED · opened 2026-09-06 by AnubhavXP.","## Problem (original report, condensed)","I have some games that have gamescope in launch options for higher resolutions those games get launched in half of the screen bottom of the dekstop is still visible i tried hiding the taskbar it increased game window size but not fully.The game without gamescope code works fine .I dont know if its a bug .But i would like to know if there is a workaround to this","v2.3.2","fedora","## Resolution","Participants' positions (paraphrased): the maintainers' and collaborators' points are summarized in the curated notes and tags on this page; the original wording lives at the source URL below.","## Thread summary (paraphrased)","14 comments by AnubhavXP, WinTone01, ladybug-me between 2026-09-06 and 2026-09-06. Decisions and scope notes are reflected in the curated notes above; the full history lives at https://github.com/ladybug-me/caelestia-kde/issues/641."],"source":"issue #641 (CLOSED, stateReason COMPLETED) https://github.com/ladybug-me/caelestia-kde/issues/641","title":"Game fullscreen problem"},{"dl":153,"id":"ISS-738","path":"ISS-738.md","sentences":["# ISS-738 — Ambient color mode","State: CLOSED, stateReason COMPLETED · opened 2026-09-15 by ladybug-me · closed 2026-09-22 (implemented).","## Proposal (original, condensed)","Feature request (label: feature), filed by the maintainer herself:","> Implement YouTube like ambient color mode to appropriate parts of the shell like Window Info (overview) or Dock popups using colors from window previews.",">","> Algorithm: [Youtube-ambilight](https://github.com/Fefedu973/Youtube-ambilight)","## Resolution","Participants' positions (paraphrased): the maintainers' and collaborators' points are summarized in the curated notes and tags on this page; the original wording lives at the source URL below.","## Comment log","- (no comments on this issue; the only timeline events are `labeled` 2026-09-15 and `closed` by ladybug-me 2026-09-22 10:13)"],"source":"issue #738 (CLOSED, stateReason COMPLETED) https://github.com/ladybug-me/caelestia-kde/issues/738","title":"Ambient color mode"},{"dl":201,"id":"ISS-744","path":"ISS-744.md","sentences":["# ISS-744 — Brightness slider shows a moon icon instead of a sun","State: CLOSED, stateReason COMPLETED · opened 2026-09-16 by aroaxinping · closed 2026-09-21.","## Problem (original report, condensed)","> The brightness slider on the right side panel shows a moon icon instead of a sun icon.","The moon is normally associated with night light, not brightness.","The night light section in the settings panel already has its own toggle and temperature sliders, so having the moon on the brightness slider is confusing.",">","> Expected: the brightness slider should show a sun icon (or a brightness icon) to distinguish it from the night light controls.","(Two screenshots of the side panel were attached; image content is not quoted.)","## Resolution","Participants' positions (paraphrased): the maintainers' and collaborators' points are summarized in the curated notes and tags on this page; the original wording lives at the source URL below.","## Thread summary (paraphrased)","1 comment by 0xSolanaceae between 2026-09-21 and 2026-09-21. Decisions and scope notes are reflected in the curated notes above; the full history lives at https://github.com/ladybug-me/caelestia-kde/issues/744."],"source":"issue #744 (CLOSED, stateReason COMPLETED) https://github.com/ladybug-me/caelestia-kde/issues/744","title":"Brightness slider shows a moon icon instead of a sun"},{"dl":173,"id":"ISS-763","path":"ISS-763.md","sentences":["# ISS-763 — [Colors] color variant changes back to \"Tonal Spot\" afther restart.","State: CLOSED, stateReason COMPLETED · opened 2026-09-17 by MITSIKU.","## Problem (original report, condensed)","when changing a color variant afther rebooting it quickly changes back to Tonal Spot when logged in.","1. set color to any variant (e.g. vibrant)","2. reboot","3. login and you will see it briefly be vibrant before going back to being Tonal Spot","V2.4.2","CachyOS","## Resolution","Participants' positions (paraphrased): the maintainers' and collaborators' points are summarized in the curated notes and tags on this page; the original wording lives at the source URL below.","## Thread summary (paraphrased)","10 comments by MITSIKU, ladybug-me between 2026-09-17 and 2026-09-20. Decisions and scope notes are reflected in the curated notes above; the full history lives at https://github.com/ladybug-me/caelestia-kde/issues/763."],"source":"issue #763 (CLOSED, stateReason COMPLETED) https://github.com/ladybug-me/caelestia-kde/issues/763","title":"[Colors] color variant changes back to \"Tonal Spot\" afther restart."},{"dl":145,"id":"ISS-765","path":"ISS-765.md","sentences":["# ISS-765 — ~/.local/bin not in path for bash","State: CLOSED, stateReason COMPLETED · opened 2026-09-17 by ladybug-me · closed 2026-09-20.","## Problem (original report, condensed)","Bug (label: bug), filed by the maintainer as a tracking issue:","> Applicable only when installation done through `install.sh`","(The issue title is the report: `~/.local/bin` is not in `PATH` for bash after an `install.sh` install.)","## Resolution","Participants' positions (paraphrased): the maintainers' and collaborators' points are summarized in the curated notes and tags on this page; the original wording lives at the source URL below.","## Thread summary (paraphrased)","1 comment by ladybug-me between 2026-09-20 and 2026-09-20. Decisions and scope notes are reflected in the curated notes above; the full history lives at https://github.com/ladybug-me/caelestia-kde/issues/765."],"source":"issue #765 (CLOSED, stateReason COMPLETED) https://github.com/ladybug-me/caelestia-kde/issues/765","title":"~/.local/bin not in path for bash"},{"dl":165,"id":"ISS-773","path":"ISS-773.md","sentences":["# ISS-773 — Different paths for installation","State: CLOSED, stateReason COMPLETED · opened 2026-09-18 by ladybug-me · closed 2026-09-19.","## Problem (original report, condensed)","Tracking issue filed by the maintainer (no label), asking to follow upstream behaviour:","> Follow upstream behaviour.",">","> - by install.sh: ~/.config/quickshell/ & ~/.local/bin/","> - by caelestia-kde: /usr/bin & /etc/xdg/quickshell/caelestia/ for shell (confirm this one with upstream)","## Resolution","Participants' positions (paraphrased): the maintainers' and collaborators' points are summarized in the curated notes and tags on this page; the original wording lives at the source URL below.","## Thread summary (paraphrased)","1 comment by ladybug-me between 2026-09-19 and 2026-09-19. Decisions and scope notes are reflected in the curated notes above; the full history lives at https://github.com/ladybug-me/caelestia-kde/issues/773."],"source":"issue #773 (CLOSED, stateReason COMPLETED) https://github.com/ladybug-me/caelestia-kde/issues/773","title":"Different paths for installation"},{"dl":202,"id":"ISS-774","path":"ISS-774.md","sentences":["# ISS-774 — [Color] Verfiy terminal sequences bleed into notification","State: CLOSED, stateReason COMPLETED · opened 2026-09-18 by ladybug-me · closed 2026-09-20.","## Problem (original report, condensed)","Bug (label: blocked), filed by the maintainer as a verification tracking issue:","> Earlier affected distro was fedora.",">","> Currently, seen \"terminal sequences\" string being written into terminals on arch distros.","> NOTE: this one is irrelevant cause it only happens when running `tests/test_color.sh`",">","> Was fixed for old color engine, requires same for new one","(The symptom: color-engine terminal escape sequences bleeding into notification text — \"weird notifications containing a lot of numbers\" in the maintainer's words below. The old color-engine fix had to be redone for the new matugen engine.)","## Resolution","Participants' positions (paraphrased): the maintainers' and collaborators' points are summarized in the curated notes and tags on this page; the original wording lives at the source URL below.","## Thread summary (paraphrased)","2 comments by ladybug-me between 2026-09-18 and 2026-09-20. Decisions and scope notes are reflected in the curated notes above; the full history lives at https://github.com/ladybug-me/caelestia-kde/issues/774."],"source":"issue #774 (CLOSED, stateReason COMPLETED) https://github.com/ladybug-me/caelestia-kde/issues/774","title":"[Color] Verfiy terminal sequences bleed into notification"},{"dl":420,"id":"ISS-788","path":"ISS-788.md","sentences":["# ISS-788 — [FR] (?) Show taskbar notification indicators","State: CLOSED, stateReason COMPLETED · opened 2026-09-20 by probablyjassin · closed 2026-09-22 by 0xSolanaceae, 14 seconds after PR #808 merged.","Capture note: this issue was still OPEN as of the corpus frontier at the","time (#805, closed 2026-09-22T16:03:41Z); 0xSolanaceae closed it as","completed at 2026-09-22T19:59:41Z. Captured live via the GitHub REST API,","and the landed feature is verified offline in this checkout (dev @","70ee7da, v2.5.0) — see \"Landed in dev\" below.","## Problem (original report, condensed)","Participants' positions (paraphrased): the maintainers' and collaborators' points are summarized in the curated notes and tags on this page; the original wording lives at the source URL below.","## Resolution","Participants' positions (paraphrased): the maintainers' and collaborators' points are summarized in the curated notes and tags on this page; the original wording lives at the source URL below.","## Thread summary (paraphrased)","2 comments by 0xSolanaceae between 2026-09-21 and 2026-09-22. Decisions and scope notes are reflected in the curated notes above; the full history lives at https://github.com/ladybug-me/caelestia-kde/issues/788.","## Landed in dev","Verified offline in this checkout (dev @ 70ee7da115fde9012e28e393c73d274f55bd2dd7, `.github/version.env` says `VERSION=v2.5.0`):","- `shell/plugin/src/Caelestia/Services/launcherentry.{hpp,cpp}` — the new `LauncherEntry` QML singleton (`forApp` / `revision`), which registers the `com.canonical.Unity` name when nothing else owns it and watches the `com.canonical.Unity.LauncherEntry` `Update` signal (constants at launcherentry.cpp:18-19).","- `shell/plugin/src/Caelestia/Config/barconfig.hpp:173` — `CONFIG_PROPERTY(bool, showBadges, true)` inside `class BarDock` (per-bar, mounted via `CONFIG_SUBOBJECT(BarDock, dock)`).","- `shell/modules/nexus/pages/panels/taskbar/BarDock.qml:75-82` — the shipped Nexus `ToggleRow` \"Show app badges\" / \"Show the count, progress and urgency an app publishes for its dock icon\", bound to `Config.bar.dock.showBadges`.","- `shell/modules/bar/components/Dock.qml:630-634` — the `badge` reader (`Config.bar.dock.showBadges ?? true`, null when off) over `LauncherEntry.forApp(modelData.id)`, plus the urgency tint, count badge and progress bar visuals.","- `shell/modules/whatsnew/Entries.qml` — revision 24, id `dock_app_badges`, \"Dock App Badges\": \"Dock icons can now display the count, progress, and urgency published by running applications.","Configure it under Settings -> Panels -> Taskbar -> Dock.\"","Prompt-injection screening: no text in the captured issue or comments addresses an AI or tries to issue instructions to one — no fenced-block quarantine needed."],"source":"issue #788 (CLOSED, stateReason COMPLETED) https://github.com/ladybug-me/caelestia-kde/issues/788","title":"[FR] (?) Show taskbar notification indicators"},{"dl":183,"id":"ISS-790","path":"ISS-790.md","sentences":["# ISS-790 — [Color] Check Vibrant color pallette","State: CLOSED, stateReason COMPLETED · opened 2026-09-20 by ladybug-me · closed 2026-09-20.","## Problem (original report, condensed)","Filed by the maintainer as a check on the vibrant palette (the issue body is empty; the title is the report): does the `vibrant` color variant still look as strong as before the color-engine change?","(Context from the linked threads: this grew out of #763, where a user noticed the `vibrant` variant looked less \"strong\" on the new color engine and asked whether the old engine could be kept; the maintainer's replies here are the answer.)","## Resolution","Participants' positions (paraphrased): the maintainers' and collaborators' points are summarized in the curated notes and tags on this page; the original wording lives at the source URL below.","## Thread summary (paraphrased)","2 comments by ladybug-me between 2026-09-20 and 2026-09-20. Decisions and scope notes are reflected in the curated notes above; the full history lives at https://github.com/ladybug-me/caelestia-kde/issues/790."],"source":"issue #790 (CLOSED, stateReason COMPLETED) https://github.com/ladybug-me/caelestia-kde/issues/790","title":"[Color] Check Vibrant color pallette"},{"dl":149,"id":"ISS-791","path":"ISS-791.md","sentences":["# ISS-791 — Add color intensity slider","State: CLOSED, stateReason COMPLETED · opened 2026-09-20 by ladybug-me · closed 2026-09-21 (implemented).","## Proposal (original, condensed)","Feature request (label: feature), filed by the maintainer:","> Feature request as per #790 & conversation in #763 .","(A control for how intense/saturated the generated colors are — the ask behind the \"vibrant palette looks weaker on the new matugen engine\" discussion in those threads.)","## Resolution","Participants' positions (paraphrased): the maintainers' and collaborators' points are summarized in the curated notes and tags on this page; the original wording lives at the source URL below.","## Thread summary (paraphrased)","1 comment by 0xSolanaceae between 2026-09-21 and 2026-09-21. Decisions and scope notes are reflected in the curated notes above; the full history lives at https://github.com/ladybug-me/caelestia-kde/issues/791."],"source":"issue #791 (CLOSED, stateReason COMPLETED) https://github.com/ladybug-me/caelestia-kde/issues/791","title":"Add color intensity slider"},{"dl":163,"id":"ISS-792","path":"ISS-792.md","sentences":["# ISS-792 — Crashes","State: CLOSED, stateReason COMPLETED · opened 2026-09-21 by tahaub · closed 2026-09-21.","## Problem (original report, condensed)","> I had crashes, I don't have that much information, I'm new into this and I don't now waht to say...",">","> [log.qslog.log](https://github.com/user-attachments/files/32479387/log.qslog.log)","> [report.txt](https://github.com/user-attachments/files/32479388/report.txt)","(The report is intentionally vague — no pasted error text, only the two attached files. The maintainer's reply below did not quote any specific line from them either, so this doc deliberately records no signature beyond \"crashes\".)","## Resolution","Participants' positions (paraphrased): the maintainers' and collaborators' points are summarized in the curated notes and tags on this page; the original wording lives at the source URL below.","## Thread summary (paraphrased)","1 comment by ladybug-me between 2026-09-21 and 2026-09-21. Decisions and scope notes are reflected in the curated notes above; the full history lives at https://github.com/ladybug-me/caelestia-kde/issues/792."],"source":"issue #792 (CLOSED, stateReason COMPLETED) https://github.com/ladybug-me/caelestia-kde/issues/792","title":"Crashes"},{"dl":202,"id":"ISS-802","path":"ISS-802.md","sentences":["# ISS-802 — ai model integration","State: CLOSED · opened 2026-09-22 by 0x0nYx · closed 2026-09-22 (redirected to #120 by the maintainer).","This thread is CLOSED: the outcome is the maintainer's redirect to #120, where the contributor asked to continue (\"mention me in a comment in the #120\").","It stays in the corpus because it defines what the on-device assistant itself may claim to do — no more, no less.","## Proposal (original, condensed)","i m quite experienced in building llms and ai models, since for many users the model will be resource heavy, it has to be narrow ai, not like an LLM but still like that that means it will be narrow ai not like an LLM but still like that that means it will be quite good at solving easy to intermediate prblms on linux shell, any kde specific prblms, folder organisations, cleaning, issue reportings t","already told why it will be useful","## Scope","Maintainer (ladybug-me): \"Why don't you create & train a small model for #120 ?\" — i.e. any assistant work is scoped against the #120 feature thread.","Corpus note (curated from this thread): the on-device assistant claims only narrow troubleshooting help (docs + resolved issues), folder-size reporting guidance, and issue drafting.","It does not claim general LLM abilities and does not act on its own.","## Thread summary (paraphrased)","3 comments by 0x0nYx, ladybug-me between 2026-09-22 and 2026-09-22. Decisions and scope notes are reflected in the curated notes above; the full history lives at https://github.com/ladybug-me/caelestia-kde/issues/802."],"source":"issue #802 (CLOSED) https://github.com/ladybug-me/caelestia-kde/issues/802","title":"ai model integration"},{"dl":396,"id":"ISS-805","path":"ISS-805.md","sentences":["# ISS-805 — Lock screen fallback issue","State: CLOSED, stateReason COMPLETED · opened 2026-09-22 by Refiichi · closed 2026-09-22 (fix confirmed by the reporter).","Capture note: this issue was created and resolved after the corpus was","first assembled — it was still OPEN when the tracker was next snapshotted,","and the maintainer closed it as completed shortly after, before this","corpus doc was written. The state above is the state at capture time.","## Problem (original report, condensed)","> I just recently updated Caelestia KDE to the recent version v2.4.3 and I have encountered an issue where the lock screen falls back to the built-in lock screen despite the command `kreadconfig6 --file plasmashellrc --group \"Shell\" --key \"ShellPackage\"` outputs correctly as \"caelestia.desktop\" and the `/usr/lib/kscreenlocker_greet --testing` actually shows the caelestia lock screen.",">","> I checked errors related to kscreenlocker in journalctl and found that the module 'Caelestia.Services\" is not found.",">","> Aside from that, I couldn't see the caelestia SDDM theme, not sure if I did something wrong even though the installer's full log says its OK","Troubleshooting the reporter had already done (condensed): re-setting `ShellPackage` via `kwriteconfig6` (reads back correctly), reinstalling v2.4.3 (was working on v2.4.2), `kscreenlocker_greet --testing` works, reboot/relogin does not help.","Caelestia version v2.4.3, distro CachyOS.","## Resolution","Participants' positions (paraphrased): the maintainers' and collaborators' points are summarized in the curated notes and tags on this page; the original wording lives at the source URL below.","## Thread summary (paraphrased)","3 comments by Refiichi, ladybug-me between 2026-09-22 and 2026-09-22. Decisions and scope notes are reflected in the curated notes above; the full history lives at https://github.com/ladybug-me/caelestia-kde/issues/805.","## Landed in dev","Both halves of the maintainer's fix landed in dev via PR #806 (the upstream","2.5.0 port, merged 2026-09-22T16:43:44Z as f2f95ac2) — verbatim subjects from","`git log f8760cb0..f2f95ac2 --format='%h %s'` (verifiable offline in any dev","checkout):","- `33e4541f` fix: ensure caelestia env variables when systemd does not start the session","- `50278414` fix: sddm theme did not install when plasmalogin binary present too","Concretely, `scripts/08-build-shell.sh` now also writes the Plasma session","environment to `~/.config/plasma-workspace/env/caelestia.sh` (sourced by KDE","Plasma on session startup for KWin, `kscreenlocker_greet`, and graphical","applications), and TROUBLESHOOTING.md §3.2 documents both locations; the","login-screen detection table (§7.6) now tells Plasma Login from SDDM by","whether `plasmalogin.service` / `sddm.service` is active/enabled rather than","by the `command -v` probe. The maintainer's startscript snippet above remains","byte-verbatim."],"source":"issue #805 (CLOSED, stateReason COMPLETED) https://github.com/ladybug-me/caelestia-kde/issues/805","title":"Lock screen fallback issue"}],"n_docs":41,"params":{"b":0.75,"k1":1.5},"postings":{"006":{"15":1},"00a":{"11":1,"5":1},"01":{"19":2,"27":1},"014":{"16":1},"02":{"1":2,"7":1},"02a":{"9":2},"03":{"20":2,"35":1},"04":{"19":1,"20":1,"21":3},"05":{"22":4,"26":3},"06":{"15":2,"16":3,"27":1,"28":3},"07":{"17":2,"18":3},"08":{"1":2,"11":1,"19":3,"20":3,"21":3,"22":4,"23":3,"24":3,"4":2,"40":1,"6":1},"09":{"15":2,"17":7,"25":1,"26":3,"27":1,"28":3,"29":4,"30":4,"31":3,"32":4,"33":4,"34":4,"35":6,"36":4,"37":4,"38":4,"39":4,"40":5,"8":2},"0x0nyx":{"17":4,"26":2,"39":2},"0xsolanaceae":{"17":2,"18":1,"19":1,"23":1,"3":2,"30":1,"35":3,"37":1},"10":{"13":6,"22":1,"29":1,"31":1,"4":2,"6":2},"100":{"26":2},"101418":{"3":5},"11":{"14":3,"17":2,"18":1,"20":1,"23":1},"12":{"19":1,"21":1,"23":3},"120":{"17":2,"39":5},"127":{"4":3,"5":1},"13":{"16":1,"26":1,"29":1},"139":{"4":3},"14":{"16":1,"17":1,"24":1,"28":1,"35":1},"15":{"29":2},"16":{"30":1},"16px":{"1":1},"17":{"31":2,"32":1},"173":{"35":1},"1793d1":{"3":1},"18":{"17":1,"33":1,"34":2,"35":1},"19":{"33":3,"35":1},"1d99f3":{"3":1},"20":{"31":1,"32":3,"34":2,"35":1,"36":4,"37":1,"4":4},"2026":{"15":3,"16":3,"17":9,"18":3,"19":3,"20":3,"21":3,"22":4,"23":3,"24":3,"25":1,"26":3,"27":1,"28":3,"29":4,"30":4,"31":3,"32":4,"33":4,"34":4,"35":6,"36":4,"37":4,"38":4,"39":4,"40":5},"21":{"30":3,"35":1,"37":3,"38":4},"22":{"17":3,"29":2,"35":2,"39":4,"40":4},"22t16":{"35":1,"40":1},"22t19":{"35":1},"23":{"17":1},"24":{"24":3,"35":1},"25":{"17":1},"25t17":{"17":1},"26":{"15":2,"25":1},"26heij":{"16":2},"26px":{"1":1},"28":{"16":2,"17":1},"29":{"16":1,"18":3},"2fcaelestia":{"3":1},"30":{"14":1},"30z":{"17":1},"32479387":{"38":1},"32479388":{"38":1},"32gb":{"19":1},"333":{"18":2},"33e4541f":{"40":1},"34":{"17":1,"3":1},"38b24e7f":{"3":1},"402":{"19":2},"4060":{"19":1},"409":{"20":2},"416":{"21":2},"418":{"22":2},"41z":{"35":2},"42px":{"1":1},"43":{"40":1},"43db":{"3":1},"44":{"16":1},"44z":{"40":1},"461":{"23":2},"462":{"23":1},"4790":{"19":1},"496":{"23":1},"50":{"26":1},"500mbs":{"17":1},"50278414":{"40":1},"51a2da":{"3":1},"528":{"24":2},"55":{"1":1},"565":{"25":1},"586":{"19":1},"59":{"35":1},"5fc7d98d":{"20":1},"5g":{"4":1},"60":{"14":1},"60hz":{"19":1},"616":{"26":2},"629":{"27":1},"630":{"35":1},"633":{"26":1},"634":{"35":1},"64":{"1":1,"3":1},"641":{"28":2},"70ee7da":{"35":1},"70ee7da115fde9012e28e393c73d274f55bd2dd7":{"35":1},"738":{"29":1},"744":{"30":2},"75":{"35":1},"763":{"31":2,"36":1,"37":1},"765":{"32":2},"773":{"33":2},"774":{"34":2},"788":{"35":2},"790":{"36":2,"37":1},"791":{"37":2},"792":{"38":2},"80":{"10":1},"802":{"39":2},"805":{"35":1,"40":2},"806":{"40":1},"808":{"35":1},"82":{"35":1},"872b":{"3":1},"8c0ac23a44fd":{"3":1},"95":{"10":1},"9bd0cc":{"3":1},"abi":{"11":2},"abilities":{"39":1},"abort":{"5":1},"aborting":{"5":1},"aborts":{"5":1},"above":{"10":3,"13":1,"15":1,"16":1,"17":2,"18":1,"19":1,"20":1,"21":1,"22":1,"23":1,"24":1,"26":1,"28":1,"30":1,"31":1,"32":1,"33":1,"34":1,"35":1,"36":1,"37":1,"38":1,"39":1,"40":3},"aboverule":{"10":1},"absent":{"1":1},"accelerated":{"1":1},"acceleration":{"1":1},"accent":{"6":2},"access":{"10":1,"14":1},"according":{"13":1},"account":{"1":1,"6":1},"across":{"0":1,"26":4,"3":1,"6":1},"act":{"39":1},"action":{"10":2,"2":1,"3":1},"activated":{"0":1},"activation":{"10":1},"active":{"0":8,"10":2,"14":1,"2":1,"26":1,"40":1,"6":1,"8":1},"activeid":{"0":1},"activeoutputname":{"0":1},"activewindow":{"0":1},"acts":{"2":1},"actual":{"16":1},"actually":{"10":1,"26":1,"40":1},"adapting":{"1":1},"add":{"3":1,"37":4},"added":{"11":1,"12":1},"address":{"0":11},"addresses":{"35":1},"adds":{"10":1},"adjacent":{"0":2},"adjust":{"37":2},"advanced":{"3":1,"37":2},"af":{"6":1},"affected":{"34":1},"affects":{"14":1},"afther":{"31":5},"against":{"11":2,"25":2,"39":1,"6":1},"agentic":{"17":2},"ai":{"17":11,"35":1,"39":11},"air":{"5":1},"album":{"1":1},"algorithm":{"29":1},"align":{"3":1},"allowing":{"17":1},"allows":{"2":1},"alongside":{"10":1},"already":{"10":2,"11":2,"13":1,"17":3,"2":1,"26":1,"30":1,"38":2,"39":1,"40":1,"6":1},"alt":{"21":9,"3":2,"6":2},"alternating":{"25":2},"always":{"10":1,"11":1},"ambience":{"29":2},"ambient":{"29":11},"ambilight":{"29":4},"amd":{"26":1},"animated":{"1":1},"animations":{"0":1},"another":{"10":1,"2":2,"21":6,"3":1,"6":1,"8":1,"9":1},"ansi":{"8":1},"answer":{"36":1,"5":1},"answers":{"6":1},"anubhavxp":{"28":2},"anymore":{"22":4},"anything":{"10":1,"22":4,"9":1},"anyway":{"11":1},"apart":{"11":1},"apertus":{"17":4},"api":{"0":4,"17":3,"3":3,"35":1},"app":{"19":1,"2":4,"3":1,"35":8,"6":3,"8":1},"app2unit":{"5":2},"appear":{"11":1,"20":1,"6":2},"appearance":{"3":2},"appearing":{"20":6,"3":3},"appears":{"11":1,"6":2,"7":1,"8":2},"appid":{"0":1},"applet":{"1":1},"applicable":{"32":1},"application":{"17":1},"applications":{"14":1,"35":1,"40":1,"6":2},"applied":{"11":1,"6":5,"8":1},"applies":{"10":1,"2":1,"6":1},"apply":{"1":1,"10":2,"14":1,"17":2,"5":1,"6":5,"8":4},"applying":{"3":2,"6":6},"approach":{"0":2},"approachable":{"17":1},"appropriate":{"29":1},"apps":{"2":3,"23":7,"35":4,"6":1},"apt":{"9":2},"apu":{"26":1},"arch":{"11":1,"3":5,"34":3,"4":3,"5":3,"9":3},"architectural":{"0":1},"architecture":{"0":9,"1":7,"17":1,"2":3,"3":1},"archive":{"11":4,"12":1},"archlinux":{"14":1,"3":1},"arg":{"11":5,"14":1,"26":1},"aroaxinping":{"30":1},"around":{"0":2,"29":2},"array":{"0":1},"arriving":{"6":1},"art":{"1":1},"artifacts":{"11":2,"4":1},"aside":{"40":1},"ask":{"37":1},"asked":{"18":1,"36":1,"39":1},"asking":{"33":1},"asks":{"11":1},"aslo":{"16":1},"assembled":{"40":1},"asset":{"17":1,"4":2,"5":1},"assets":{"10":1,"17":1,"3":3},"assistant":{"17":25,"39":11},"associated":{"30":1},"assumption":{"26":1},"atim":{"5":1},"attach":{"23":1},"attached":{"30":1,"38":1},"attachment":{"20":1},"attachments":{"3":1,"38":2},"attempt":{"26":1},"attempted":{"9":1},"aubio":{"4":3},"audio":{"19":9,"20":2,"6":1},"aur":{"14":2,"27":7,"33":2,"5":6,"8":1,"9":3},"authentication":{"1":4},"authenticator":{"1":1},"author":{"17":1},"auto":{"11":2,"16":4,"4":1,"5":2,"9":1},"automatic":{"31":2},"automatically":{"1":4,"12":1,"16":1,"2":2,"7":1},"autostart":{"32":4,"5":1,"6":4,"7":2},"availability":{"14":1},"available":{"0":1,"12":1},"avatar":{"1":3,"7":3},"averaged":{"26":8},"averages":{"26":1},"avoid":{"8":1},"avoids":{"6":1},"back":{"1":3,"10":2,"11":4,"12":1,"13":1,"15":2,"2":3,"22":4,"3":1,"31":8,"40":4,"5":3,"6":4,"8":1},"backed":{"0":1},"backend":{"0":7,"1":1,"2":2},"background":{"0":2,"1":2,"10":2,"20":1},"backgrounds":{"1":1},"backlog":{"17":1},"backlogged":{"17":1},"backup":{"12":3},"backups":{"12":6,"13":1},"backward":{"0":1},"bad":{"10":1},"badge":{"1":1,"25":3,"3":10,"35":6},"badges":{"35":11},"bali10050":{"3":2},"bar":{"17":1,"22":2,"26":1,"3":1,"35":7,"6":1},"barconfig":{"35":1},"bardock":{"35":3},"bare":{"25":1,"3":1},"base":{"11":1,"12":1,"4":2},"based":{"0":3,"1":1,"3":1,"9":2},"bash":{"1":3,"10":6,"11":1,"13":3,"14":4,"27":2,"3":6,"32":9,"6":9,"7":1,"8":6,"9":4},"bashrc":{"12":1},"basically":{"16":1,"21":1},"bc":{"17":1},"beginning":{"0":1},"behave":{"27":1},"behavior":{"11":1},"behaviour":{"33":2},"behind":{"10":1,"17":2,"37":1,"5":1,"6":1,"9":4},"belongs":{"6":1},"below":{"15":1,"16":1,"18":1,"19":1,"20":1,"21":1,"22":1,"23":1,"24":1,"26":1,"28":1,"29":1,"30":1,"31":1,"32":1,"33":1,"34":2,"35":3,"36":1,"37":1,"38":2,"40":1},"beside":{"11":1},"between":{"15":1,"16":1,"17":1,"18":1,"19":1,"20":1,"21":1,"22":1,"23":1,"24":1,"25":2,"26":1,"28":1,"30":1,"31":1,"32":1,"33":1,"34":1,"35":1,"36":1,"37":1,"38":1,"39":1,"40":1,"6":1},"beyond":{"38":1},"bgmargin":{"1":2},"bgradius":{"1":3},"bin":{"10":2,"25":2,"32":9,"33":4,"6":4},"binary":{"14":1,"4":2,"40":1,"6":4},"binding":{"2":2,"8":1},"bindings":{"0":1,"2":1,"8":1},"binds":{"0":1},"bitbucket":{"3":1},"blank":{"6":3},"bleed":{"34":4},"bleeding":{"3":1,"34":1,"8":1},"blinker":{"2":1},"block":{"35":1},"blocked":{"34":1},"blocking":{"1":1,"7":1},"bluetooth":{"15":13},"bluez":{"15":4},"blur":{"1":3,"17":1},"blurred":{"1":1},"blurring":{"1":1},"body":{"36":1},"bool":{"0":5,"35":1},"boolean":{"0":3},"boost":{"37":2},"boot":{"10":1},"bottlenecks":{"1":1},"bottom":{"28":3},"bound":{"35":1},"box":{"26":1},"branch":{"10":1,"11":1,"18":2,"25":3,"3":1,"38":2},"breaks":{"21":1,"26":1},"breeze":{"1":3,"10":1,"7":5,"8":1},"bridge":{"0":7,"10":5},"briefly":{"31":1,"6":2},"brightness":{"30":17},"brings":{"0":1,"1":1},"broken":{"11":1,"18":2,"2":1,"24":2},"browse":{"3":1},"browser":{"19":1},"browsers":{"23":2},"brycensranch":{"5":1},"bt":{"15":2},"bug":{"16":1,"28":1,"3":1,"30":2,"32":2,"34":1,"4":1},"bugfixes":{"17":2},"build":{"1":2,"11":3,"12":1,"13":1,"14":2,"27":5,"4":21,"40":1,"6":1},"buildenv":{"27":6},"building":{"11":1,"39":1},"builds":{"1":1,"11":3,"27":5,"4":1,"9":1},"built":{"11":1,"14":1,"3":3,"40":5,"6":2},"bundle":{"12":1,"25":3,"7":1},"bundled":{"17":1},"bundling":{"17":1},"bus":{"0":6,"35":2},"busy":{"26":5},"button":{"25":2},"byte":{"40":1},"cache":{"12":1,"13":5,"14":6,"27":3,"4":2,"5":1,"6":1,"8":1},"cachos":{"19":1},"cachy":{"9":1},"cachyos":{"15":3,"18":1,"19":2,"21":1,"22":1,"23":1,"31":1,"40":3,"9":5},"caelestia":{"0":4,"1":17,"10":17,"11":6,"12":7,"13":8,"14":14,"15":1,"16":1,"17":8,"18":1,"19":2,"2":7,"20":1,"21":1,"22":1,"23":4,"24":3,"25":8,"26":2,"27":3,"28":1,"3":28,"30":1,"31":1,"32":3,"33":5,"34":1,"35":3,"36":1,"37":1,"38":3,"39":1,"4":5,"40":15,"5":4,"6":31,"7":12,"8":6,"9":2},"caelestiafetch":{"1":1},"caelestiafetchcard":{"1":1},"call":{"19":1},"calls":{"0":1,"17":1,"26":1,"6":1},"camera":{"19":10,"6":4},"cannot":{"10":1,"11":2,"6":1,"9":6},"canonical":{"35":4},"cant":{"21":7},"capabilities":{"0":1},"capture":{"2":1,"35":1,"40":2},"captured":{"35":2},"card":{"1":3,"26":11},"cardn":{"26":1},"cardradius":{"1":1},"cargo":{"5":1},"carries":{"10":1,"11":1},"carry":{"27":1},"carrying":{"11":1},"case":{"26":1},"cat":{"14":4,"4":1,"6":1,"8":1},"categories":{"2":1},"categorized":{"1":1},"cause":{"11":1,"26":1,"27":1,"34":1,"4":1,"5":2,"6":3,"7":1,"8":1},"causes":{"19":4,"4":1},"causing":{"6":1},"ccache":{"11":2,"27":17,"4":8},"celestelove":{"4":1,"5":2},"center":{"1":1,"3":1},"centered":{"1":1,"10":1},"central":{"0":1,"2":2},"certain":{"12":1},"cgtop":{"23":2},"change":{"10":2,"16":2,"2":1,"27":4,"36":1,"6":3},"changed":{"16":6,"27":3,"6":1},"changes":{"10":2,"11":1,"17":2,"25":3,"31":7,"5":1,"6":1},"changing":{"31":1},"chart":{"3":4},"cheatsheet":{"3":1},"check":{"11":2,"14":6,"16":1,"25":1,"27":1,"36":5,"4":3,"5":1,"6":3},"checked":{"16":1,"40":1},"checker":{"13":1},"checkout":{"11":2,"25":3,"35":2,"40":1,"9":1},"checkouts":{"25":3},"checks":{"11":2,"14":3,"3":1,"9":1},"checksum":{"11":5},"checksums":{"11":1},"choice":{"17":1},"choose":{"3":3},"choosing":{"11":1},"chose":{"11":1},"chosen":{"10":1},"chromium":{"23":3},"ci":{"3":1},"claim":{"17":1,"39":2},"claims":{"39":1},"class":{"0":2,"26":8,"35":1},"classify":{"26":1},"clean":{"10":1,"12":1,"22":2,"25":1},"cleaned":{"12":1},"cleaning":{"39":3},"cleans":{"2":1},"cleanup":{"12":1},"cli":{"10":1,"12":3,"17":3,"3":1,"6":1,"8":2},"clicking":{"23":1},"client":{"4":1},"clients":{"6":2},"clip":{"1":1,"5":2},"clipboard":{"3":1,"5":1},"clipped":{"1":1},"clock":{"1":2},"clockwidget":{"1":1},"clone":{"13":3,"25":13,"9":4},"cloned":{"13":1},"close":{"0":1},"closed":{"10":1,"15":1,"16":1,"18":1,"19":2,"20":1,"21":1,"22":2,"23":2,"24":1,"26":3,"27":1,"28":1,"29":3,"30":2,"31":1,"32":2,"33":2,"34":2,"35":4,"36":2,"37":2,"38":2,"39":3,"40":3},"closes":{"2":1},"closewindow":{"0":1},"clue":{"4":1},"cmake":{"11":1,"4":15},"cmakelists":{"3":1,"4":3},"code":{"26":1,"28":1},"codes":{"34":2},"codex":{"23":1},"collaborator":{"17":2},"collaborators":{"15":1,"16":1,"18":1,"19":1,"20":1,"21":1,"22":1,"23":1,"24":1,"26":1,"28":1,"29":1,"30":1,"31":1,"32":1,"33":1,"34":1,"35":2,"36":1,"37":1,"38":1,"40":1},"collision":{"0":1,"2":2},"collisions":{"2":1},"color":{"10":2,"16":4,"29":7,"3":4,"31":12,"34":12,"36":17,"37":8,"6":1},"colors":{"10":2,"12":1,"14":1,"16":7,"29":3,"3":4,"31":6,"36":4,"37":7,"6":19},"colorscheme":{"14":1,"6":5},"colour":{"16":7},"column":{"1":2},"colur":{"16":1},"com":{"13":1,"14":1,"15":1,"16":1,"17":1,"18":1,"19":1,"20":1,"21":1,"22":1,"23":1,"24":1,"26":1,"28":1,"29":1,"3":17,"30":1,"31":1,"32":1,"33":1,"34":1,"35":5,"36":1,"37":1,"38":3,"39":1,"40":1},"combinations":{"2":1},"combos":{"8":1},"come":{"0":1,"22":4,"6":1},"command":{"10":1,"13":2,"3":1,"4":4,"40":2,"6":4,"9":1},"commands":{"10":1,"14":5,"32":2,"7":1},"comment":{"29":1,"30":1,"32":1,"33":1,"37":1,"38":1,"39":1},"comments":{"15":1,"16":1,"17":3,"18":1,"19":1,"20":1,"21":1,"22":1,"23":1,"24":1,"26":1,"28":1,"29":1,"31":1,"34":1,"35":2,"36":1,"39":1,"40":1},"commit":{"25":13},"commits":{"11":1,"25":2},"common":{"14":1},"communicates":{"0":1,"2":1},"compact":{"17":1},"compatibility":{"0":1},"compilation":{"4":5},"compile":{"11":1,"4":2},"compiled":{"6":1},"compiler":{"4":1},"compiles":{"14":1,"4":1},"completed":{"15":1,"16":1,"18":1,"19":1,"20":1,"21":1,"22":2,"23":1,"24":1,"26":1,"28":1,"29":1,"30":1,"31":1,"32":1,"33":1,"34":1,"35":2,"36":1,"37":1,"38":1,"40":2},"completes":{"13":1},"component":{"0":2,"1":2,"2":1},"components":{"0":3,"1":2,"2":2,"35":1},"compositing":{"1":1},"compositor":{"1":2},"compositors":{"1":1},"concentric":{"1":1},"concerned":{"10":1},"concretely":{"40":1},"condensed":{"15":1,"16":1,"17":1,"18":1,"19":1,"20":1,"21":1,"22":1,"23":1,"24":1,"25":1,"26":1,"27":1,"28":1,"29":1,"30":1,"31":1,"32":1,"33":1,"34":1,"35":1,"36":1,"37":1,"38":1,"39":1,"40":2},"condition":{"1":1,"11":1},"conf":{"0":1,"10":7,"27":10,"6":1},"config":{"0":1,"1":1,"10":4,"12":2,"13":1,"14":3,"17":1,"2":2,"25":5,"3":1,"33":3,"35":5,"4":2,"40":1,"6":6,"8":3,"9":3},"configobject":{"17":2},"configuration":{"10":1,"11":1,"17":5,"19":1,"8":6},"configurations":{"12":1},"configure":{"11":1,"17":1,"35":1,"7":1},"configured":{"10":1,"2":1,"7":1,"9":3},"configures":{"8":1},"configuring":{"3":3},"confirm":{"11":6,"33":1},"confirmed":{"40":1},"conflict":{"0":1,"2":1,"6":1},"conflicts":{"11":1,"2":5,"5":1,"8":5},"confusing":{"30":1},"connecting":{"17":1},"consent":{"27":2},"const":{"0":14,"26":3},"constants":{"1":1,"35":1},"container":{"1":4},"containing":{"0":1,"34":1},"contains":{"0":2,"12":1},"content":{"29":2,"30":1,"9":1},"contents":{"1":2,"7":1},"context":{"11":1,"3":1,"36":1},"continue":{"39":1},"continues":{"11":2,"5":1,"9":1},"continuously":{"0":1},"contributor":{"17":2,"39":1},"control":{"30":2,"37":3},"controlled":{"17":1},"controls":{"1":1,"30":1},"conversation":{"37":1},"convert":{"17":1},"converts":{"11":1},"coordinator":{"2":1},"copied":{"10":1,"3":1},"copr":{"4":1,"5":6,"8":1},"copy":{"10":2,"13":1,"4":1},"core":{"19":1,"2":2},"corner":{"1":3},"corpus":{"17":4,"35":1,"39":2,"40":2},"correct":{"2":1,"21":4,"22":4},"correctly":{"40":2},"correspond":{"25":1},"corrupted":{"12":1,"6":1,"7":1},"cosmetic":{"12":1},"couldn":{"40":1},"count":{"10":3,"25":3,"26":4,"35":7,"8":2},"covered":{"0":1},"covers":{"0":1},"cp":{"1":1,"7":1},"cpp":{"2":2,"26":2,"35":2},"cpu":{"1":2,"19":1},"crash":{"0":1,"19":6,"2":2,"22":3,"23":9,"38":2,"6":1},"crashed":{"22":4,"6":2},"crashes":{"2":2,"22":4,"38":8,"7":1},"crashing":{"23":4,"38":2},"create":{"39":1,"6":1},"created":{"10":1,"40":1},"creates":{"0":1,"10":2},"createworkspace":{"0":1},"credits":{"3":1},"critical":{"23":4,"9":1},"crlf":{"5":5},"cross":{"0":1},"ctrl":{"11":2,"3":1},"curated":{"15":2,"16":2,"17":2,"18":2,"19":2,"20":2,"21":2,"22":3,"23":2,"24":2,"26":2,"28":2,"29":1,"30":2,"31":2,"32":2,"33":2,"34":2,"35":3,"36":2,"37":2,"38":2,"39":2,"40":2},"curl":{"13":1,"14":1,"3":1},"current":{"0":4,"10":1,"14":1,"25":6,"6":1},"currently":{"0":2,"17":1,"2":1,"34":1},"custom":{"16":2,"4":1},"customization":{"17":1},"customizations":{"2":1},"customize":{"17":1},"customshortcut":{"0":2,"2":1},"cutting":{"17":1},"cuz":{"17":1},"cvds7sfgajh3wihln72p8wzuoqt2k2f71zocgl":{"3":3},"cxx":{"4":1},"daemon":{"0":4,"10":1},"damaged":{"11":1},"dark":{"16":14,"3":2},"darker":{"16":2},"darkly":{"3":4,"5":1,"8":9},"dashboard":{"3":1},"data":{"0":1,"12":1,"2":1,"3":1,"39":2},"database":{"14":2},"date":{"1":1,"3":4,"5":1},"day":{"22":1},"db":{"5":1},"dbus":{"6":1},"dcmake":{"4":2},"dead":{"18":2},"debian":{"3":2,"9":2},"debug":{"14":2,"3":1,"4":2},"debugging":{"6":1},"decide":{"11":1},"decided":{"6":1},"decision":{"17":1},"decisions":{"15":1,"16":1,"17":1,"18":1,"19":1,"20":1,"21":1,"22":1,"23":1,"24":1,"26":1,"28":1,"30":1,"31":1,"32":1,"33":1,"34":1,"35":1,"36":1,"37":1,"38":1,"39":1,"40":1},"declarative":{"11":1,"4":1},"declared":{"0":1,"2":1},"declares":{"1":1},"decoration":{"8":2},"decorations":{"8":1},"decoupled":{"0":1},"default":{"1":3,"2":3,"6":4},"defaultenv":{"18":2},"defaults":{"0":1,"2":1},"defined":{"12":1,"2":1},"defines":{"17":1,"39":1},"defining":{"2":1},"degraded":{"12":1},"dekstop":{"28":1},"delete":{"1":1,"10":6,"7":1},"deleted":{"10":1,"12":1,"17":1},"deletes":{"10":1,"2":1,"6":1},"deleting":{"13":1},"deliberately":{"38":1},"dependencies":{"11":1,"12":4,"4":2},"dependency":{"4":1,"5":3,"6":1},"depending":{"25":1},"deploy":{"25":2,"7":1,"9":1},"deployed":{"1":1},"deployment":{"1":3,"9":1},"deploys":{"25":1},"derive":{"6":1},"derives":{"6":2},"describe":{"17":1},"description":{"0":1},"design":{"1":3,"3":2,"36":2},"desktop":{"0":9,"1":14,"10":4,"12":1,"14":4,"17":3,"26":1,"28":2,"3":2,"40":3,"6":12,"7":6,"8":1},"desktopid":{"0":2},"desktops":{"0":2,"6":1,"8":6},"despite":{"40":1},"destinations":{"25":1},"desync":{"25":4},"detail":{"0":1},"detailed":{"3":1},"details":{"0":1},"detected":{"4":1,"5":1},"detection":{"26":1,"40":1,"6":1},"detects":{"2":1},"determine":{"12":1},"dev":{"10":2,"14":4,"18":2,"20":1,"21":1,"22":1,"24":2,"25":1,"3":1,"35":4,"38":4,"40":3},"devel":{"12":1,"4":13},"developer":{"0":1,"1":1},"device":{"17":2,"26":5,"39":2},"diagnostic":{"14":5,"7":2},"diagnostics":{"14":4},"dialog":{"10":1,"22":3,"6":1},"dialogs":{"10":5},"didn":{"4":1,"6":1},"diff":{"0":1},"different":{"10":1,"25":5,"33":4,"8":2},"differently":{"27":2},"difficult":{"23":1},"diffs":{"25":1},"dimmed":{"10":2},"dir":{"11":4,"12":2,"14":1,"25":3,"33":2,"6":3,"7":1},"direct":{"1":1},"direction":{"17":4,"25":1,"27":1},"directly":{"0":3,"1":5,"17":1,"39":1,"6":1,"7":1},"directory":{"1":1,"10":1,"13":2,"4":1,"7":1,"9":1},"dirn":{"3":1},"dirs":{"26":1},"disable":{"10":1,"27":1,"3":1,"6":2},"disabled":{"10":3},"disables":{"10":1,"8":1},"disagree":{"10":1},"disappear":{"25":1},"disappeared":{"25":2},"disappears":{"6":1},"discarding":{"25":1},"discards":{"10":1},"disclosed":{"27":1},"disclosure":{"27":3},"discord":{"19":9,"23":3,"35":2},"discrete":{"26":3},"discussed":{"27":1},"discussion":{"17":1,"37":1},"disk":{"1":1,"11":6,"2":1,"27":4},"display":{"10":2,"35":1},"displays":{"1":1,"26":1},"distinguish":{"30":1},"distro":{"3":3,"34":1,"4":1,"40":1,"5":1},"distros":{"27":1,"34":1},"div":{"3":2},"dnf":{"12":1,"4":1,"5":2,"9":2},"doc":{"38":1,"40":1},"dock":{"1":2,"17":1,"29":3,"35":19},"docs":{"0":2,"3":5,"39":1},"doctor":{"6":1},"document":{"0":1,"1":1,"2":1},"documentation":{"0":1,"17":1},"documents":{"11":1,"40":1},"dodge":{"28":4},"doesn":{"10":1,"11":1,"5":1,"6":4},"doesnt":{"21":1,"22":8},"dolphin":{"12":1},"don":{"10":1,"2":1,"38":2,"39":1},"done":{"11":2,"32":1,"40":1},"dont":{"28":1},"dos2unix":{"5":5},"dot":{"2":2,"35":2},"dotfiles":{"3":3},"dots":{"1":1,"14":1,"17":1,"25":1,"3":7,"9":5},"double":{"0":1},"download":{"11":3,"19":1},"downloaded":{"11":1,"17":1,"19":1},"downloads":{"5":1,"9":1},"dr":{"17":1},"drafting":{"39":1},"drive":{"3":1},"driven":{"25":1},"drives":{"0":1,"6":1},"drm":{"26":9},"dual":{"25":3},"due":{"13":1},"duplicated":{"20":3},"dynamic":{"14":1,"3":1,"6":2},"dynamically":{"0":1},"e95420":{"3":1},"earlier":{"34":1},"early":{"17":1},"easiest":{"17":1},"easily":{"2":1},"easy":{"39":1},"eating":{"27":3},"edge":{"26":1,"3":1},"editing":{"17":1,"2":1},"edits":{"25":4,"27":1},"effect":{"10":2,"12":1,"27":2,"6":7},"effects":{"6":1},"either":{"21":1,"26":1,"38":1},"elapsed":{"11":2},"electron":{"35":2},"element":{"3":1},"elevation":{"36":2},"eliminating":{"1":1},"else":{"35":1},"elsewhere":{"4":1},"emoji":{"3":1},"empty":{"10":1,"11":1,"22":2,"36":1,"9":5},"enable":{"0":1,"3":1},"enabled":{"10":2,"27":3,"40":1,"6":2},"enables":{"27":3,"4":1,"5":1,"6":1},"enabling":{"15":1},"encountered":{"40":1},"end":{"0":1,"25":1},"ending":{"5":1},"endings":{"5":1},"endpoint":{"20":2},"engine":{"31":2,"34":6,"36":7,"37":1},"enough":{"6":1},"ensure":{"27":2,"4":1,"40":1},"enter":{"3":1},"entirely":{"17":1,"27":1,"6":1},"entries":{"10":2,"12":1,"35":1,"6":1},"entry":{"1":1,"26":1},"entrylist":{"26":1},"env":{"11":1,"35":1,"40":4,"6":3},"environment":{"0":1,"32":2,"40":3,"6":8,"9":1},"environments":{"17":1},"err":{"11":3,"14":2,"4":2,"9":1},"error":{"1":1,"11":1,"13":1,"14":1,"19":4,"24":3,"38":1,"4":3,"7":1,"9":1},"errornointernet":{"5":1},"errors":{"11":1,"4":2,"40":1,"5":1},"escape":{"34":5,"8":1},"etc":{"10":5,"12":1,"2":1,"27":6,"33":3,"39":1},"even":{"21":1,"40":1},"events":{"29":1},"every":{"10":2,"16":1,"26":5,"27":1,"3":1,"6":8,"9":1},"everything":{"17":1},"everytime":{"16":1,"21":1},"evolution":{"0":1},"exact":{"27":1},"exactly":{"0":1,"11":1,"8":1},"examples":{"17":1},"executing":{"0":1},"exist":{"11":1,"17":1,"6":1,"7":2},"existed":{"12":1},"existing":{"16":1,"17":1,"2":1,"9":2},"exists":{"6":2},"exit":{"11":2,"4":6,"5":1,"6":1},"exited":{"11":5},"exits":{"14":1},"expandable":{"1":1},"expected":{"12":1,"30":1,"6":2,"7":1},"expects":{"17":1},"experienced":{"39":1},"explicit":{"17":1},"explore":{"17":1},"export":{"14":1,"6":2,"9":4},"exposed":{"0":1,"25":1},"exposes":{"1":1,"26":1},"external":{"0":1},"extra":{"5":1},"extracting":{"11":1},"extracts":{"11":1},"f2f95ac2":{"40":2},"f8760cb0":{"40":1},"face":{"1":3,"7":2},"fail":{"10":1,"11":1,"5":2,"6":1,"9":1},"failed":{"12":5,"14":4,"3":1,"4":2,"5":6,"8":3,"9":1},"fails":{"10":1,"11":6,"12":2,"15":2,"4":4,"5":4,"6":1,"7":1,"9":6},"failure":{"5":3,"9":2},"failures":{"5":2,"9":1},"fake":{"0":2},"fallback":{"1":1,"12":1,"40":6,"9":1},"fallen":{"17":1},"falling":{"11":1},"falls":{"1":1,"11":1,"12":1,"40":3,"5":3,"6":1,"8":1},"false":{"10":2,"11":1,"6":2,"8":1},"family":{"17":1},"far":{"10":1},"fastblur":{"1":1},"fatal":{"11":1,"4":1,"5":1},"favor":{"10":1},"fdd9":{"3":1},"fdx":{"25":1},"feat":{"17":4},"feature":{"11":1,"17":1,"29":4,"35":3,"37":5,"39":1},"features":{"12":1,"17":2,"2":1,"4":1},"fedora":{"16":1,"28":1,"3":5,"34":3,"4":5,"5":4,"9":2},"fedoraproject":{"3":1},"feeds":{"2":1},"feel":{"17":1},"feels":{"17":1},"fefedu973":{"29":1},"fenced":{"35":1},"fetch":{"1":1,"17":1,"9":2},"fetched":{"17":1,"9":1},"fetches":{"9":1},"ffmpeg":{"5":2},"fields":{"0":1},"file":{"1":3,"10":12,"11":1,"14":5,"2":6,"27":3,"33":2,"40":1,"5":1,"6":4,"7":4,"8":2},"filed":{"22":1,"29":1,"32":1,"33":1,"34":1,"36":1,"37":1},"files":{"1":1,"10":1,"11":5,"12":6,"17":2,"2":1,"3":1,"38":3,"4":3,"6":1,"7":2},"finally":{"9":1},"find":{"4":2},"fine":{"19":1,"28":1},"fingerprint":{"1":4},"fingerprints":{"25":1,"27":1},"finish":{"13":1},"first":{"11":2,"13":1,"17":1,"2":1,"27":1,"40":1,"9":1},"fix":{"14":1,"22":1,"25":1,"27":2,"3":1,"34":1,"4":1,"40":4,"5":1,"6":3},"fixed":{"34":1,"38":4},"fixes":{"14":1,"4":1,"5":1},"fixing":{"13":1},"flash":{"16":2},"flashes":{"14":1,"6":4},"flashing":{"20":2},"flawlessly":{"19":1},"flickers":{"6":1},"flip":{"27":1},"flips":{"15":2,"27":1},"floating":{"0":1},"flow":{"17":1},"focus":{"6":1},"focused":{"0":1,"10":1,"6":1},"focuses":{"0":1},"focuswindow":{"0":1},"folder":{"13":2,"39":2,"9":1},"follow":{"33":2,"6":1},"followed":{"9":1},"following":{"0":1,"13":1},"fonts":{"3":1},"forapp":{"35":2},"force":{"2":1},"forced":{"10":1,"19":1,"9":1},"forces":{"10":2},"forecast":{"1":1},"fork":{"10":1},"format":{"40":1},"formatted":{"0":1,"1":1},"found":{"32":2,"4":6,"40":4,"6":1},"four":{"9":1},"fr":{"35":4},"fractional":{"0":1},"francisco":{"20":2,"24":2},"free":{"11":2},"freedesktop":{"6":1},"freeze":{"19":3,"6":3},"freezes":{"19":4,"6":3},"fresh":{"6":1},"friendly":{"0":1},"front":{"0":1},"frontend":{"2":1},"frontier":{"35":1},"frosted":{"1":1},"fssl":{"13":1,"3":1},"full":{"0":2,"15":1,"16":1,"17":1,"18":1,"19":1,"20":1,"21":1,"22":1,"23":1,"24":1,"26":1,"28":1,"3":1,"30":1,"31":1,"32":1,"33":1,"34":1,"35":1,"36":1,"37":1,"38":1,"39":1,"40":2,"6":1},"fullscreen":{"0":4,"21":3,"28":6},"fullscreened":{"21":8},"fully":{"28":1},"functionality":{"21":1},"fusion":{"5":5},"game":{"26":1,"28":10},"games":{"28":4},"gamescope":{"28":6},"gapped":{"5":1},"garbage":{"34":2},"garbled":{"8":3},"garuda":{"20":1,"24":3},"gave":{"2":1},"gcc":{"4":5},"geforce":{"19":1},"general":{"10":4,"39":1,"4":1},"generated":{"37":1,"6":1},"generates":{"5":1,"6":1},"generic":{"26":1},"gesture":{"6":1},"gestures":{"0":1},"get":{"17":1,"28":1},"getting":{"6":1},"git":{"11":1,"14":5,"24":2,"25":6,"40":1,"5":5,"9":9},"github":{"11":1,"14":1,"15":1,"16":1,"17":3,"18":1,"19":1,"20":1,"21":1,"22":1,"23":1,"24":1,"26":1,"28":1,"29":1,"3":14,"30":1,"31":1,"32":1,"33":1,"34":1,"35":3,"36":1,"37":1,"38":3,"39":1,"40":1,"9":1},"githubusercontent":{"13":1,"3":1},"gitmodules":{"9":1},"give":{"17":1},"given":{"2":1},"gives":{"10":1,"13":1,"24":1},"glass":{"1":1},"global":{"0":4,"18":2,"9":2},"globalshortcut":{"0":8,"2":6,"8":1},"globalshortcutdispatcher":{"0":2,"2":5},"glow":{"29":4},"go":{"21":1,"3":1},"going":{"31":1},"gone":{"10":2,"12":1},"gonna":{"17":1},"good":{"39":1},"google":{"3":1},"governing":{"27":1},"gpasswd":{"12":1},"gpl":{"3":3},"gpu":{"1":1,"14":1,"19":1,"26":30,"5":2,"6":4},"gpus":{"26":2},"grace":{"1":1},"gracefully":{"0":1,"11":1},"grants":{"6":1},"graphical":{"40":1,"6":1},"graphics":{"26":6},"greater":{"17":1},"greet":{"1":5,"40":5,"6":3,"7":2},"greeter":{"1":14,"10":7,"14":1,"7":8},"greeters":{"10":1},"greeting":{"1":1},"greetingpill":{"1":1},"grep":{"10":1,"14":1,"27":1},"greps":{"11":1},"grew":{"36":1},"group":{"1":3,"10":21,"12":4,"14":3,"40":1,"7":4,"8":2},"groups":{"1":1,"10":3,"2":1},"gtk":{"3":2},"gui":{"3":1},"guidance":{"39":1},"guide":{"18":1},"guidelines":{"1":1},"guides":{"3":1},"gunuqnte3ey14fx":{"3":3},"h264":{"5":1},"haidir":{"3":1},"half":{"26":3,"28":5},"halves":{"40":1},"hand":{"10":1,"6":2,"9":1},"handed":{"17":2,"6":1},"handle":{"6":1},"handled":{"1":1,"11":1},"handles":{"0":1,"12":1,"2":2,"4":1},"handling":{"1":1,"17":1},"handover":{"17":1},"hangs":{"6":1},"happening":{"6":1},"happens":{"21":2,"34":1},"hard":{"25":1,"9":1},"hardware":{"1":2},"harmless":{"10":1},"hash":{"25":1},"haven":{"19":1},"head":{"14":3,"25":2,"3":1},"headers":{"11":1},"heals":{"7":1},"heavily":{"0":2},"heavy":{"39":1},"height":{"0":1,"1":1},"helium":{"23":1},"help":{"23":4,"39":1,"40":1},"helper":{"10":2},"helpers":{"3":1},"hence":{"13":1},"herself":{"29":1},"hgfs":{"9":1},"hhmmss":{"12":1},"hiding":{"28":1},"high":{"2":1},"higher":{"17":1,"28":1},"historical":{"27":1},"history":{"15":1,"16":1,"17":2,"18":1,"19":1,"20":1,"21":1,"22":1,"23":1,"24":1,"26":1,"28":1,"3":6,"30":1,"31":1,"32":1,"33":1,"34":1,"35":1,"36":1,"37":1,"38":1,"39":1,"40":1},"holds":{"10":1,"11":1},"home":{"1":1,"10":1,"11":1,"12":1,"14":3,"4":2,"5":1,"6":7,"8":1},"hood":{"2":1},"hook":{"10":1},"hops":{"0":1},"horz":{"0":1},"hotkey":{"2":1},"hour":{"1":1},"hovering":{"2":1},"hpp":{"2":4,"35":2},"href":{"3":1},"http":{"9":7},"https":{"13":1,"14":2,"15":1,"16":1,"17":2,"18":1,"19":1,"20":1,"21":1,"22":1,"23":1,"24":1,"26":1,"28":1,"29":1,"3":26,"30":1,"31":1,"32":1,"33":1,"34":1,"35":1,"36":1,"37":1,"38":3,"39":1,"40":1,"9":2},"hub":{"2":1},"hybrid":{"26":6},"hyprctl":{"0":5,"12":1},"hyprland":{"0":5,"2":1,"3":2},"i7":{"19":1},"icon":{"1":4,"3":2,"30":16,"35":1},"icons":{"22":4,"35":3,"6":1},"icture":{"10":1},"id":{"0":5,"10":1,"35":2},"identical":{"26":1,"6":1},"identify":{"26":1},"idle":{"26":1},"ignore":{"11":1},"ignored":{"10":1},"igpu":{"26":1},"ik":{"16":1},"ill":{"23":1},"im":{"23":1},"image":{"10":4,"16":1,"23":2,"24":1,"3":1,"30":1,"6":1,"7":2},"images":{"23":1},"img":{"3":7},"immediately":{"10":1,"2":1,"6":1,"7":1},"implement":{"29":1},"implementation":{"1":1,"17":1},"implemented":{"29":1,"37":1},"import":{"12":1,"14":1,"40":2,"6":4},"important":{"17":1,"2":1},"imports":{"14":1},"inactive":{"10":1},"include":{"10":1,"18":1},"including":{"17":1,"25":1},"increase":{"17":1,"4":1},"increased":{"28":1},"indentifying":{"23":4},"independent":{"17":1,"25":4},"index":{"0":3,"10":3,"2":1},"indexed":{"0":1},"indexes":{"9":1},"indicators":{"35":8},"individual":{"12":1},"individually":{"5":1},"inert":{"17":1},"info":{"1":1,"14":1,"18":1,"29":1},"information":{"0":1,"1":1,"23":1,"38":1},"init":{"14":1,"9":1},"initially":{"0":1},"inject":{"0":1},"injection":{"0":1,"10":3,"35":1},"injects":{"10":1},"inline":{"3":1},"inner":{"1":1},"input":{"1":1,"10":2,"12":4,"21":2},"inside":{"0":1,"10":2,"35":1},"inspect":{"27":1},"inspects":{"0":1},"install":{"10":2,"11":10,"12":1,"13":5,"25":4,"27":1,"3":9,"32":5,"33":13,"4":9,"40":1,"5":6,"6":5,"9":1},"installation":{"1":1,"12":1,"13":1,"3":4,"32":1,"33":4,"4":1,"5":1,"9":2},"installed":{"10":2,"11":2,"12":2,"14":3,"16":1,"25":1,"4":2,"5":1,"6":3,"8":1,"9":2},"installer":{"1":1,"10":8,"11":14,"12":1,"13":1,"14":5,"27":6,"3":5,"4":9,"40":1,"5":5,"6":2,"8":2,"9":3},"installing":{"27":1},"instance":{"0":1},"instead":{"1":1,"11":2,"17":3,"30":5,"6":1,"7":2},"instructions":{"35":1},"instructs":{"1":1},"int":{"0":3,"26":1},"integer":{"0":1},"integrated":{"26":1},"integration":{"0":1,"1":1,"17":2,"39":4,"4":1},"intel":{"19":1},"intended":{"26":1},"intense":{"37":1},"intensity":{"36":2,"37":10},"intent":{"17":1},"intentionally":{"38":1},"interact":{"0":1},"interacting":{"23":1},"interactive":{"1":1},"interface":{"1":1,"2":1,"6":1},"interfaces":{"0":1,"1":1},"interim":{"0":1},"intermediate":{"39":1},"internals":{"6":1},"internet":{"13":1},"interpret":{"17":1},"interrupted":{"4":1},"intituve":{"17":1},"introducing":{"17":1},"introspect":{"6":1},"introspectable":{"6":1},"invited":{"17":1},"invokables":{"0":2},"involved":{"0":1},"involving":{"23":1},"io":{"3":5},"ipc":{"0":2},"irrelevant":{"34":1},"isn":{"26":1,"6":1},"iss":{"15":1,"16":1,"17":1,"18":1,"19":1,"20":1,"21":1,"22":1,"23":1,"24":1,"25":1,"26":1,"27":1,"28":1,"29":1,"30":1,"31":1,"32":1,"33":1,"34":1,"35":1,"36":1,"37":1,"38":1,"39":1,"40":1},"issue":{"11":1,"17":4,"18":1,"19":2,"22":1,"23":5,"25":1,"27":2,"29":1,"3":1,"32":2,"33":1,"34":1,"35":3,"36":1,"39":4,"40":6,"5":1},"issues":{"10":3,"11":3,"12":3,"13":3,"15":1,"16":1,"17":1,"18":1,"19":1,"20":1,"21":1,"22":1,"23":1,"24":1,"26":1,"28":1,"3":2,"30":1,"31":1,"32":1,"33":1,"34":1,"35":1,"36":1,"37":1,"38":1,"39":2,"4":3,"40":1,"5":5,"6":5,"7":3,"8":3,"9":3},"item":{"1":1},"join":{"19":1},"journal":{"40":2},"journalctl":{"14":2,"40":1,"6":3},"js":{"0":2},"json":{"0":3,"1":1,"10":1,"2":4,"3":3,"6":1,"8":2},"kbuildsycoca6":{"14":4,"6":1},"kde":{"0":9,"1":13,"10":13,"11":1,"12":2,"13":3,"14":8,"15":2,"16":9,"17":2,"18":2,"19":1,"2":6,"20":1,"21":1,"22":1,"23":1,"24":1,"25":1,"26":1,"28":1,"3":17,"30":1,"31":1,"32":1,"33":4,"34":1,"35":1,"36":1,"37":1,"38":1,"39":2,"40":3,"5":2,"6":18,"7":6,"8":9,"9":2},"kdecoration2":{"8":2},"kdeglobals":{"10":1,"6":2,"8":1},"keep":{"10":2,"11":1,"16":1},"keeps":{"10":3,"17":1,"2":1,"21":1,"38":2,"6":3,"8":2},"kept":{"0":1,"36":1,"9":2},"kernel":{"19":1},"key":{"0":3,"1":3,"10":11,"14":3,"2":4,"40":1,"6":1,"7":4,"8":2},"keybind":{"3":1},"keybinds":{"0":1,"18":2,"2":4,"3":5},"keybindsdefaults":{"2":2},"keybindsmodel":{"0":2,"2":6},"keyboard":{"0":3,"10":1,"18":2,"8":1},"keyd":{"8":1},"keys":{"10":3,"2":3,"8":1},"keystrokes":{"2":1},"kf6":{"4":3},"kf6windowsystem":{"4":1},"kglobalaccel":{"0":4,"18":2,"2":3,"4":4,"8":3},"kglobalacceld":{"8":1},"killed":{"11":1,"2":1},"kmixrc":{"8":1},"kmy":{"6":1},"know":{"28":2},"known":{"5":1},"knsv":{"12":1},"konsave":{"12":4},"konsole":{"6":3},"kpackage":{"1":4},"kpackagestructure":{"1":1},"kpackagetool6":{"1":1,"14":1},"kpipewire":{"4":3},"kreadconfig6":{"10":5,"14":1,"40":3,"7":3},"krohnkite":{"10":4,"3":1},"krohnkiteenabled":{"10":1},"kscreen":{"6":1},"kscreenlocker":{"1":7,"40":10,"6":3,"7":2},"kscreenlockerrc":{"1":1,"14":1,"7":5},"kservice":{"6":1},"ktypedetectscript":{"26":1},"kwin":{"0":16,"1":3,"10":21,"11":4,"14":6,"2":1,"3":1,"40":1,"6":14,"8":3},"kwinactivewindowbridge":{"0":6,"22":2},"kwindowsystem":{"4":3},"kwinrc":{"10":1,"14":1,"8":2},"kwinrulesrc":{"10":9},"kwinworkspacestate":{"0":6},"kwriteconfig6":{"1":3,"10":3,"14":2,"40":1,"7":5,"8":2},"kyedae":{"15":1,"19":1,"21":2,"22":3,"23":2},"la":{"10":1,"14":1,"7":1},"label":{"0":1,"29":1,"32":1,"33":1,"34":1,"37":1},"labelcolor":{"3":5},"labeled":{"17":1,"29":1},"ladybug":{"13":1,"14":1,"15":2,"16":2,"17":3,"18":1,"19":1,"20":2,"21":2,"22":2,"23":1,"24":2,"26":2,"28":2,"29":2,"3":8,"30":1,"31":2,"32":3,"33":3,"34":3,"35":1,"36":3,"37":2,"38":2,"39":3,"40":2},"lagging":{"0":1},"landed":{"22":1,"35":3,"40":2},"lands":{"25":1},"landscape":{"1":1},"language":{"17":8,"3":1},"last":{"10":1,"11":2,"17":1,"24":1,"25":1,"6":2},"later":{"11":2,"17":1,"3":3,"9":1},"latest":{"13":5,"23":1,"24":1},"launch":{"28":3},"launched":{"28":1,"6":1},"launcher":{"21":9,"3":2},"launcherentry":{"35":7},"launches":{"28":2},"launching":{"6":1},"layer":{"17":1},"layout":{"1":3,"3":3},"layouts":{"1":1},"ldd":{"4":1},"lead":{"3":1},"leak":{"23":2,"8":1},"leave":{"10":1,"11":1},"leaves":{"12":1,"3":1},"left":{"1":1,"10":2,"17":1,"3":4,"6":1,"7":1},"leftover":{"6":1},"legacy":{"0":2,"10":1,"7":1},"legend":{"3":4},"leloubil":{"5":1},"lens":{"3":1},"less":{"17":1,"36":3,"39":1},"level":{"2":1,"25":1},"lib":{"1":1,"10":1,"11":1,"12":1,"14":2,"3":1,"4":1,"40":1,"6":6,"7":1},"libcava":{"4":3,"5":4},"libkwin":{"6":1},"libpam":{"4":1},"libpipewire":{"4":1},"libplasma":{"11":1},"libpulse":{"4":2},"libqalculate":{"4":3},"libraries":{"11":1,"4":1},"library":{"4":3,"8":2},"libs":{"4":1},"license":{"3":6},"light":{"16":3,"29":2,"3":1,"30":7},"like":{"0":1,"11":1,"17":2,"2":3,"28":1,"29":4,"30":2,"39":4},"likely":{"4":1,"6":1},"limitations":{"39":2},"line":{"11":1,"3":1,"38":1,"5":2},"lines":{"12":1,"26":1},"link":{"6":1},"linked":{"36":1,"6":1},"linux":{"17":1,"20":1,"24":1,"3":3,"39":1,"5":1},"list":{"0":4,"10":5,"14":4,"2":1,"6":1,"8":1,"9":1},"listed":{"5":1},"listened":{"0":1},"lists":{"0":1,"12":1,"3":1,"6":2,"9":2},"live":{"1":2,"11":1,"17":3,"20":5,"23":2,"35":1,"6":5},"livepreviews":{"6":1},"lives":{"15":2,"16":2,"17":1,"18":2,"19":2,"20":2,"21":2,"22":2,"23":2,"24":2,"25":1,"26":2,"28":2,"29":1,"30":2,"31":2,"32":2,"33":2,"34":2,"35":3,"36":2,"37":2,"38":2,"39":1,"40":2},"ll":{"17":1,"18":1,"19":2},"llm":{"39":3},"llms":{"39":1},"lm":{"4":3},"load":{"1":1,"11":1,"26":1,"4":1},"loaded":{"0":1,"10":1,"11":1,"6":2,"7":1},"loading":{"0":1,"2":1,"6":3},"loads":{"0":3,"10":2,"2":2,"4":1,"6":1},"loadscript":{"10":1},"local":{"0":1,"1":5,"10":3,"11":2,"14":3,"25":6,"32":9,"33":1,"4":2,"6":8,"7":4},"locally":{"11":3},"located":{"1":2},"locations":{"33":2,"40":1,"6":1},"lock":{"1":15,"11":11,"14":4,"40":17,"7":12},"lockbg":{"1":1},"locked":{"1":1},"locking":{"1":1},"locks":{"1":1,"11":1},"lockscreen":{"1":7,"7":3},"lockscreenui":{"1":1,"7":1},"log":{"10":1,"11":8,"14":7,"16":1,"25":1,"29":1,"3":1,"38":4,"4":4,"40":2,"5":1,"6":2},"logged":{"12":1,"31":1,"5":1},"logic":{"0":1,"2":1},"login":{"10":11,"11":1,"12":1,"16":2,"31":5,"40":2,"6":6,"7":1},"logo":{"1":1,"3":7},"logocolor":{"3":4},"logout":{"10":1,"16":5},"logs":{"13":1,"14":2,"3":1,"5":1},"long":{"27":1},"longer":{"10":1,"11":1,"22":4},"look":{"11":1,"17":2,"36":1,"6":1},"lookandfeeltool":{"8":1},"looked":{"36":1},"looking":{"17":1},"looks":{"37":1,"4":1},"loop":{"6":1},"loops":{"6":1},"lost":{"25":2},"lot":{"34":3},"ls":{"10":2,"14":2,"7":1},"m3":{"1":2},"machine":{"27":2},"main":{"0":1,"1":1,"11":3,"13":1,"3":2},"maintainer":{"17":3,"29":1,"3":1,"32":1,"33":1,"34":2,"36":2,"37":1,"38":1,"39":3,"40":3},"maintainers":{"15":1,"16":1,"18":1,"19":1,"20":1,"21":1,"22":1,"23":1,"24":1,"26":1,"28":1,"29":1,"30":1,"31":1,"32":1,"33":1,"34":1,"35":2,"36":1,"37":1,"38":1,"40":1},"maintains":{"25":1},"maintenance":{"3":1},"make":{"13":1,"17":4,"4":3,"5":1},"makepkg":{"27":12,"5":1,"9":1},"makes":{"6":1},"manage":{"0":1,"2":1},"management":{"0":4,"6":1},"manager":{"0":3,"10":1,"2":1,"3":1,"6":2,"9":1},"managers":{"10":1},"manages":{"0":1,"1":1,"2":3,"8":1},"manifest":{"1":1},"manual":{"1":1,"12":1,"6":1,"8":1},"manually":{"0":1,"11":1,"17":1,"4":1,"5":1,"6":2},"many":{"0":1,"16":1,"39":1},"map":{"0":2},"mapped":{"1":1},"markdown":{"18":1},"markdownlint":{"3":1},"marker":{"11":4},"masked":{"10":1},"match":{"10":1,"11":1,"25":2},"matches":{"10":4,"11":1,"6":1},"matching":{"1":1},"material":{"1":1,"16":20,"36":4,"6":7},"materialyou":{"6":1},"materialyoucolor":{"36":2},"matugen":{"14":1,"34":3,"36":2,"37":3,"5":6,"6":4},"maximized":{"0":3},"maximizes":{"0":1},"maximizewindow":{"0":1},"maximum":{"0":1},"may":{"10":1,"11":3,"12":1,"17":1,"39":1,"4":3,"5":3,"8":2},"mayonas3":{"18":2},"md":{"0":4,"3":4,"40":1},"md034":{"3":1},"meaning":{"11":1},"meaningless":{"26":4},"means":{"25":1,"39":2,"4":1,"6":3,"9":2},"mechanisms":{"25":3},"media":{"1":2,"3":2},"mediacard":{"1":1},"medium":{"27":1},"membership":{"12":1},"memory":{"11":4,"23":4},"mention":{"39":1},"menu":{"11":2,"3":2,"8":1},"merged":{"19":1,"23":2,"35":1,"40":1},"merges":{"0":1},"message":{"11":1,"9":1},"meta":{"2":1,"28":2,"8":1},"metadata":{"1":1,"4":4,"9":1},"meters":{"1":1},"methods":{"0":2},"mid":{"3":1},"might":{"13":1},"minimal":{"17":1},"minimizes":{"0":1},"minimizewindow":{"0":1},"minute":{"1":1},"mirror":{"25":1,"9":8},"mirrors":{"9":4},"misc":{"0":1},"mismatch":{"11":2,"25":2,"4":1},"misses":{"27":3},"missing":{"10":1,"12":2,"14":1,"35":2,"4":10,"5":1,"6":2,"7":2,"8":2},"mitsiku":{"31":2},"mkdir":{"1":1},"mnt":{"9":1},"mocha":{"6":1},"mock":{"0":2,"12":1},"mode":{"14":2,"29":7,"3":1},"model":{"17":8,"39":6},"modeldata":{"35":1},"models":{"39":1},"modern":{"4":1},"modes":{"9":1},"modified":{"27":1},"modify":{"17":1},"module":{"14":1,"17":1,"4":6,"40":3},"modules":{"0":1,"35":3,"4":2},"moment":{"26":1},"monitor":{"0":1,"21":14,"22":4,"6":1},"monitors":{"0":1,"22":4},"monochrome":{"3":1},"months":{"27":1},"moon":{"30":13},"mostly":{"17":1},"mounted":{"35":1,"9":1},"move":{"17":1},"moved":{"11":2,"12":1},"moves":{"0":1},"mp4":{"6":1},"mpris":{"1":1},"much":{"17":1,"38":1,"4":1},"multi":{"0":1,"21":2,"26":7},"multiple":{"22":4},"name":{"0":5,"10":2,"35":1},"named":{"10":1},"names":{"10":3,"11":2,"14":1,"6":1},"narrow":{"17":1,"39":7},"native":{"0":13,"1":4,"10":1,"6":1,"7":1,"9":1},"natively":{"0":3},"natural":{"17":8},"need":{"17":2,"23":4,"5":1},"needed":{"3":1,"35":1,"4":1,"5":2},"needs":{"10":1,"6":1,"9":1},"neither":{"9":1},"nested":{"1":2},"network":{"11":1,"14":1,"5":1,"9":6},"never":{"10":1,"17":2,"2":1,"21":1,"27":3,"3":1},"new":{"0":1,"11":2,"17":1,"2":1,"34":2,"35":1,"36":3,"37":1,"38":1,"6":1},"newer":{"10":1},"newperc":{"26":1},"next":{"0":1,"10":3,"11":1,"12":1,"2":1,"3":1,"38":2,"40":1,"6":1,"7":1},"nextdesktop":{"0":1},"nexus":{"0":3,"17":2,"2":3,"25":8,"26":1,"3":5,"35":2,"6":1},"nfi4jxcozai26mlgx2jeashmrd1pis09clm":{"3":3},"night":{"30":7},"nl":{"17":2},"noconfirm":{"5":2},"nodotanddotdot":{"26":1},"noincremental":{"14":2,"6":1},"non":{"1":1,"11":1,"26":1,"7":1,"9":1},"none":{"10":1,"18":1,"6":1},"nopasswd":{"10":1},"normal":{"10":1,"11":1,"9":1},"normalization":{"5":2},"normally":{"2":1,"30":1},"note":{"13":1,"17":2,"22":1,"3":1,"34":1,"35":1,"39":1,"4":1,"40":1},"notes":{"15":3,"16":3,"17":2,"18":3,"19":3,"20":3,"21":3,"22":3,"23":3,"24":3,"26":3,"28":3,"29":1,"3":1,"30":3,"31":3,"32":3,"33":3,"34":3,"35":4,"36":3,"37":3,"38":3,"39":2,"40":3},"nothing":{"11":1,"15":4,"18":2,"35":1,"5":1,"6":5},"noticed":{"36":1},"notifdock":{"1":1},"notification":{"1":2,"3":1,"34":7,"35":8},"notifications":{"34":7},"null":{"10":1,"14":4,"35":1},"number":{"10":1,"26":1,"8":3},"numbered":{"3":1},"numbers":{"26":4,"34":5},"nvidia":{"19":3,"26":1,"6":1},"ofc":{"17":1},"offline":{"35":2,"40":1,"9":1},"offset":{"0":1,"6":1},"ok":{"26":1,"40":1},"old":{"10":1,"11":1,"34":2,"36":1,"6":1},"older":{"12":1,"27":1,"4":1,"6":2},"ollama":{"17":3},"one":{"10":3,"17":1,"25":1,"26":3,"27":1,"33":1,"34":2,"35":1,"40":2,"6":4,"9":1},"onto":{"1":1,"3":1},"opacity":{"10":8},"opacityinactive":{"10":1},"opacityinactiverule":{"10":1},"opacitymask":{"1":1},"open":{"10":2,"17":5,"21":1,"22":4,"24":7,"25":2,"26":1,"3":1,"35":1,"40":1},"opencv":{"6":1},"opened":{"15":1,"16":1,"17":1,"18":1,"19":1,"20":1,"21":1,"22":1,"23":1,"24":1,"26":1,"28":1,"29":1,"30":1,"31":1,"32":1,"33":1,"34":1,"35":1,"36":1,"37":1,"38":1,"39":1,"40":1},"opening":{"21":4},"opens":{"21":2},"optimized":{"0":2},"optional":{"1":1,"10":1,"12":1},"options":{"28":3},"order":{"10":1},"org":{"1":1,"10":5,"14":3,"17":1,"3":4,"6":3,"7":1,"8":6},"organisations":{"39":1},"organizes":{"2":1},"original":{"15":2,"16":2,"17":2,"18":2,"19":2,"2":1,"20":2,"21":2,"22":2,"23":2,"24":2,"25":1,"26":2,"27":1,"28":2,"29":2,"3":1,"30":2,"31":2,"32":2,"33":2,"34":2,"35":3,"36":2,"37":2,"38":2,"39":1,"40":2},"os":{"19":1},"osd":{"8":7},"others":{"10":1},"otherwise":{"4":1},"ours":{"10":1},"outcome":{"39":1},"outer":{"1":1,"11":1},"outlines":{"1":1},"outlived":{"27":1},"output":{"0":3,"11":1,"27":1,"6":1,"7":1,"8":3},"outputname":{"0":1},"outputs":{"40":1},"outside":{"12":1},"overall":{"17":1},"overhead":{"0":1},"overridden":{"2":1},"override":{"0":1,"10":1},"overrides":{"0":1,"2":2},"overview":{"1":1,"2":2,"29":3,"3":2,"6":1},"overwrites":{"25":1},"overwrote":{"25":2},"owns":{"35":1},"package":{"1":6,"12":2,"27":1,"3":2,"33":8,"4":5,"5":8,"7":4,"8":1,"9":2},"packaged":{"1":1,"6":1},"packages":{"1":2,"11":4,"12":1,"14":2,"5":9,"7":1,"8":1},"pacman":{"24":2,"4":1,"5":3,"6":1,"9":4},"padding":{"1":1},"page":{"15":1,"16":1,"18":1,"19":1,"20":1,"21":1,"22":1,"23":1,"24":1,"25":1,"26":1,"28":1,"29":1,"30":1,"31":1,"32":1,"33":1,"34":1,"35":2,"36":1,"37":1,"38":1,"40":1},"pages":{"35":1},"pairing":{"15":4},"pairs":{"15":1},"palette":{"1":2,"36":3,"37":1,"5":1,"6":8},"palettes":{"6":1},"pallette":{"36":4},"pam":{"1":3,"4":2},"panel":{"2":1,"30":5},"panels":{"3":1,"35":2},"paraphrased":{"15":2,"16":2,"17":4,"18":2,"19":2,"20":2,"21":2,"22":2,"23":2,"24":2,"26":2,"28":2,"29":1,"30":2,"31":2,"32":2,"33":2,"34":2,"35":3,"36":2,"37":2,"38":2,"39":1,"40":2},"parse":{"25":2},"parser":{"17":1},"parses":{"17":1},"part":{"17":2},"partial":{"11":3,"4":1,"5":1},"participants":{"15":1,"16":1,"18":1,"19":1,"20":1,"21":1,"22":1,"23":1,"24":1,"26":1,"28":1,"29":1,"30":1,"31":1,"32":1,"33":1,"34":1,"35":2,"36":1,"37":1,"38":1,"40":1},"parts":{"29":1},"party":{"1":1},"paru":{"24":2},"password":{"1":2},"passwordpill":{"1":1},"past":{"17":1,"9":1},"pasted":{"38":1},"patch":{"10":1,"12":3,"8":1},"patches":{"12":5,"14":2,"8":1},"path":{"12":1,"14":1,"17":2,"25":1,"26":2,"32":11,"40":2,"6":7},"paths":{"25":2,"26":2,"27":1,"33":8},"pause":{"20":2},"pc":{"13":1},"pegs":{"26":1},"pending":{"17":1,"25":6},"pentagon":{"1":1},"per":{"10":1,"11":1,"17":1,"3":2,"35":1,"37":1,"6":3},"percent":{"10":1,"26":7},"percentage":{"10":1},"performance":{"0":1},"performed":{"1":1},"permanently":{"2":1,"27":4},"persist":{"11":1,"5":2},"persistence":{"0":1,"5":1},"persists":{"12":1},"pgrep":{"6":1},"physically":{"25":1},"pick":{"25":1},"picker":{"3":1},"picks":{"10":1},"picture":{"1":1,"10":1,"3":2,"7":1},"pictures":{"6":2},"pid":{"6":2},"pidof":{"6":1},"pieces":{"17":1},"pill":{"1":2},"pills":{"6":5},"pinned":{"10":1,"11":1},"pip":{"10":3},"pipeline":{"0":1,"3":1},"pipewire":{"19":2,"20":2,"4":3},"pkg":{"4":1},"pkgbuild":{"5":1},"place":{"7":1},"placement":{"10":3},"placementrule":{"10":1},"places":{"10":1},"plain":{"9":1},"planck4":{"15":1},"plasma":{"0":6,"1":13,"10":13,"11":1,"14":4,"15":1,"16":1,"18":1,"3":6,"40":6,"6":13,"7":5,"8":3},"plasmaapplicationwallpaper":{"7":1},"plasmalogin":{"10":10,"40":2},"plasmanotifyrc":{"8":1},"plasmarc":{"8":1},"plasmashell":{"1":1,"14":1,"8":1},"plasmashellrc":{"1":3,"14":1,"40":1,"7":4},"plasmawindows":{"0":1},"play":{"20":2},"playback":{"1":1},"player":{"1":1,"3":1},"plugin":{"0":1,"1":1,"10":1,"11":2,"14":1,"26":1,"3":2,"35":2,"4":3},"plugins":{"0":3,"10":1,"14":2,"3":1},"plus":{"10":1,"3":2,"35":1},"png":{"6":1},"point":{"6":1},"pointed":{"17":2},"pointing":{"10":1},"points":{"15":1,"16":1,"18":1,"19":1,"20":1,"21":1,"22":1,"23":1,"24":1,"26":1,"28":1,"29":1,"30":1,"31":1,"32":1,"33":1,"34":1,"35":2,"36":1,"37":1,"38":1,"40":1,"6":1},"policy":{"10":1},"poll":{"6":1},"pop":{"21":1},"popup":{"18":2},"popups":{"29":3},"port":{"0":6,"3":4,"40":1,"9":5},"portal":{"10":5,"6":8},"portals":{"10":2},"portrait":{"1":1},"position":{"17":1},"positions":{"15":1,"16":1,"18":1,"19":1,"20":1,"21":1,"22":1,"23":1,"24":1,"26":1,"28":1,"29":1,"30":1,"31":1,"32":1,"33":1,"34":1,"35":2,"36":1,"37":1,"38":1,"40":1},"positives":{"6":1},"possible":{"12":1},"post":{"11":5},"posthook":{"10":1},"powerdevilrc":{"8":1},"powered":{"17":4},"pp":{"10":1},"pr":{"17":1,"19":1,"23":1,"26":1,"3":1,"35":1,"40":1},"pragma":{"18":2},"prblms":{"39":2},"prebuilt":{"11":6,"4":2,"5":2,"8":1},"predates":{"11":1},"predefined":{"17":2},"preferences":{"2":1},"prefers":{"3":2},"prefix":{"4":2},"prematurely":{"11":4},"prereqs":{"27":1},"prerequisites":{"27":1},"present":{"10":1,"13":1,"40":1,"7":1},"preserved":{"3":1},"preventing":{"6":1},"previews":{"23":2,"29":3,"6":2},"previous":{"0":1},"previousdesktop":{"0":1},"previously":{"0":1},"primarily":{"23":1},"primary":{"26":1},"print":{"2":1},"prints":{"17":1,"6":1},"prioritizes":{"1":1},"priority":{"1":1,"17":1},"private":{"25":1},"privileged":{"6":1},"probablyjassin":{"35":1},"probe":{"40":1},"problem":{"0":1,"14":1,"15":1,"16":1,"18":1,"19":1,"20":1,"21":1,"22":1,"23":1,"24":1,"25":1,"26":2,"27":1,"28":5,"3":1,"30":1,"31":1,"32":1,"33":1,"34":1,"35":1,"36":1,"38":1,"40":1},"proceed":{"9":1},"process":{"1":2,"13":1,"6":1},"processes":{"0":1},"producing":{"26":4},"profile":{"6":2,"7":1},"profileavatar":{"1":3},"profiles":{"6":1},"progress":{"0":1,"35":5},"project":{"17":1,"4":4},"promise":{"6":1},"prompt":{"11":1,"35":1,"5":1},"prompting":{"16":1},"prone":{"0":1},"properly":{"4":1},"properties":{"0":3},"property":{"0":1,"35":1},"proposal":{"17":2,"29":1,"37":1,"39":1},"protocol":{"0":2,"6":4},"protocols":{"0":1},"provided":{"0":1},"provides":{"0":2,"1":1,"2":1},"providing":{"1":1},"proxies":{"1":2},"proxy":{"5":1,"9":20},"publish":{"17":1},"published":{"11":4,"35":1},"publishes":{"35":1},"pull":{"11":1,"25":3},"pulled":{"12":1},"pulseaudio":{"4":1},"pure":{"0":1},"purpose":{"2":1},"pushing":{"0":1},"put":{"13":1},"py":{"0":1,"1":1},"python":{"0":3,"10":1,"6":1},"python3":{"12":2},"qabstractlistmodel":{"0":1},"qdbus6":{"0":1,"10":2,"14":2,"6":2,"8":1},"qdir":{"26":3},"qfile":{"26":1},"qlocalsocket":{"0":3},"qml":{"0":7,"1":13,"11":1,"14":6,"2":7,"3":2,"35":4,"4":8,"6":4,"7":1},"qml2":{"12":1,"14":1,"40":2,"6":4},"qml6":{"14":1},"qmldir":{"4":4},"qprocess":{"0":1},"qreal":{"26":2},"qs":{"0":1,"10":5,"18":2},"qslog":{"38":4},"qstring":{"0":15,"26":2},"qstringlist":{"26":1},"qt":{"1":1,"11":2,"3":2,"4":3},"qt6":{"11":3,"14":2,"4":14,"6":2},"qtdeclarative":{"4":1},"qtquick":{"1":1},"qtshadertools":{"4":1},"qtwayland":{"4":1},"quarantine":{"35":1},"question":{"6":1},"questions":{"3":1},"quick":{"14":2,"30":2,"4":1},"quickly":{"31":1},"quickshell":{"0":2,"1":1,"14":5,"15":1,"16":1,"22":9,"23":2,"24":13,"25":4,"33":4,"5":5,"6":10},"quite":{"39":2},"quote":{"38":1},"quoted":{"27":1,"30":1},"qvariantlist":{"0":2},"qvariantmap":{"0":3},"r0xx133":{"19":2},"radii":{"1":1},"radius":{"1":4},"raises":{"0":1},"raisewindow":{"0":1},"ram":{"1":1,"19":1},"ran":{"0":1,"25":1,"27":1},"random":{"23":4},"randomly":{"21":1,"23":3},"ranking":{"9":6},"ranks":{"9":1},"rarely":{"5":1},"rate":{"9":2},"rather":{"1":1,"10":2,"40":1,"6":2},"raw":{"13":1,"3":1},"rc":{"12":3},"re":{"10":2,"13":2,"17":1,"27":1,"3":1,"4":2,"40":1,"6":5,"7":1,"8":3,"9":1},"reach":{"9":1},"read":{"10":4,"14":1,"17":1,"18":1,"25":1,"4":1,"6":1,"9":1},"readall":{"26":1},"reader":{"1":1,"35":1},"readgenericusage":{"26":1},"readgputemperature":{"26":1},"readme":{"3":5},"reads":{"2":1,"40":1},"real":{"0":3,"25":6,"26":1,"40":2},"reason":{"23":1},"rebind":{"2":2,"3":1},"reboot":{"11":1,"16":2,"31":5,"40":1,"6":2},"rebooting":{"31":1},"rebuild":{"14":1,"6":2},"rebuilds":{"4":2,"6":1},"recent":{"40":1},"recently":{"40":1},"recognition":{"3":1},"recognized":{"1":1},"recommended":{"13":1},"reconciliation":{"17":1},"reconfigure":{"10":1,"14":3,"6":1,"8":1},"record":{"12":1,"6":2},"recorded":{"9":1},"recorder":{"14":1,"3":1,"5":2,"6":5},"recording":{"10":2,"12":1,"14":1,"6":6},"records":{"38":1,"8":1,"9":1},"recovery":{"0":1,"2":5},"recursive":{"14":1,"9":1},"red":{"2":2,"35":2},"redirect":{"39":1},"redirected":{"39":1},"redo":{"6":1},"redone":{"34":1},"reference":{"0":1,"14":6},"refiichi":{"40":2},"reflected":{"15":1,"16":1,"17":1,"18":1,"19":1,"20":1,"21":1,"22":1,"23":1,"24":1,"26":1,"28":1,"30":1,"31":1,"32":1,"33":1,"34":1,"35":1,"36":1,"37":1,"38":1,"39":1,"40":1},"reflector":{"9":3},"refresh":{"14":4,"5":1,"9":2},"refreshes":{"9":1},"refreshwindows":{"0":1},"refuses":{"6":1},"region":{"21":2},"regions":{"1":1},"register":{"0":1},"registered":{"2":2},"registering":{"0":1},"registers":{"2":2,"35":1,"8":1},"registration":{"1":1},"regular":{"19":1},"reinstall":{"24":4},"reinstalling":{"40":1},"reinstalls":{"6":1},"rejected":{"11":1},"related":{"40":1},"relay":{"0":1},"release":{"11":7,"38":2,"4":3,"5":2},"released":{"11":1},"releases":{"6":1},"reliability":{"0":1},"reliable":{"0":1},"relied":{"0":2},"relinked":{"6":1},"reload":{"10":1,"18":2,"6":2},"reloaded":{"16":1},"relogin":{"40":1},"relying":{"1":1},"remain":{"11":1,"25":1,"9":1},"remaining":{"11":1},"remains":{"2":1,"40":1},"remote":{"11":1,"14":1},"removal":{"10":1,"12":2},"remove":{"1":1,"10":1,"11":1,"12":3,"13":1,"2":1},"removed":{"10":1,"27":1,"6":1},"removes":{"0":1,"10":1,"12":1,"6":2},"removeworkspace":{"0":1},"rendering":{"1":2},"reopened":{"10":1},"repaints":{"6":1},"repeating":{"6":1},"replace":{"11":1},"replaced":{"11":4,"16":1},"replacement":{"0":2},"replaces":{"10":1},"replies":{"36":1},"reply":{"38":1},"repo":{"13":5,"17":1,"25":4,"3":2,"39":1},"report":{"15":1,"16":1,"18":1,"19":1,"20":1,"21":1,"22":2,"23":1,"24":1,"25":1,"26":1,"27":1,"28":1,"30":1,"31":1,"32":2,"33":1,"34":1,"35":1,"36":2,"38":8,"40":1},"reporter":{"22":1,"27":1,"40":2},"reporting":{"39":3,"9":1},"reportings":{"39":1},"reports":{"25":1,"3":1,"5":1,"6":1,"9":1},"repos":{"3":4},"repositories":{"9":1},"repository":{"12":1,"25":1,"3":3,"9":1},"representing":{"0":1},"reproduce":{"23":1},"request":{"17":2,"29":3,"35":2,"37":4},"requests":{"0":1,"17":1},"required":{"0":1,"1":1,"4":1},"requirement":{"5":1},"requirements":{"3":3},"requires":{"34":1,"4":3,"5":1},"reran":{"16":1},"reset":{"1":1,"2":1,"22":2,"25":1,"3":1,"7":2},"resets":{"16":2,"31":2,"6":2,"8":1},"resides":{"0":1},"residue":{"10":1},"resolution":{"0":1,"15":1,"16":1,"17":1,"18":1,"19":1,"2":1,"20":1,"21":1,"22":1,"23":1,"24":1,"26":1,"28":1,"29":1,"30":1,"31":1,"32":1,"33":1,"34":1,"35":1,"36":1,"37":1,"38":1,"40":1},"resolutions":{"17":1,"28":1},"resolved":{"39":1,"40":1},"resolves":{"6":1},"resource":{"1":1,"26":1,"39":1},"resources":{"1":1},"resourcescard":{"1":1},"responsive":{"1":1},"rest":{"17":2,"35":1},"restart":{"13":1,"14":2,"19":1,"22":4,"31":4,"6":3,"8":1},"restarts":{"10":1,"6":1},"restoration":{"2":1},"restore":{"1":1,"12":5,"7":1},"restored":{"12":1},"restores":{"2":2},"restoring":{"12":2,"2":1},"restricted":{"0":1},"retries":{"5":1},"retrieves":{"17":1},"retry":{"11":1},"returning":{"0":1},"rev":{"25":2},"reversal":{"27":3},"revert":{"1":1,"12":1,"31":2,"6":2},"reverted":{"27":1},"reverting":{"1":1},"reverts":{"31":2},"revision":{"11":1,"35":2},"rewrites":{"10":1,"6":2},"rewriting":{"9":1},"rf":{"1":1,"13":1,"4":1},"rgba":{"1":1},"rhythm":{"6":1},"right":{"1":1,"17":1,"30":3},"ripped":{"0":1},"rm":{"1":1,"11":2,"13":1,"14":1,"4":1,"8":1},"rn":{"10":1},"rns":{"12":1},"root":{"1":1,"26":1,"27":1},"roughly":{"26":1,"6":1},"rounded":{"1":1},"routes":{"17":1},"routine":{"6":1},"routing":{"0":1},"rpc":{"14":1},"rpm":{"5":5},"rtx":{"19":1},"rule":{"10":8,"25":1,"27":1},"rules":{"10":15,"3":1},"run":{"10":1,"11":3,"13":3,"14":1,"16":2,"3":6,"4":3,"6":3,"7":1,"8":2,"9":2},"running":{"1":1,"10":2,"11":2,"16":2,"19":1,"2":1,"26":1,"34":1,"35":1,"4":1,"6":2,"9":1},"runs":{"10":2,"11":1,"12":1,"25":1,"3":2,"6":4,"7":1},"runtime":{"11":4,"14":1,"4":2,"6":5,"7":3},"ryzen":{"26":1},"safe":{"0":1},"safely":{"1":1},"safety":{"2":1},"saturated":{"37":1},"save":{"6":1},"saved":{"2":1},"saves":{"10":1},"saving":{"2":1},"say":{"38":1},"says":{"17":1,"35":1,"40":1},"scaled":{"1":1},"scaling":{"1":1},"scan":{"23":1},"schema":{"16":1},"scheme":{"10":2,"14":1,"16":11,"3":6,"31":4,"5":1,"6":8},"schemes":{"10":1,"14":1,"6":1},"scope":{"15":1,"16":1,"17":6,"18":1,"19":1,"20":1,"21":1,"22":1,"23":1,"24":1,"26":1,"28":1,"30":1,"31":1,"32":1,"33":1,"34":1,"35":1,"36":1,"37":1,"38":1,"39":4,"40":1},"scoped":{"39":1},"screen":{"1":16,"10":5,"11":1,"14":3,"16":2,"19":6,"21":6,"28":5,"29":2,"3":1,"40":16,"5":2,"6":22,"7":12},"screencast":{"19":2,"6":6},"screening":{"35":1},"screenlocker":{"1":1},"screenshare":{"19":4,"6":2},"screenshot":{"12":1,"14":1,"17":1,"3":1,"6":4},"screenshots":{"3":1,"30":1,"6":5},"script":{"0":2,"1":1,"10":5,"11":3,"25":1,"26":1,"3":1,"33":2,"5":3,"8":2},"scripting":{"10":3},"scripts":{"0":1,"1":5,"10":3,"11":2,"27":1,"3":3,"40":1,"6":4,"7":1,"8":2,"9":1},"sddm":{"10":20,"40":6},"sdk":{"5":1},"sealed":{"3":3},"seamless":{"1":1},"seamlessly":{"0":1},"search":{"17":1},"searching":{"17":1},"second":{"10":1,"6":4},"secondary":{"26":1},"seconds":{"11":2,"35":1},"section":{"30":1},"sections":{"10":1},"sed":{"12":1,"27":2},"see":{"0":1,"10":1,"11":1,"25":1,"27":1,"3":4,"31":1,"35":1,"40":1,"6":1},"seem":{"13":1,"23":1},"seems":{"19":1,"23":1},"seen":{"34":1},"select":{"3":1},"selected":{"12":1},"selection":{"6":1},"selector":{"3":1},"selects":{"10":1},"self":{"7":1},"semicolon":{"0":1},"send":{"18":1},"sensor":{"4":1},"sensors":{"4":3},"sensorslib":{"4":1},"separate":{"17":1,"6":1},"separated":{"0":1},"sequence":{"12":1,"2":1,"8":2},"sequences":{"34":10,"8":1},"server":{"0":1},"service":{"0":1,"10":9,"15":2,"16":2,"40":2,"6":6,"8":1},"services":{"14":1,"26":1,"35":1,"40":3},"session":{"1":2,"10":1,"11":5,"14":1,"32":2,"35":2,"40":3,"6":2,"7":1},"set":{"10":2,"14":1,"16":1,"3":6,"31":1,"6":5,"7":1,"8":1,"9":1},"setactiveoutputname":{"0":1},"setdesktop":{"0":1},"seted":{"16":1},"setfullscreen":{"0":1},"setmaximized":{"0":1},"sets":{"0":3,"11":1,"16":4},"setted":{"16":1},"setting":{"1":1,"10":1,"40":1},"settings":{"10":1,"15":1,"16":1,"17":10,"2":4,"3":3,"30":3,"35":1,"6":3,"7":1},"settled":{"17":1},"setup":{"10":1,"11":6,"14":1,"16":6,"3":1,"4":2,"9":1},"setups":{"6":1},"setwindowdesktop":{"0":1},"setwindowproperty":{"0":1},"several":{"4":1},"severity":{"27":1},"sh":{"1":6,"10":4,"11":10,"13":6,"16":6,"25":4,"27":2,"3":5,"32":6,"33":5,"34":3,"4":3,"40":2,"5":2,"6":10,"7":2,"8":2,"9":2},"sha256":{"11":1},"shader":{"4":1},"shadereffectsource":{"1":1},"shadertools":{"4":2},"shadow":{"25":3},"shapes":{"1":1},"share":{"1":4,"10":5,"14":1,"19":6,"25":3,"6":5,"7":3},"shared":{"3":1,"4":1,"9":1},"sharing":{"6":1},"shell":{"0":3,"1":17,"10":1,"11":15,"12":3,"13":1,"14":6,"17":6,"2":5,"22":4,"24":2,"26":1,"29":1,"3":15,"33":1,"35":5,"38":2,"39":1,"4":8,"40":2,"5":1,"6":31,"7":6},"shellpackage":{"1":3,"14":1,"40":4,"7":3},"shellrc":{"12":1},"shells":{"1":8,"7":5},"shields":{"3":5},"shift":{"28":2,"3":5},"ship":{"17":2},"shipped":{"3":1,"35":1},"shortcut":{"0":8,"2":14,"3":3,"8":4},"shortcuts":{"0":7,"18":11,"2":22,"3":1,"8":7},"shortly":{"40":1},"show":{"10":1,"2":1,"30":1,"35":8,"6":2},"showbadges":{"35":5},"showing":{"35":2,"6":1,"8":3},"shows":{"10":2,"2":2,"21":1,"22":6,"26":3,"27":1,"30":7,"40":1,"7":3},"si":{"14":1,"5":1,"9":1},"side":{"17":1,"27":2,"30":4},"sidebar":{"3":2},"sigint":{"11":1},"sigkill":{"11":1},"signal":{"0":1,"35":1},"signals":{"0":2},"signature":{"38":1},"sigsegv":{"4":3},"sigterm":{"11":1},"silently":{"27":1,"4":1,"6":1,"8":1},"simplified":{"2":1},"simply":{"10":1,"13":2,"17":1},"since":{"11":2,"19":1,"39":1},"single":{"2":1},"singleton":{"0":4,"2":1,"35":1},"singletons":{"0":2},"sits":{"26":1},"sitting":{"11":1},"size":{"11":2,"28":1,"39":1},"skip":{"4":1,"5":1},"skipped":{"5":1,"9":2},"skips":{"8":1},"slider":{"30":11,"37":8},"sliders":{"30":1},"slideshow":{"3":1},"slightly":{"8":1},"slow":{"27":2,"4":1},"slower":{"4":1},"small":{"39":1,"4":1},"smart":{"2":1},"snapshotted":{"40":1},"snippet":{"40":1},"socket":{"10":1},"sockets":{"0":1},"software":{"1":1},"solution":{"7":1},"solving":{"39":1},"something":{"17":1,"21":1,"27":1,"40":1,"5":1,"6":1},"sometimes":{"19":1,"23":2},"somewhere":{"13":1},"soramanew":{"3":2},"sorry":{"18":1},"source":{"1":1,"10":1,"11":1,"15":1,"16":1,"17":1,"18":1,"19":1,"20":1,"21":1,"22":1,"23":1,"24":1,"26":1,"28":1,"29":1,"3":3,"30":1,"31":1,"32":1,"33":1,"34":1,"35":2,"36":1,"37":1,"38":1,"40":1,"5":1,"6":1},"sourced":{"40":1,"6":1},"sources":{"25":1,"9":2},"sourcing":{"1":1},"space":{"11":4},"sparse":{"25":1},"spawned":{"6":1},"specific":{"10":3,"14":1,"38":1,"39":1,"6":1},"specified":{"0":4},"spectacle":{"14":1,"2":1,"6":2},"speed":{"13":1},"speeding":{"4":1},"spot":{"23":1,"31":10,"6":2},"spotify":{"23":3},"src":{"1":4,"14":1,"25":1,"26":1,"3":3,"35":2,"7":1,"9":5},"srcset":{"3":2},"ssl":{"9":1},"stable":{"23":1,"3":1,"5":1},"stack":{"0":1},"stacked":{"1":1},"stacking":{"10":1},"stale":{"11":7,"14":1,"3":1,"4":1,"6":2},"standard":{"4":2},"standardizes":{"0":1},"star":{"3":5},"starship":{"5":2},"start":{"10":2,"14":1,"24":2,"40":1,"5":1,"6":7},"started":{"19":1},"starts":{"6":1},"startscript":{"40":1},"startup":{"0":1,"2":1,"40":1,"6":2},"stash":{"25":1},"stashes":{"11":1},"state":{"0":2,"10":2,"11":1,"12":2,"14":3,"15":1,"16":1,"17":1,"18":1,"19":1,"20":1,"21":1,"22":1,"23":1,"24":1,"25":7,"26":1,"27":1,"28":1,"29":1,"30":1,"31":1,"32":1,"33":1,"34":1,"35":1,"36":1,"37":1,"38":1,"39":1,"40":3},"statereason":{"15":1,"16":1,"18":1,"19":1,"20":1,"21":1,"22":1,"23":1,"24":1,"26":1,"28":1,"29":1,"30":1,"31":1,"32":1,"33":1,"34":1,"35":1,"36":1,"37":1,"38":1,"40":1},"states":{"0":2},"static":{"6":1},"stats":{"4":1},"status":{"14":2,"6":3,"8":1},"stays":{"10":1,"17":1,"39":1,"6":1},"stderr":{"11":2,"14":1,"4":1},"steal":{"2":1},"stealing":{"2":3},"steals":{"2":1,"8":1},"steam":{"23":3},"step":{"1":1,"10":1,"11":2,"27":1,"3":1,"4":1,"5":2,"9":2},"steps":{"11":2,"3":1},"stick":{"25":1},"still":{"0":1,"11":3,"16":1,"17":1,"27":1,"28":1,"35":1,"36":1,"39":2,"4":1,"40":1,"6":5,"8":2,"9":1},"stock":{"1":2,"3":1,"7":1},"stole":{"2":1},"stolen":{"0":1,"2":8,"8":4},"stop":{"6":1},"stopped":{"8":2},"stops":{"11":2,"6":2},"store":{"3":1},"stored":{"12":1},"straight":{"11":1},"strange15":{"17":1},"stream":{"19":5},"strength":{"36":2},"string":{"0":5,"34":1},"strips":{"10":1},"strong":{"36":2,"37":2},"structure":{"1":2},"structured":{"17":2},"stuck":{"13":1,"6":2},"stutters":{"16":2,"6":1},"style":{"3":5,"8":1},"subjects":{"40":1},"submodule":{"11":1,"14":3,"9":6},"submodules":{"3":1,"9":3},"subobject":{"35":1},"subsystem":{"17":1,"6":1},"succeeded":{"11":1},"success":{"11":2},"sudo":{"10":2,"12":1,"27":2,"4":2},"sudoers":{"10":1},"sufficient":{"26":1},"suggestions":{"17":1},"sum":{"26":3},"summaries":{"17":1},"summarized":{"15":1,"16":1,"18":1,"19":1,"20":1,"21":1,"22":1,"23":1,"24":1,"26":1,"28":1,"29":1,"30":1,"31":1,"32":1,"33":1,"34":1,"35":2,"36":1,"37":1,"38":1,"40":1},"summary":{"11":1,"15":1,"16":1,"17":1,"18":1,"19":1,"20":1,"21":1,"22":1,"23":1,"24":1,"26":1,"28":1,"30":1,"31":1,"32":1,"33":1,"34":1,"35":1,"36":1,"37":1,"38":1,"39":1,"40":1},"sun":{"30":8},"super":{"11":1,"3":14},"support":{"4":1,"5":1},"sure":{"13":1,"18":2,"40":1},"surface":{"1":1},"svg":{"3":1},"swipe":{"0":3,"6":1},"swipeoffset":{"0":1},"swiping":{"6":1},"switch":{"3":1,"7":1},"switcher":{"21":5,"22":6},"switches":{"0":4,"10":2},"switchto":{"0":1},"sy":{"5":1,"9":1},"symbols":{"1":1},"symptom":{"11":1,"25":1,"27":1,"34":1,"4":1,"6":3,"7":1,"8":1},"symptoms":{"5":1},"sync":{"10":6,"9":1},"syntax":{"27":1},"sys":{"26":8},"sysinfo":{"1":1},"system":{"0":3,"1":4,"10":2,"11":3,"14":3,"15":1,"16":1,"17":1,"2":4,"23":1,"26":2,"27":6,"3":1,"4":1,"5":2,"6":3,"7":2,"8":3},"systemctl":{"10":1,"14":4,"6":6,"8":2},"systemd":{"10":1,"16":2,"23":2,"40":1,"6":5},"systems":{"17":1,"26":4,"5":1,"9":3},"syu":{"6":1},"tab":{"21":9,"3":1,"6":1},"table":{"40":1},"tag":{"11":2},"tags":{"15":1,"16":1,"18":1,"19":1,"20":1,"21":1,"22":1,"23":1,"24":1,"26":1,"28":1,"29":1,"30":1,"31":1,"32":1,"33":1,"34":1,"35":2,"36":1,"37":1,"38":1,"40":1},"tahaub":{"38":1},"tail":{"14":1},"take":{"10":1},"takes":{"10":1,"11":1,"12":1,"13":1},"tampered":{"11":1},"tarball":{"11":1},"taskbar":{"28":3,"35":10,"6":2},"tasks":{"0":1},"tato":{"20":2,"24":2},"technique":{"1":1},"tell":{"10":1,"13":1},"tells":{"40":1},"temp":{"1":1},"temperature":{"26":7,"30":1},"temperatures":{"1":1},"templates":{"3":1},"temporarily":{"2":1},"temporary":{"0":1,"10":1},"terminal":{"12":1,"3":1,"34":8,"6":1,"8":4},"terminals":{"34":1},"test":{"1":2,"14":2,"34":3,"7":2},"testing":{"1":3,"40":4,"7":1},"tests":{"3":2,"34":1},"text":{"12":1,"17":1,"2":1,"3":1,"34":3,"35":1,"38":1,"4":1,"5":2,"8":1,"9":1},"textures":{"1":1},"theft":{"0":1},"theme":{"1":2,"10":7,"12":2,"16":2,"3":2,"40":2,"5":1,"6":2,"7":2,"8":5},"themes":{"10":4,"5":1,"6":1},"things":{"23":2},"think":{"17":1},"thinner":{"17":1},"third":{"1":1},"though":{"40":1},"thread":{"15":1,"16":1,"17":6,"18":1,"19":1,"20":1,"21":1,"22":1,"23":1,"24":1,"26":1,"28":1,"30":1,"31":1,"32":1,"33":1,"34":1,"35":1,"36":1,"37":1,"38":1,"39":4,"40":1},"threads":{"36":1,"37":1},"three":{"10":4},"thumbnails":{"14":1,"6":5},"tiling":{"10":1},"time":{"0":3,"1":2,"10":2,"13":1,"17":1,"27":1,"35":1,"40":1,"6":2},"timeline":{"29":1},"times":{"27":1},"tint":{"35":3},"tip":{"11":1},"title":{"0":2,"10":1,"22":1,"32":1,"36":1},"titlebar":{"16":2},"tmp":{"11":4,"14":4,"4":2},"todouble":{"26":1},"together":{"17":1},"toggle":{"15":2,"28":2,"30":1,"6":1},"togglerow":{"35":1},"toggles":{"0":1},"token":{"3":3},"told":{"10":1,"11":1,"39":1,"6":1},"tonal":{"31":10,"36":2,"6":2},"tool":{"17":1,"4":1,"6":2},"tools":{"12":1,"17":5,"3":1,"4":1},"top":{"0":1,"25":1,"3":4},"traced":{"27":1},"track":{"2":1,"6":1},"tracker":{"0":4,"40":1,"6":6},"tracking":{"0":5,"10":1,"12":1,"25":3,"32":1,"33":1,"34":1},"trackpad":{"0":2},"trackpads":{"0":1},"tracks":{"0":1,"2":2},"train":{"39":1},"training":{"39":2},"translucent":{"1":1},"treats":{"26":1},"tree":{"11":2},"tried":{"16":1,"19":2,"28":1},"tries":{"35":1,"8":1},"trigger":{"6":1},"trimmed":{"26":1},"troubleshooting":{"18":1,"3":7,"39":3,"40":2},"true":{"0":2,"11":1,"35":2},"truncated":{"11":1,"17":1,"26":1},"truth":{"25":1},"try":{"2":1},"trying":{"21":1},"tty":{"32":2},"tui":{"3":6,"4":4},"turn":{"19":2},"turns":{"15":4,"3":1},"tweak":{"8":2},"tweaks":{"8":2},"twice":{"11":1},"two":{"10":1,"25":5,"26":2,"30":1,"38":1,"6":5},"txt":{"12":1,"14":2,"38":4,"4":3,"5":3,"8":1},"type":{"14":1,"26":1,"3":4,"4":1},"typo":{"3":1},"ubuntu":{"3":5},"udev":{"10":1},"ui":{"0":2,"1":2,"17":1,"2":4},"uinput":{"10":2},"unassigned":{"17":1},"unavailable":{"9":2},"unchanged":{"8":1},"uncommitted":{"11":1,"25":4},"undocumented":{"27":1},"unexpectedly":{"11":1,"27":1},"unfullscreen":{"21":1},"uninstall":{"1":2,"10":2,"12":5,"27":6,"3":6},"uninstallation":{"1":2},"uninstaller":{"10":1,"12":2,"8":1},"uninstalling":{"3":1},"union":{"10":1},"unique":{"17":1},"unit":{"6":11},"units":{"14":1},"unity":{"35":6},"unless":{"12":1},"unpack":{"11":1},"unread":{"35":4},"unrecognized":{"18":2},"unrelated":{"11":1,"25":1},"unsets":{"0":2},"unstable":{"19":2,"6":2},"unwanted":{"27":1},"update":{"0":1,"11":9,"13":13,"14":2,"18":2,"2":1,"24":6,"25":14,"3":7,"35":1,"36":2,"40":2,"5":2,"6":5,"7":1,"9":4},"updated":{"1":1,"17":1,"24":1,"40":1},"updater":{"11":1,"13":6,"25":8},"updaters":{"25":1},"updates":{"17":2,"25":8,"3":3,"6":1},"updating":{"14":1,"3":3},"upgrade":{"11":8},"upgrades":{"11":1,"5":1},"upstream":{"25":1,"27":1,"3":1,"33":3,"40":1},"urgency":{"35":5},"url":{"15":1,"16":1,"17":1,"18":1,"19":1,"20":1,"21":1,"22":1,"23":1,"24":1,"26":1,"28":1,"29":1,"3":1,"30":1,"31":1,"32":1,"33":1,"34":1,"35":2,"36":1,"37":1,"38":1,"40":1,"9":2},"urls":{"9":1},"usage":{"23":2,"26":9,"27":1},"use":{"1":1,"11":2,"16":1,"17":2,"19":1,"2":1,"21":5,"6":1,"8":1,"9":1},"used":{"0":2,"11":3,"3":1,"5":1},"useful":{"39":1},"user":{"0":2,"1":2,"10":9,"12":2,"14":3,"16":2,"17":1,"2":6,"25":3,"27":1,"3":1,"36":1,"38":2,"6":12,"7":1,"8":2},"userimage":{"1":1},"users":{"17":2,"2":2,"25":2,"27":2,"39":1,"7":1},"uses":{"1":1,"12":2,"2":2,"25":1,"4":3,"5":1,"6":2,"8":1,"9":1},"using":{"0":2,"1":2,"11":1,"13":2,"17":1,"19":4,"2":3,"25":1,"29":1,"3":1,"6":2},"usr":{"1":1,"10":7,"33":3,"40":1,"6":1,"7":1},"usually":{"9":1},"utilities":{"36":2},"utility":{"6":1},"utilizing":{"0":1},"utils":{"15":2},"uuid":{"0":3},"v1":{"19":2,"6":2},"v2":{"19":1,"20":1,"28":1,"31":1,"35":4,"40":6},"vague":{"38":3},"value":{"10":2},"variables":{"40":3,"6":3,"9":1},"variant":{"31":10,"36":4},"various":{"9":1},"ve":{"19":1},"vendored":{"3":1},"venv":{"12":2},"verbatim":{"40":2},"verfiy":{"34":4},"verifiable":{"40":1},"verification":{"11":1,"34":1},"verified":{"35":2},"verifies":{"6":1},"verify":{"10":2,"14":3,"25":1,"6":1,"7":2,"9":1},"version":{"11":3,"12":1,"13":4,"15":1,"24":1,"25":3,"3":1,"35":2,"4":1,"40":2},"versions":{"27":1,"8":1},"vert":{"0":1},"vertical":{"1":2},"vesktop":{"19":12,"6":6},"via":{"0":4,"15":1,"17":1,"35":2,"40":2,"6":3,"7":1,"9":1},"vibrant":{"31":2,"36":13,"37":3},"victims":{"23":1},"video":{"20":10,"21":5,"3":1,"6":1},"view":{"14":4},"virtual":{"0":6,"8":3},"visible":{"10":1,"11":3,"17":1,"28":3,"6":1},"visuals":{"35":1},"vlecn0vbvygrzdn9kp8sqn7nt2xpneilgrmzywtzgdqygskadmgophakmy6r6lufqj8ifjy":{"3":3},"void":{"0":17},"vs":{"26":2,"33":2,"8":1},"waht":{"38":1},"wait":{"13":1},"walks":{"26":1},"wallpaper":{"1":4,"10":5,"14":2,"20":12,"3":5,"5":1,"6":7,"7":1},"wallpaperplugin":{"14":1,"7":2},"wallpapers":{"10":1,"20":7,"6":1},"want":{"17":1,"2":1},"wants":{"17":1},"warning":{"11":1,"12":1,"2":2},"washed":{"36":2},"watch":{"10":1},"watches":{"35":1},"way":{"3":1,"6":1},"wayland":{"0":7,"1":3,"11":1,"3":1,"4":2},"waylandclient":{"4":1},"wbpg":{"17":1},"weaker":{"36":2,"37":1},"weather":{"1":3,"17":1},"weathercard":{"1":1},"web":{"17":1},"weird":{"23":4,"34":3},"well":{"18":1},"went":{"18":1},"whatever":{"18":1},"whatsnew":{"35":1},"whenever":{"2":1},"wherever":{"25":1},"whether":{"11":1,"12":1,"36":1,"40":1,"6":1},"whichever":{"6":2},"white":{"3":4},"whole":{"17":1},"whose":{"10":2,"6":1},"wide":{"0":1,"27":6},"widget":{"1":1,"15":3,"26":3},"widgets":{"1":1,"26":1,"3":3},"width":{"0":1,"3":1},"window":{"0":20,"1":1,"10":14,"14":1,"21":5,"22":8,"28":1,"29":6,"3":1,"6":7,"7":1,"8":3},"windowlist":{"0":1},"windows":{"0":4,"1":1,"10":3,"22":4,"28":4,"29":2},"wins":{"10":1,"6":1},"wintone01":{"21":1,"24":1,"28":1},"withdrawn":{"10":1},"within":{"1":1},"without":{"0":1,"1":1,"11":3,"12":1,"17":1,"19":1,"27":2,"28":1,"5":1,"9":1},"wl":{"5":2},"won":{"14":1,"4":1,"5":2},"wont":{"24":2},"wording":{"15":1,"16":1,"18":1,"19":1,"20":1,"21":1,"22":1,"23":1,"24":1,"26":1,"28":1,"29":1,"30":1,"31":1,"32":1,"33":1,"34":1,"35":2,"36":1,"37":1,"38":1,"40":1},"words":{"34":1},"work":{"1":2,"10":1,"17":1,"19":1,"39":1,"5":1},"workaround":{"28":1},"worked":{"17":1,"19":1},"workflow":{"25":1},"workflows":{"3":1},"working":{"14":2,"15":4,"17":1,"18":7,"40":1,"6":2,"8":2},"works":{"1":1,"12":2,"2":2,"28":1,"40":3},"workspace":{"0":6,"11":1,"22":2,"3":1,"40":3,"6":14},"workspaces":{"0":2,"6":1},"wrapper":{"0":3,"1":1,"11":1,"6":3},"wrapping":{"0":2},"wraps":{"6":1},"writable":{"9":1},"writes":{"10":3,"11":1,"17":1,"2":1,"40":1,"6":2},"writing":{"25":1},"written":{"3":1,"34":1,"40":1,"9":1},"wrong":{"18":1,"21":6,"25":4,"26":2,"30":2,"40":1,"6":1,"8":4},"wrymt":{"3":2},"www":{"17":1,"3":1},"xdg":{"10":4,"11":4,"12":1,"14":3,"33":3,"5":1,"6":5,"8":1},"xe":{"6":1},"xoy8evpwlwta0acy3kok0nis1":{"3":3},"yay":{"12":1,"5":4},"ydotool":{"10":1},"ydotoold":{"10":5},"yet":{"3":1},"yields":{"25":1},"yourself":{"3":1},"youtube":{"29":7},"yyyymmdd":{"12":1},"zkde":{"19":2,"6":2}},"version":1} \ No newline at end of file diff --git a/plugins/caelestia-assistant/assistant/data/mined_synonyms.json b/plugins/caelestia-assistant/assistant/data/mined_synonyms.json new file mode 100644 index 0000000..8e11d66 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/data/mined_synonyms.json @@ -0,0 +1,644 @@ +{ + "how": "PMI-mined synonym hints (this script); hints only, never replacements; reload happens at import", + "min_freq": 4, + "min_pmi": 1.5, + "mined": { + "setActionOnClick": [ + "escape" + ], + "setAmbientColor": [ + "color", + "engine", + "intensity", + "mode" + ], + "setAmbientOpacity": [ + "color", + "mode" + ], + "setArpcCaelestiaInfo": [ + "caelestia-dots", + "found" + ], + "setAudioIncrement": [ + "camera", + "stream" + ], + "setAutoSchemeEnabled": [ + "dark", + "material" + ], + "setAutoSchemeMode": [ + "ambient", + "dark", + "material" + ], + "setBaseDuration": [ + "window" + ], + "setBlobScaleSpeed": [ + "window" + ], + "setBlurWallpaper": [ + "audio", + "breeze", + "built-in", + "video" + ], + "setBrightnessIncrement": [ + "moon", + "night" + ], + "setCheckUpdates": [ + "install", + "nexus" + ], + "setClearThreshold": [ + "escape" + ], + "setClockShowDate": [ + "legend", + "repos" + ], + "setClockShowIcon": [ + "brightness", + "side" + ], + "setCurrentDesktopOnly": [ + "switches", + "virtual" + ], + "setDefaultExpireTimeout": [ + "escape" + ], + "setDesktopClockEnabled": [ + "switches", + "virtual" + ], + "setDesktopClockInvertColors": [ + "intensity", + "switches", + "vibrant", + "virtual" + ], + "setDesktopClockPosition": [ + "switches", + "virtual" + ], + "setDesktopClockScale": [ + "switches", + "virtual" + ], + "setDesktopIconsEnabled": [ + "switches", + "virtual" + ], + "setDesktopLyricsAlignment": [ + "switches", + "virtual" + ], + "setDesktopLyricsAutoHide": [ + "switches", + "virtual" + ], + "setDesktopLyricsEnabled": [ + "switches", + "virtual" + ], + "setDesktopLyricsInvertColors": [ + "intensity", + "switches", + "vibrant", + "virtual" + ], + "setDesktopLyricsPosition": [ + "switches", + "virtual" + ], + "setDesktopLyricsScale": [ + "switches", + "virtual" + ], + "setDesktopShapesAutoHide": [ + "switches", + "virtual" + ], + "setDesktopShapesEnabled": [ + "switches", + "virtual" + ], + "setDesktopShapesPosition": [ + "switches", + "virtual" + ], + "setDesktopShapesScale": [ + "switches", + "virtual" + ], + "setDisableWallpaperBlur": [ + "audio", + "video", + "window" + ], + "setDockBadges": [ + "badge", + "badges", + "count", + "dock" + ], + "setDockCurrentDesktopOnly": [ + "badge", + "badges", + "switches", + "virtual" + ], + "setDockIconSize": [ + "badge", + "badges", + "brightness", + "side" + ], + "setDockPreviewOnDesktop": [ + "badge", + "badges", + "switches", + "virtual" + ], + "setDockRecolourIcons": [ + "badge", + "badges" + ], + "setDodgeWindows": [ + "window" + ], + "setEasingType": [ + "legend", + "repos", + "window" + ], + "setEnableBrightness": [ + "moon", + "night" + ], + "setEnableFprint": [ + "breeze", + "built-in" + ], + "setEnableOverviewBlur": [ + "window" + ], + "setExpandThreshold": [ + "escape" + ], + "setExpire": [ + "escape" + ], + "setFullscreen": [ + "escape" + ], + "setFullscreenExpireTimeout": [ + "escape" + ], + "setGameModeAutoEnable": [ + "ambient" + ], + "setGameModeDisableDesktopLyrics": [ + "ambient", + "switches", + "virtual" + ], + "setGameModeDisableHyprlandAnimations": [ + "ambient" + ], + "setGameModeDisableHyprlandBlur": [ + "ambient" + ], + "setGameModeDisableHyprlandGaps": [ + "ambient" + ], + "setGameModeDisableHyprlandShadows": [ + "ambient" + ], + "setGameModeDisableShellTransparency": [ + "ambient", + "caelestia-dots", + "start" + ], + "setGameModeDisableToastTransparency": [ + "ambient" + ], + "setGameModeDisableVisualizer": [ + "ambient" + ], + "setGameModeDisableWindowTransparency": [ + "ambient", + "rules", + "switcher" + ], + "setGithubBackground": [ + "caelestia-dots", + "caelestia-kde" + ], + "setGpuType": [ + "legend", + "repos", + "usage", + "widget" + ], + "setGreeterAfternoonStart": [ + "lock", + "screen", + "shell" + ], + "setGreeterCompact": [ + "lock", + "screen" + ], + "setGreeterEveningStart": [ + "lock", + "screen", + "shell" + ], + "setGreeterInverted": [ + "lock", + "screen" + ], + "setGreeterMode": [ + "ambient", + "lock", + "screen" + ], + "setGreeterMorningStart": [ + "lock", + "screen", + "shell" + ], + "setGreeterNightStart": [ + "brightness", + "light", + "lock", + "screen", + "shell" + ], + "setGreeterShowOnHover": [ + "lock", + "screen" + ], + "setGreeterSlideshowInterval": [ + "lock", + "screen" + ], + "setGreeterSlideshowRandom": [ + "lock", + "screen" + ], + "setGridFadeSpeed": [ + "window" + ], + "setGroupPreviewNum": [ + "escape" + ], + "setHideNotifs": [ + "breeze", + "built-in" + ], + "setHoverBottomLeft": [ + "window" + ], + "setHoverBottomRight": [ + "icon", + "window" + ], + "setHoverTopLeft": [ + "window" + ], + "setHoverTopRight": [ + "icon", + "window" + ], + "setLauncherVimKeybinds": [ + "shortcuts" + ], + "setLayoutType": [ + "legend", + "repos", + "window" + ], + "setLivePreviews": [ + "video", + "wallpaper", + "window" + ], + "setLockOnStartup": [ + "breeze", + "built-in" + ], + "setMaterialYouIconsEnabled": [ + "colour", + "dark", + "material" + ], + "setMaterialYouIconsVibrant": [ + "color", + "colors", + "colour", + "dark", + "material" + ], + "setMaxFprintTries": [ + "breeze", + "built-in" + ], + "setMediaUpdateInterval": [ + "cache", + "updater" + ], + "setMonitor": [ + "escape", + "fullscreened", + "video" + ], + "setNetworkRescanInterval": [ + "install", + "updates" + ], + "setNotifsMaxNotifs": [ + "escape" + ], + "setNotifsMaxPopups": [ + "escape" + ], + "setOpenExpanded": [ + "escape", + "issue" + ], + "setOverviewDragThreshold": [ + "window" + ], + "setOverviewEnabled": [ + "window" + ], + "setOverviewHoverThickness": [ + "window" + ], + "setOverviewShowOnHover": [ + "window" + ], + "setPerformanceShowGpu": [ + "usage", + "widget" + ], + "setPopoutsGreeter": [ + "lock", + "screen" + ], + "setPosition": [ + "escape" + ], + "setPreviewOnDesktop": [ + "switches", + "virtual" + ], + "setPreviewScaleWithBar": [ + "audio", + "camera" + ], + "setPreviewScalesAudio": [ + "camera", + "stream" + ], + "setPreviewScalesDock": [ + "badge", + "badges" + ], + "setPreviewScalesGithub": [ + "caelestia-dots", + "caelestia-kde" + ], + "setPreviewScalesGreeter": [ + "lock", + "screen" + ], + "setPreviewScalesLockStatus": [ + "breeze", + "built-in" + ], + "setPreviewScalesNotifications": [ + "escape" + ], + "setRecolourLogo": [ + "breeze", + "built-in", + "logocolor", + "white" + ], + "setResourceUpdateInterval": [ + "cache", + "updater" + ], + "setRotateProfilePic": [ + "breeze", + "built-in" + ], + "setScrollActionsBrightness": [ + "moon", + "night" + ], + "setSessionDragThreshold": [ + "plasma" + ], + "setSessionEnabled": [ + "plasma" + ], + "setSessionVimKeybinds": [ + "plasma", + "shortcuts" + ], + "setShowHibernate": [ + "breeze", + "built-in" + ], + "setShowLogout": [ + "breeze", + "built-in" + ], + "setShowReboot": [ + "breeze", + "built-in", + "color" + ], + "setShowScreenRecorder": [ + "breeze", + "lock" + ], + "setShowShutdown": [ + "breeze", + "built-in" + ], + "setShowSleep": [ + "breeze", + "built-in" + ], + "setShowSwitchUser": [ + "breeze", + "built-in", + "systemd" + ], + "setShowTerminal": [ + "sequences" + ], + "setSmartScheme": [ + "dark", + "material" + ], + "setSoundsCameraClick": [ + "audio", + "camera", + "stream", + "vesktop" + ], + "setSoundsChargingStarted": [ + "camera", + "stream" + ], + "setSoundsEffectTick": [ + "camera", + "stream" + ], + "setSoundsEnabled": [ + "camera", + "stream" + ], + "setSoundsLock": [ + "breeze", + "built-in", + "camera", + "stream" + ], + "setSoundsLowBattery": [ + "camera", + "stream" + ], + "setSoundsNotificationVolume": [ + "camera", + "stream" + ], + "setSoundsScreenRecord": [ + "breeze", + "camera", + "lock", + "stream" + ], + "setSoundsSfxVolume": [ + "camera", + "stream" + ], + "setSoundsUnlock": [ + "camera", + "stream" + ], + "setSyncWallpaper": [ + "audio", + "breeze", + "built-in", + "video" + ], + "setToastsConfigLoaded": [ + "install" + ], + "setToastsGameModeChanged": [ + "ambient" + ], + "setToastsNightLightChanged": [ + "brightness", + "light", + "night" + ], + "setUseFuzzyApps": [ + "crash" + ], + "setVideoWallpaperMuteOnMedia": [ + "audio", + "live", + "video", + "wallpaper" + ], + "setVideoWallpaperPauseOnAllDisplays": [ + "audio", + "live", + "video", + "wallpaper" + ], + "setVideoWallpaperPauseOnFullscreen": [ + "audio", + "live", + "video", + "wallpaper" + ], + "setVideoWallpaperPauseOnTiled": [ + "audio", + "live", + "video", + "wallpaper" + ], + "setVideoWallpaperPaused": [ + "audio", + "live", + "video", + "wallpaper" + ], + "setVideoWallpaperSoundEnabled": [ + "audio", + "live", + "video", + "wallpaper" + ], + "setWallpaperEnabled": [ + "audio", + "video" + ], + "setWallpaperFadeSpeed": [ + "audio", + "video", + "window" + ], + "setWallpaperFillMode": [ + "ambient", + "audio", + "video" + ], + "setWallpaperRecolor": [ + "audio", + "video" + ], + "setWallpaperRecolorStrength": [ + "audio", + "video" + ], + "setWorkspacesActiveIndicator": [ + "window" + ], + "setWorkspacesActiveTrail": [ + "window" + ], + "setWorkspacesDisplayType": [ + "legend", + "repos" + ], + "setWorkspacesMaxWindowIcons": [ + "rules", + "switcher" + ], + "setWorkspacesPerMonitor": [ + "fullscreened", + "video" + ], + "setWorkspacesShowWindows": [ + "window" + ], + "setWorkspacesShowWindowsOnSpecialWorkspaces": [ + "window" + ] + }, + "window": 8 +} diff --git a/plugins/caelestia-assistant/assistant/data/paraphrase_candidates.json b/plugins/caelestia-assistant/assistant/data/paraphrase_candidates.json new file mode 100644 index 0000000..51b69f3 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/data/paraphrase_candidates.json @@ -0,0 +1,2807 @@ +{ + "how": "grammar-template paraphrase candidates; feed through eval grow's quarantine, never auto-promote", + "items": [ + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you turn off session general", + "tool": "setSessionEnabled" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please transparency layers appearance should be 0.5", + "tool": "setTransparencyLayers" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "decrease network rescan interval", + "tool": "setNetworkRescanInterval" + }, + { + "expect": "ROUTED", + "kind": "enum", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please move greeter mode bar slideshow", + "tool": "setGreeterMode" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "could you make launcher shown smaller", + "tool": "setLauncherMaxShown" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please turn on bar hover", + "tool": "setBarShowOnHover" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "could you turn on scroll actions volume", + "tool": "setScrollActionsVolume" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "enable expire notifs notifications", + "tool": "setExpire" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "could you turn on dodge windows bar", + "tool": "setDodgeWindows" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you raise slideshow interval background to 0.5", + "tool": "setSlideshowInterval" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "could you decrease rounding border", + "tool": "setRounding" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "lower wallpaper fade speed to 2.55", + "tool": "setWallpaperFadeSpeed" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "stop osd", + "tool": "setOsdEnabled" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please hide lock startup lockscreen", + "tool": "setLockOnStartup" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "could you hide workspaces windows special", + "tool": "setWorkspacesShowWindowsOnSpecialWorkspaces" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please activate preview desktop tab", + "tool": "setPreviewOnDesktop" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please make launcher shown bigger", + "tool": "setLauncherMaxShown" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "make clipboard entries launcher bigger", + "tool": "setClipboardMaxEntries" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you make notifs popups notifications smaller", + "tool": "setNotifsMaxPopups" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "could you hide colorize media gif", + "tool": "setColorizeMediaGif" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please lower desktop clock scale to 1.75", + "tool": "setDesktopClockScale" + }, + { + "expect": "ROUTED", + "kind": "enum", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "data units services binary please", + "tool": "setDataUnits" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "ambient opacity appearance should be 0.5", + "tool": "setAmbientOpacity" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "could you make workspaces shown bar smaller", + "tool": "setWorkspacesShown" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "hide bar persistent", + "tool": "setBarPersistent" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "make preview scales greeter bigger", + "tool": "setPreviewScalesGreeter" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "could you greeter night start should be 11.5", + "tool": "setGreeterNightStart" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please enable overview hover", + "tool": "setOverviewShowOnHover" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please no more hover bottom right", + "tool": "setHoverBottomRight" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "could you show dock preview desktop", + "tool": "setDockPreviewOnDesktop" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you activate visualiser auto background", + "tool": "setVisualiserAutoHide" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you enable game mode shell", + "tool": "setGameModeDisableShellTransparency" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please turn on game mode shell", + "tool": "setGameModeDisableShellTransparency" + }, + { + "expect": "ROUTED", + "kind": "enum", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you wallpaper fill mode 1 please", + "tool": "setWallpaperFillMode" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you decrease deform scale appearance", + "tool": "setDeformScale" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "turn on performance dashboard", + "tool": "setShowPerformance" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please turn on utilities", + "tool": "setUtilitiesEnabled" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "increase fullscreen expire timeout", + "tool": "setFullscreenExpireTimeout" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "could you i want overview blur on", + "tool": "setEnableOverviewBlur" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please turn on clock seconds bar", + "tool": "setClockShowSeconds" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please turn on video wallpaper pause", + "tool": "setVideoWallpaperPauseOnTiled" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "could you stop performance memory dashboard", + "tool": "setPerformanceShowMemory" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you disable workspaces per monitor", + "tool": "setWorkspacesPerMonitor" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please i want performance network dashboard on", + "tool": "setPerformanceShowNetwork" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "could you arpc idle timeout should be 1800.0", + "tool": "setArpcIdleTimeout" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "could you i want check updates general on", + "tool": "setCheckUpdates" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "i want colorize media gif on", + "tool": "setColorizeMediaGif" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you i want game mode window on", + "tool": "setGameModeDisableWindowTransparency" + }, + { + "expect": "ROUTED", + "kind": "enum", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "could you clock format services auto please", + "tool": "setClockFormat" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "raise osd hover width to 55.0", + "tool": "setOsdHoverWidth" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please disable desktop shapes background", + "tool": "setDesktopShapesEnabled" + }, + { + "expect": "ROUTED", + "kind": "enum", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "could you set sensor units services to auto", + "tool": "setSensorUnits" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you increase visualiser spacing background", + "tool": "setVisualiserSpacing" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "could you show transparency appearance effects", + "tool": "setTransparencyEnabled" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "could you hide desktop shapes auto", + "tool": "setDesktopShapesAutoHide" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you resource update interval should be 5250.0", + "tool": "setResourceUpdateInterval" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you lower preview scales dock to 0.0", + "tool": "setPreviewScalesDock" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "stop desktop lyrics invert", + "tool": "setDesktopLyricsInvertColors" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please no more github background bar", + "tool": "setGithubBackground" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "could you enable islands appearance effects", + "tool": "setIslands" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "could you session drag threshold should be 105.0", + "tool": "setSessionDragThreshold" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "increase volume services", + "tool": "setMaxVolume" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "turn on rotate profile pic", + "tool": "setRotateProfilePic" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you activate sounds charging started", + "tool": "setSoundsChargingStarted" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you decrease greeter evening start", + "tool": "setGreeterEveningStart" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "could you increase default expire timeout", + "tool": "setDefaultExpireTimeout" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you activate scroll actions workspaces", + "tool": "setScrollActionsWorkspaces" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "preview scales greeter should be 0.0", + "tool": "setPreviewScalesGreeter" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "could you turn off dock preview desktop", + "tool": "setDockPreviewOnDesktop" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "could you enable auto scheme services", + "tool": "setAutoSchemeEnabled" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you turn off preview scale with", + "tool": "setPreviewScaleWithBar" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "could you turn on performance memory dashboard", + "tool": "setPerformanceShowMemory" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you stop scroll actions volume", + "tool": "setScrollActionsVolume" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "show recolour logo lock", + "tool": "setRecolourLogo" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please make launcher hover width bigger", + "tool": "setLauncherHoverWidth" + }, + { + "expect": "ROUTED", + "kind": "enum", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please move position notifs notifications top left", + "tool": "setPosition" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please activate open expanded notifs", + "tool": "setOpenExpanded" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please hide clock date bar", + "tool": "setClockShowDate" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you raise greeter afternoon start to 11.5", + "tool": "setGreeterAfternoonStart" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you no more volume osd", + "tool": "setEnableVolume" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "no more clock icon bar", + "tool": "setClockShowIcon" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please raise grid fade speed to 2.55", + "tool": "setGridFadeSpeed" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "stop desktop icons background", + "tool": "setDesktopIconsEnabled" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "hide visualiser blur background", + "tool": "setVisualiserBlur" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "disable game mode desktop", + "tool": "setGameModeDisableDesktopLyrics" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "could you desktop clock scale should be 1.75", + "tool": "setDesktopClockScale" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "activate game mode auto", + "tool": "setGameModeAutoEnable" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you no more clock background bar", + "tool": "setClockBackground" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please raise launcher drag threshold to 100.0", + "tool": "setLauncherDragThreshold" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you show arpc manual override", + "tool": "setArpcManualOverride" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you enable desktop clock invert", + "tool": "setDesktopClockInvertColors" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please utilities drag threshold should be 100.0", + "tool": "setUtilitiesDragThreshold" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you enable sounds charging started", + "tool": "setSoundsChargingStarted" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you greeter afternoon start should be 11.5", + "tool": "setGreeterAfternoonStart" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please raise grab width sidebar to 50.5", + "tool": "setGrabWidth" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "stop scroll actions workspaces", + "tool": "setScrollActionsWorkspaces" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "could you turn on desktop clock invert", + "tool": "setDesktopClockInvertColors" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please raise fprint tries lock to 3.0", + "tool": "setMaxFprintTries" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "raise rounding scale appearance to 1.25", + "tool": "setRoundingScale" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please no more notifs lock lockscreen", + "tool": "setHideNotifs" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you make preview scale bar bigger", + "tool": "setPreviewScale" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "could you activate hover bottom right", + "tool": "setHoverBottomRight" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you make layout type overview smaller", + "tool": "setLayoutType" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "stop clock seconds bar", + "tool": "setClockShowSeconds" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please i want performance dashboard on", + "tool": "setShowPerformance" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "decrease preview scales lock", + "tool": "setPreviewScalesLockStatus" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you no more logout lock lockscreen", + "tool": "setShowLogout" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you make dashboard hover width smaller", + "tool": "setDashboardHoverWidth" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you disable dashboard hover", + "tool": "setDashboardShowOnHover" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you increase desktop lyrics alignment", + "tool": "setDesktopLyricsAlignment" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "default expire timeout should be 30500.0", + "tool": "setDefaultExpireTimeout" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you enable fprint lock lockscreen", + "tool": "setEnableFprint" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "could you increase grid fade speed", + "tool": "setGridFadeSpeed" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "could you utilities hover thickness should be 50.5", + "tool": "setUtilitiesHoverThickness" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you no more toasts night light", + "tool": "setToastsNightLightChanged" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "could you show scroll actions workspaces", + "tool": "setScrollActionsWorkspaces" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you activate overview blur", + "tool": "setEnableOverviewBlur" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please utilities hover width should be 55.0", + "tool": "setUtilitiesHoverWidth" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "could you hide greeter compact bar", + "tool": "setGreeterCompact" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please disable sounds camera click", + "tool": "setSoundsCameraClick" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you make notifs notifications smaller", + "tool": "setNotifsMaxNotifs" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "could you no more toasts transparency utilities", + "tool": "setToastsTransparency" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "could you i want greeter hover bar on", + "tool": "setGreeterShowOnHover" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you enable game mode desktop", + "tool": "setGameModeDisableDesktopLyrics" + }, + { + "expect": "ROUTED", + "kind": "enum", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you put sensor units services auto", + "tool": "setSensorUnits" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "could you activate fuzzy actions launcher", + "tool": "setUseFuzzyActions" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please make dashboard hover width bigger", + "tool": "setDashboardHoverWidth" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "stop toasts config loaded", + "tool": "setToastsConfigLoaded" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "could you make fullscreen expire timeout smaller", + "tool": "setFullscreenExpireTimeout" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "i want action click notifs on", + "tool": "setActionOnClick" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "disable sleep lock lockscreen", + "tool": "setShowSleep" + }, + { + "expect": "ROUTED", + "kind": "enum", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please move easing type overview 0", + "tool": "setEasingType" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "could you i want blur wallpaper lock on", + "tool": "setBlurWallpaper" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "raise fullscreen expire timeout to 15500.0", + "tool": "setFullscreenExpireTimeout" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "show lock startup lockscreen", + "tool": "setLockOnStartup" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you turn off desktop clock background", + "tool": "setDesktopClockEnabled" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please base duration overview should be 550.0", + "tool": "setBaseDuration" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "i want game mode hyprland on", + "tool": "setGameModeDisableHyprlandAnimations" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "show greeter inverted bar", + "tool": "setGreeterInverted" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "no more sounds unlock audio", + "tool": "setSoundsUnlock" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please show status wifi bar", + "tool": "setStatusShowWifi" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please make preview scales battery bigger", + "tool": "setPreviewScalesBattery" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "could you enable overview blur", + "tool": "setEnableOverviewBlur" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "activate ambient color appearance", + "tool": "setAmbientColor" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you enable fuzzy apps launcher", + "tool": "setUseFuzzyApps" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please stop islands appearance effects", + "tool": "setIslands" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "could you hide desktop lyrics invert", + "tool": "setDesktopLyricsInvertColors" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "preview scales dock should be 0.0", + "tool": "setPreviewScalesDock" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you enable osd", + "tool": "setOsdEnabled" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you decrease sounds sfx volume", + "tool": "setSoundsSfxVolume" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you no more popouts status icons", + "tool": "setPopoutsStatusIcons" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you enable keep awake utilities", + "tool": "setShowKeepAwake" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please stop overview hover", + "tool": "setOverviewShowOnHover" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "could you enable launcher vim keybinds", + "tool": "setLauncherVimKeybinds" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you activate arpc caelestia info", + "tool": "setArpcCaelestiaInfo" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "show sounds audio", + "tool": "setSoundsEnabled" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please decrease expand threshold notifs", + "tool": "setExpandThreshold" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you lower greeter evening start to 11.5", + "tool": "setGreeterEveningStart" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please turn off dodge focused only", + "tool": "setDodgeFocusedOnly" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "could you turn on game mode desktop", + "tool": "setGameModeDisableDesktopLyrics" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please show hover bottom right", + "tool": "setHoverBottomRight" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please turn on overview blur", + "tool": "setEnableOverviewBlur" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please disable transparency appearance effects", + "tool": "setTransparencyEnabled" + }, + { + "expect": "ROUTED", + "kind": "enum", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you move auto scheme mode fixed", + "tool": "setAutoSchemeMode" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "raise resource update interval to 5250.0", + "tool": "setResourceUpdateInterval" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you no more all screens tab", + "tool": "setAllScreens" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please turn on clock icon bar", + "tool": "setClockShowIcon" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you i want fuzzy schemes launcher on", + "tool": "setUseFuzzySchemes" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please decrease visualiser spacing background", + "tool": "setVisualiserSpacing" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you no more dock recolour icons", + "tool": "setDockRecolourIcons" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "increase brightness increment services", + "tool": "setBrightnessIncrement" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you hide performance gpu dashboard", + "tool": "setPerformanceShowGpu" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "lower font scale appearance to 1.25", + "tool": "setFontScale" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you show material you icons", + "tool": "setMaterialYouIconsEnabled" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you stop launcher", + "tool": "setLauncherEnabled" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "stop workspaces windows bar", + "tool": "setWorkspacesShowWindows" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you visualiser rounding background should be 0.5", + "tool": "setVisualiserRounding" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "turn on sidebar", + "tool": "setSidebarEnabled" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "could you activate video wallpaper paused", + "tool": "setVideoWallpaperPaused" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "lower deform scale appearance to 0.75", + "tool": "setDeformScale" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "turn on wallpaper blur overview", + "tool": "setDisableWallpaperBlur" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "overview hover thickness should be 50.5", + "tool": "setOverviewHoverThickness" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you activate wallpaper recolor background", + "tool": "setWallpaperRecolor" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you lower brightness increment services to 0.26", + "tool": "setBrightnessIncrement" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please turn off clock seconds dashboard", + "tool": "setShowClockSeconds" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please show video wallpaper mute", + "tool": "setVideoWallpaperMuteOnMedia" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please no more fuzzy apps launcher", + "tool": "setUseFuzzyApps" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you lower default expire timeout to 30500.0", + "tool": "setDefaultExpireTimeout" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please make brightness increment services bigger", + "tool": "setBrightnessIncrement" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "hide popouts tray bar", + "tool": "setPopoutsTray" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please turn off video wallpaper sound", + "tool": "setVideoWallpaperSoundEnabled" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please i want clock seconds bar on", + "tool": "setClockShowSeconds" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you hide hover top left", + "tool": "setHoverTopLeft" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please increase preview scales tray", + "tool": "setPreviewScalesTrayMenu" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "could you hide game mode window", + "tool": "setGameModeDisableWindowTransparency" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "could you make clipboard entries launcher smaller", + "tool": "setClipboardMaxEntries" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you stop clock icon bar", + "tool": "setClockShowIcon" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please hide slideshow background wallpaper-scheme", + "tool": "setSlideshowEnabled" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please activate performance memory dashboard", + "tool": "setPerformanceShowMemory" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please lower animation speed appearance to 2.12", + "tool": "setAnimationSpeed" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you no more hover bottom left", + "tool": "setHoverBottomLeft" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please i want visualiser blur background on", + "tool": "setVisualiserBlur" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "could you i want desktop shapes background on", + "tool": "setDesktopShapesEnabled" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you decrease arpc idle timeout", + "tool": "setArpcIdleTimeout" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you stop fprint lock lockscreen", + "tool": "setEnableFprint" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "stop visualiser auto background", + "tool": "setVisualiserAutoHide" + }, + { + "expect": "ROUTED", + "kind": "enum", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "set greeter mode bar to time of day", + "tool": "setGreeterMode" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "decrease volume services", + "tool": "setMaxVolume" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please turn on status wifi bar", + "tool": "setStatusShowWifi" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "could you expand threshold notifs should be 52.5", + "tool": "setExpandThreshold" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "hide clock seconds bar", + "tool": "setClockShowSeconds" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you hide clock icon bar", + "tool": "setClockShowIcon" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please make group preview num smaller", + "tool": "setGroupPreviewNum" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "spacing scale appearance should be 1.25", + "tool": "setSpacingScale" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you stop scroll actions brightness", + "tool": "setScrollActionsBrightness" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "stop launcher hover", + "tool": "setLauncherShowOnHover" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please activate game mode hyprland", + "tool": "setGameModeDisableHyprlandShadows" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please make wallpaper recolor strength bigger", + "tool": "setWallpaperRecolorStrength" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you enable video wallpaper mute", + "tool": "setVideoWallpaperMuteOnMedia" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "could you no more tray recolour bar", + "tool": "setTrayRecolour" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "turn on fuzzy schemes launcher", + "tool": "setUseFuzzySchemes" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please show workspaces unoccupied bar", + "tool": "setWorkspacesShowUnoccupied" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you hide session vim keybinds", + "tool": "setSessionVimKeybinds" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "could you no more launcher hover", + "tool": "setLauncherShowOnHover" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "disable browse empty launcher", + "tool": "setShowBrowseOnEmpty" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you dashboard drag threshold should be 100.0", + "tool": "setDashboardDragThreshold" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "could you activate wallpaper blur overview", + "tool": "setDisableWallpaperBlur" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "disable sounds lock audio", + "tool": "setSoundsLock" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "turn off hover bottom left", + "tool": "setHoverBottomLeft" + }, + { + "expect": "ROUTED", + "kind": "enum", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "workspaces display type shapes please", + "tool": "setWorkspacesDisplayType" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you make font scale appearance smaller", + "tool": "setFontScale" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "could you animation speed appearance should be 2.12", + "tool": "setAnimationSpeed" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "enable workspaces windows bar", + "tool": "setWorkspacesShowWindows" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "could you raise utilities hover width to 55.0", + "tool": "setUtilitiesHoverWidth" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you enable greeter compact bar", + "tool": "setGreeterCompact" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you raise desktop lyrics scale to 1.75", + "tool": "setDesktopLyricsScale" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you increase network rescan interval", + "tool": "setNetworkRescanInterval" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you i want clock icon bar on", + "tool": "setClockShowIcon" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you i want recolour logo lock on", + "tool": "setRecolourLogo" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "preview scales battery should be 0.0", + "tool": "setPreviewScalesBattery" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "could you make expand threshold notifs bigger", + "tool": "setExpandThreshold" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "could you activate clock seconds bar", + "tool": "setClockShowSeconds" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "could you make layout type overview bigger", + "tool": "setLayoutType" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please turn on dashboard", + "tool": "setDashboardEnabled" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you activate sounds audio", + "tool": "setSoundsEnabled" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "could you show fuzzy actions launcher", + "tool": "setUseFuzzyActions" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please activate video wallpaper pause", + "tool": "setVideoWallpaperPauseOnFullscreen" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "could you enable workspaces per monitor", + "tool": "setWorkspacesPerMonitor" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please make preview scales battery smaller", + "tool": "setPreviewScalesBattery" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please workspaces shown bar should be 10.5", + "tool": "setWorkspacesShown" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "could you turn off video wallpaper paused", + "tool": "setVideoWallpaperPaused" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you show fuzzy apps launcher", + "tool": "setUseFuzzyApps" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "turn on toasts game mode", + "tool": "setToastsGameModeChanged" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please disable video wallpaper pause", + "tool": "setVideoWallpaperPauseOnAllDisplays" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "could you turn off game mode desktop", + "tool": "setGameModeDisableDesktopLyrics" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "could you i want dock recolour icons on", + "tool": "setDockRecolourIcons" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "could you stop microphone osd", + "tool": "setEnableMicrophone" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you decrease visualiser bars services", + "tool": "setVisualiserBars" + }, + { + "expect": "ROUTED", + "kind": "enum", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "put wallpaper fill mode 1", + "tool": "setWallpaperFillMode" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "raise brightness increment services to 0.26", + "tool": "setBrightnessIncrement" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "could you decrease greeter night start", + "tool": "setGreeterNightStart" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "could you make workspaces shown bar bigger", + "tool": "setWorkspacesShown" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please turn off scroll actions volume", + "tool": "setScrollActionsVolume" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please activate gif recorder utilities", + "tool": "setShowGifRecorder" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "could you dashboard hover width should be 55.0", + "tool": "setDashboardHoverWidth" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you font scale appearance should be 1.25", + "tool": "setFontScale" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you launcher shown should be 10.5", + "tool": "setLauncherMaxShown" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "stop popouts status icons", + "tool": "setPopoutsStatusIcons" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please increase launcher hover thickness", + "tool": "setLauncherHoverThickness" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please lower media update interval to 1050.0", + "tool": "setMediaUpdateInterval" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please preview scales wireless should be 0.0", + "tool": "setPreviewScalesWirelessPassword" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "spacing scale appearance should be 1.25", + "tool": "setSpacingScale" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you increase preview scales dock", + "tool": "setPreviewScalesDock" + }, + { + "expect": "ROUTED", + "kind": "enum", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you put fullscreen notifs notifications off", + "tool": "setFullscreen" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "could you hide scroll actions volume", + "tool": "setScrollActionsVolume" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you lower utilities drag threshold to 100.0", + "tool": "setUtilitiesDragThreshold" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "could you stop hover bottom right", + "tool": "setHoverBottomRight" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you hide blur mask appearance", + "tool": "setBlurMask" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "could you dashboard hover thickness should be 50.5", + "tool": "setDashboardHoverThickness" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please turn off greeter slideshow random", + "tool": "setGreeterSlideshowRandom" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "show fuzzy variants launcher", + "tool": "setUseFuzzyVariants" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please raise greeter slideshow interval to 1802.5", + "tool": "setGreeterSlideshowInterval" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please increase osd hover thickness", + "tool": "setOsdHoverThickness" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "could you raise overview hover thickness to 50.5", + "tool": "setOverviewHoverThickness" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "could you enable sleep lock lockscreen", + "tool": "setShowSleep" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "activate popouts tray bar", + "tool": "setPopoutsTray" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "disable action click notifs", + "tool": "setActionOnClick" + }, + { + "expect": "ROUTED", + "kind": "enum", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you move workspaces display type text", + "tool": "setWorkspacesDisplayType" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please i want desktop icons background on", + "tool": "setDesktopIconsEnabled" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "no more arpc manual override", + "tool": "setArpcManualOverride" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "turn off wallpaper background wallpaper-scheme", + "tool": "setWallpaperEnabled" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you i want dock preview desktop on", + "tool": "setDockPreviewOnDesktop" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "ambient opacity appearance should be 0.5", + "tool": "setAmbientOpacity" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please i want sounds camera click on", + "tool": "setSoundsCameraClick" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you i want blur appearance effects on", + "tool": "setBlurEnabled" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "show performance network dashboard", + "tool": "setPerformanceShowNetwork" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please increase dashboard hover thickness", + "tool": "setDashboardHoverThickness" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "could you i want quick toggles utilities on", + "tool": "setShowQuickToggles" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please turn on browse empty launcher", + "tool": "setShowBrowseOnEmpty" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you activate dock badges bar", + "tool": "setDockBadges" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "could you show greeter slideshow random", + "tool": "setGreeterSlideshowRandom" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please increase visualiser rounding background", + "tool": "setVisualiserRounding" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "increase clear threshold notifs", + "tool": "setClearThreshold" + }, + { + "expect": "ROUTED", + "kind": "enum", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "put desktop lyrics position top left", + "tool": "setDesktopLyricsPosition" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you audio increment services should be 0.26", + "tool": "setAudioIncrement" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please i want weather dashboard on", + "tool": "setShowWeather" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please activate game mode hyprland", + "tool": "setGameModeDisableHyprlandAnimations" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please turn off dock current desktop", + "tool": "setDockCurrentDesktopOnly" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please stop colorize media gif", + "tool": "setColorizeMediaGif" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please turn on media shapes dashboard", + "tool": "setUseMediaShapes" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you hide wallpaper blur overview", + "tool": "setDisableWallpaperBlur" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you dock icon size should be 56.0", + "tool": "setDockIconSize" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you make launcher hover width smaller", + "tool": "setLauncherHoverWidth" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you turn on confirm clear clipboard", + "tool": "setConfirmClearClipboard" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please activate lock startup lockscreen", + "tool": "setLockOnStartup" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you greeter evening start should be 11.5", + "tool": "setGreeterEveningStart" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please show media dashboard", + "tool": "setShowMedia" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "could you turn off power menu launcher", + "tool": "setShowPowerMenu" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you greeter morning start should be 11.5", + "tool": "setGreeterMorningStart" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "turn off utilities hover", + "tool": "setUtilitiesShowOnHover" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please turn on minimized tab switch", + "tool": "setShowMinimized" + }, + { + "expect": "ROUTED", + "kind": "enum", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you set clock format services to twelve hour", + "tool": "setClockFormat" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "make base duration overview bigger", + "tool": "setBaseDuration" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please activate toasts game mode", + "tool": "setToastsGameModeChanged" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "could you make rounding border bigger", + "tool": "setRounding" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "no more quick toggles utilities", + "tool": "setShowQuickToggles" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "could you disable weather dashboard", + "tool": "setShowWeather" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please hide shutdown lock lockscreen", + "tool": "setShowShutdown" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "could you raise group preview num to 5.5", + "tool": "setGroupPreviewNum" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "could you no more dock preview desktop", + "tool": "setDockPreviewOnDesktop" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "toasts utilities should be 5.5", + "tool": "setMaxToasts" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "could you lower overview drag threshold to 105.0", + "tool": "setOverviewDragThreshold" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please disable media dashboard", + "tool": "setShowMedia" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you show workspaces windows special", + "tool": "setWorkspacesShowWindowsOnSpecialWorkspaces" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please no more smart scheme services", + "tool": "setSmartScheme" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you hide status wifi bar", + "tool": "setStatusShowWifi" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please stop minimized tab switch", + "tool": "setShowMinimized" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "could you no more check updates general", + "tool": "setCheckUpdates" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you raise utilities drag threshold to 100.0", + "tool": "setUtilitiesDragThreshold" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please make dashboard hover thickness smaller", + "tool": "setDashboardHoverThickness" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you no more workspaces occupied bg", + "tool": "setWorkspacesOccupiedBg" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "could you show sounds lock audio", + "tool": "setSoundsLock" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "could you i want ambient color appearance on", + "tool": "setAmbientColor" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "enable arpc caelestia info", + "tool": "setArpcCaelestiaInfo" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you activate workspaces per monitor", + "tool": "setWorkspacesPerMonitor" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "smoothing border should be 50.0", + "tool": "setSmoothing" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please turn on shutdown lock lockscreen", + "tool": "setShowShutdown" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "could you stop arpc caelestia info", + "tool": "setArpcCaelestiaInfo" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please no more desktop lyrics background", + "tool": "setDesktopLyricsEnabled" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you i want workspaces unoccupied bar on", + "tool": "setWorkspacesShowUnoccupied" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please turn on quick toggles utilities", + "tool": "setShowQuickToggles" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please i want toasts config loaded on", + "tool": "setToastsConfigLoaded" + }, + { + "expect": "ROUTED", + "kind": "enum", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "move desktop clock position top center", + "tool": "setDesktopClockPosition" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "activate visualiser blur background", + "tool": "setVisualiserBlur" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you disable greeter inverted bar", + "tool": "setGreeterInverted" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "could you stop workspaces per monitor", + "tool": "setWorkspacesPerMonitor" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "increase font scale appearance", + "tool": "setFontScale" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you stop game mode hyprland", + "tool": "setGameModeDisableHyprlandGaps" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "stop utilities", + "tool": "setUtilitiesEnabled" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "i want media dashboard on", + "tool": "setShowMedia" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you lower preview scales notifications to 0.0", + "tool": "setPreviewScalesNotifications" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you enable media shapes dashboard", + "tool": "setUseMediaShapes" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "could you activate slideshow random background", + "tool": "setSlideshowRandom" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "could you raise notifs notifications to 1010.0", + "tool": "setNotifsMaxNotifs" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please grab width sidebar should be 50.5", + "tool": "setGrabWidth" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you make wallpapers launcher bigger", + "tool": "setMaxWallpapers" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "could you enable wallpaper recolor background", + "tool": "setWallpaperRecolor" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "could you turn on material you icons", + "tool": "setMaterialYouIconsVibrant" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "could you no more osd", + "tool": "setOsdEnabled" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "activate shutdown lock lockscreen", + "tool": "setShowShutdown" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "show toasts transparency utilities", + "tool": "setToastsTransparency" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "could you enable sounds lock audio", + "tool": "setSoundsLock" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you enable fuzzy variants launcher", + "tool": "setUseFuzzyVariants" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please activate weather dashboard", + "tool": "setShowWeather" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "could you turn off overview blur", + "tool": "setEnableOverviewBlur" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "show scroll actions brightness", + "tool": "setScrollActionsBrightness" + }, + { + "expect": "ROUTED", + "kind": "enum", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "position notifs notifications top left please", + "tool": "setPosition" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "could you show logout lock lockscreen", + "tool": "setShowLogout" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you stop bar hover", + "tool": "setBarShowOnHover" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please hide toasts game mode", + "tool": "setToastsGameModeChanged" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "could you enable scroll actions brightness", + "tool": "setScrollActionsBrightness" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "i want desktop lyrics auto on", + "tool": "setDesktopLyricsAutoHide" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "could you no more ambient color appearance", + "tool": "setAmbientColor" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you activate quick toggles utilities", + "tool": "setShowQuickToggles" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "disable toasts game mode", + "tool": "setToastsGameModeChanged" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "raise volume services to 1.25", + "tool": "setMaxVolume" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "show colorize media gif", + "tool": "setColorizeMediaGif" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please hide terminal dashboard", + "tool": "setShowTerminal" + }, + { + "expect": "ROUTED", + "kind": "enum", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you set wallpaper fill mode to 1", + "tool": "setWallpaperFillMode" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "lower wallpaper recolor strength to 0.5", + "tool": "setWallpaperRecolorStrength" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you show material you icons", + "tool": "setMaterialYouIconsVibrant" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "please show wallpaper background wallpaper-scheme", + "tool": "setWallpaperEnabled" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you disable islands appearance effects", + "tool": "setIslands" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "no more browse empty launcher", + "tool": "setShowBrowseOnEmpty" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "i want power menu launcher on", + "tool": "setShowPowerMenu" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "hide overview blur", + "tool": "setEnableOverviewBlur" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you turn on reboot lock lockscreen", + "tool": "setShowReboot" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "can you show sounds charging started", + "tool": "setSoundsChargingStarted" + }, + { + "expect": "ROUTED", + "kind": "numeric", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "could you lower dashboard hover width to 55.0", + "tool": "setDashboardHoverWidth" + }, + { + "expect": "ROUTED", + "kind": "bool", + "provenance": "grammar-template candidate (review before promotion into a dev set)", + "text": "i want game mode auto on", + "tool": "setGameModeAutoEnable" + } + ], + "n": 400, + "seed": 120 +} From 4f181d54d6a1655b54bdbb70cbedcc996a6d10c8 Mon Sep 17 00:00:00 2001 From: 0x0nYx <0x0nYx@users.noreply.github.com> Date: Fri, 9 Oct 2026 12:19:12 +0000 Subject: [PATCH 07/10] feat(assistant): diagnostics capability: rulepacks, fusion, argumentation, forecasting (migration chunk 6/12) The diagnostics capability: signed rulepacks (install/runtime/config_kde/known_regressions...), the diagnosis engine, rule rete, fusion, robust baselines, argumentation, forecast and telemetry. Chunk contents (22 files): - assistant/capabilities/diagnostics/__init__.py - assistant/capabilities/diagnostics/argumentation.py - assistant/capabilities/diagnostics/cli.py - assistant/capabilities/diagnostics/drain.py - assistant/capabilities/diagnostics/engine.py - assistant/capabilities/diagnostics/forecast.py - assistant/capabilities/diagnostics/fusion.py - assistant/capabilities/diagnostics/manifest.py - assistant/capabilities/diagnostics/rete.py - assistant/capabilities/diagnostics/risk.py - assistant/capabilities/diagnostics/robust_baseline.py - assistant/capabilities/diagnostics/rulepack.py - ... and 10 more Source: 0x0nYx/caelestia-assistant@2c193e7 (main, v0.1) Faithfulness: byte-identical copy (sha256-verified in the migration audit; only metadata.json / README.md are plugin-store scaffolding, and .caelestia-audit-ignore documents scanner false positives). Safety audit: 0 errors; 36 line-level findings documented in .caelestia-audit-ignore (string vocabularies / rulepack prose / test assertion targets / opt-in provider calls - nothing executes). Store CI: validate.py OK - check_safety.py OK - check_scope.py OK. Next chunk: plugin/caelestia-assistant/07-settings --- .../.caelestia-audit-ignore | 45 ++ .../capabilities/diagnostics/__init__.py | 12 + .../capabilities/diagnostics/argumentation.py | 670 ++++++++++++++++ .../assistant/capabilities/diagnostics/cli.py | 9 + .../capabilities/diagnostics/drain.py | 366 +++++++++ .../capabilities/diagnostics/engine.py | 745 ++++++++++++++++++ .../capabilities/diagnostics/forecast.py | 210 +++++ .../capabilities/diagnostics/fusion.py | 271 +++++++ .../capabilities/diagnostics/manifest.py | 10 + .../capabilities/diagnostics/rete.py | 598 ++++++++++++++ .../capabilities/diagnostics/risk.py | 198 +++++ .../diagnostics/robust_baseline.py | 164 ++++ .../capabilities/diagnostics/rulepack.py | 297 +++++++ .../diagnostics/rules.d/config_kde.json | 198 +++++ .../diagnostics/rules.d/folder_cleanup.json | 153 ++++ .../diagnostics/rules.d/idle_throttle.json | 41 + .../diagnostics/rules.d/install.json | 234 ++++++ .../rules.d/known_regressions.json | 66 ++ .../diagnostics/rules.d/runtime.json | 171 ++++ .../capabilities/diagnostics/schema_lint.py | 149 ++++ .../capabilities/diagnostics/settings_join.py | 141 ++++ .../capabilities/diagnostics/stacking.py | 208 +++++ .../capabilities/diagnostics/telemetry.py | 249 ++++++ 23 files changed, 5205 insertions(+) create mode 100755 plugins/caelestia-assistant/assistant/capabilities/diagnostics/__init__.py create mode 100644 plugins/caelestia-assistant/assistant/capabilities/diagnostics/argumentation.py create mode 100755 plugins/caelestia-assistant/assistant/capabilities/diagnostics/cli.py create mode 100644 plugins/caelestia-assistant/assistant/capabilities/diagnostics/drain.py create mode 100755 plugins/caelestia-assistant/assistant/capabilities/diagnostics/engine.py create mode 100644 plugins/caelestia-assistant/assistant/capabilities/diagnostics/forecast.py create mode 100644 plugins/caelestia-assistant/assistant/capabilities/diagnostics/fusion.py create mode 100644 plugins/caelestia-assistant/assistant/capabilities/diagnostics/manifest.py create mode 100644 plugins/caelestia-assistant/assistant/capabilities/diagnostics/rete.py create mode 100755 plugins/caelestia-assistant/assistant/capabilities/diagnostics/risk.py create mode 100644 plugins/caelestia-assistant/assistant/capabilities/diagnostics/robust_baseline.py create mode 100644 plugins/caelestia-assistant/assistant/capabilities/diagnostics/rulepack.py create mode 100755 plugins/caelestia-assistant/assistant/capabilities/diagnostics/rules.d/config_kde.json create mode 100755 plugins/caelestia-assistant/assistant/capabilities/diagnostics/rules.d/folder_cleanup.json create mode 100644 plugins/caelestia-assistant/assistant/capabilities/diagnostics/rules.d/idle_throttle.json create mode 100755 plugins/caelestia-assistant/assistant/capabilities/diagnostics/rules.d/install.json create mode 100644 plugins/caelestia-assistant/assistant/capabilities/diagnostics/rules.d/known_regressions.json create mode 100755 plugins/caelestia-assistant/assistant/capabilities/diagnostics/rules.d/runtime.json create mode 100755 plugins/caelestia-assistant/assistant/capabilities/diagnostics/schema_lint.py create mode 100644 plugins/caelestia-assistant/assistant/capabilities/diagnostics/settings_join.py create mode 100644 plugins/caelestia-assistant/assistant/capabilities/diagnostics/stacking.py create mode 100644 plugins/caelestia-assistant/assistant/capabilities/diagnostics/telemetry.py diff --git a/plugins/caelestia-assistant/.caelestia-audit-ignore b/plugins/caelestia-assistant/.caelestia-audit-ignore index 6ce8168..80400c5 100644 --- a/plugins/caelestia-assistant/.caelestia-audit-ignore +++ b/plugins/caelestia-assistant/.caelestia-audit-ignore @@ -30,6 +30,51 @@ assistant/adapters/caelestia/shell/modules/sidebar/AiAssistant.qml:2232 assistant/adapters/caelestia/shell/modules/sidebar/AiAssistant.qml:2238 assistant/adapters/caelestia/shell/modules/sidebar/AiAssistant.qml:2359 + # assistant/capabilities/diagnostics/argumentation.py + # Command tokenization: the literal 'sudo' is stripped/classified as a token; analysis only, never + executed. +assistant/capabilities/diagnostics/argumentation.py:278 +assistant/capabilities/diagnostics/argumentation.py:281 + + # assistant/capabilities/diagnostics/risk.py + # Static risk classifier: deny-list REGEX VOCABULARY that matches dangerous shapes (curl|sh, + wget|sh, sudo, pkexec, doas) to LABEL commands PRIVILEGED/DESTRUCTIVE. Text patterns; the engine + never runs commands. +assistant/capabilities/diagnostics/risk.py:12 +assistant/capabilities/diagnostics/risk.py:17 +assistant/capabilities/diagnostics/risk.py:41 +assistant/capabilities/diagnostics/risk.py:42 +assistant/capabilities/diagnostics/risk.py:62 + + # assistant/capabilities/diagnostics/rules.d/config_kde.json + # Rulepack prose: display-only suggested command (assistant never executes; steps are labeled and + require explicit user confirmation). +assistant/capabilities/diagnostics/rules.d/config_kde.json:73 + + # assistant/capabilities/diagnostics/rules.d/install.json + # Rulepack: display-only copy-paste install commands, in-rule labeled PRIVILEGED via command_risk, + plus updater prose mentioning 'git clone'. Never executed by the assistant. +assistant/capabilities/diagnostics/rules.d/install.json:23 +assistant/capabilities/diagnostics/rules.d/install.json:25 +assistant/capabilities/diagnostics/rules.d/install.json:30 +assistant/capabilities/diagnostics/rules.d/install.json:32 +assistant/capabilities/diagnostics/rules.d/install.json:36 +assistant/capabilities/diagnostics/rules.d/install.json:38 +assistant/capabilities/diagnostics/rules.d/install.json:114 +assistant/capabilities/diagnostics/rules.d/install.json:132 +assistant/capabilities/diagnostics/rules.d/install.json:133 +assistant/capabilities/diagnostics/rules.d/install.json:153 +assistant/capabilities/diagnostics/rules.d/install.json:229 + + # assistant/capabilities/diagnostics/rules.d/known_regressions.json + # Rulepack prose: display-only suggested command string, confirmation-gated, never executed. +assistant/capabilities/diagnostics/rules.d/known_regressions.json:27 + + # assistant/capabilities/diagnostics/rules.d/runtime.json + # Rulepack prose: display-only suggested reinstall command string, confirmation-gated, never + executed. +assistant/capabilities/diagnostics/rules.d/runtime.json:74 + # assistant/data/index/bm25.json # Built BM25 search-index artifact (single-line JSON): term/document data mentioning 'curl', 'git ls-remote'. Data, not code; JSON cannot carry line-level opt-out comments. diff --git a/plugins/caelestia-assistant/assistant/capabilities/diagnostics/__init__.py b/plugins/caelestia-assistant/assistant/capabilities/diagnostics/__init__.py new file mode 100755 index 0000000..b2299a9 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/capabilities/diagnostics/__init__.py @@ -0,0 +1,12 @@ +"""Layer 1: deterministic rule-based diagnostics (no ML, no execution). + +Loads rules from rules.d/*.json, matches user text + pasted logs against +error signatures drawn from docs/TROUBLESHOOTING.md and the resolved issue +history, and prints a fix plan whose commands are inert strings. +""" + +from . import engine # noqa: F401 +from . import risk # noqa: F401 +from . import schema_lint # noqa: F401 + +__all__ = ["engine", "risk", "schema_lint"] diff --git a/plugins/caelestia-assistant/assistant/capabilities/diagnostics/argumentation.py b/plugins/caelestia-assistant/assistant/capabilities/diagnostics/argumentation.py new file mode 100644 index 0000000..029a359 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/capabilities/diagnostics/argumentation.py @@ -0,0 +1,670 @@ +"""diagnostics.argumentation — Dung abstract argumentation over +conflicting diagnostic rules. + +Dung 1995, "On the Acceptability of Arguments and its Fundamental Role in +Nonmonotonic Reasoning, Logic Programming and n-Person Games", +Artificial Intelligence 77(2), pp. 321-357 — the semantics implemented +EXACTLY as defined there: + +- admissible(S): S is conflict-free (no member attacks a member, itself + included) and every attacker of a member is attacked by some member of S; +- grounded extension: the least fixed point of the characteristic function + F(S) = {a | every attacker of a is attacked by some member of S}, + obtained by iterating F from the empty set until stable; +- preferred extensions: the subset-maximal admissible sets, found here by + include-first DFS enumeration with conflict pruning and maximality + filtering (a later-visited set can never be a strict superset of an + earlier-visited one under include-first order, so one pass suffices); + enumeration is REFUSED above 20 arguments with the stated reason — + honesty over completeness: the search is exponential and the module says + so instead of hanging; the grounded verdict stays available. + +WHEN FIXES FIGHT, the framework answers "which fix wins and why" without +inventing a tie-break: symmetric two-rule conflicts (A says enable X, B +says disable X) have NO Dung winner — nothing defends either side, the +grounded extension is empty, and resolve() says "undecided between 2 +admissible positions" and ABSTAINS. A winner needs a defender (an +unattacked rule that defeats the loser), and the verdict then carries the +winner's defense set — exactly which attackers it defeats and how. + +Attack edges, two deterministic sources: + +1. CONTRADICTIONS — an explicit table of rule-id pairs with reason + + citation. The shipped table is INTENTIONALLY EMPTY, said plainly: a + full read of the six rules.d files found NO pair of fixes that + genuinely conflict — no same-unit opposing verbs, no opposing + instructions about the same service, file, or binary (the corpus is + deliberately consistent; pinned by test). Manufacturing an attack + between non-conflicting rules would be a fake claim, so the table + stays empty until a real conflicting pair ships in rules.d, at which + point it gets an entry with reason + citation. The mechanism itself is + pinned by tests with synthetic pairs. +2. Structural detection — a small deterministic parser over the fix + command strings: commands that target the SAME unit (systemd unit, + package, or file path) with OPPOSING verbs (enable/disable, start/ + stop, mask/unmask, install/remove; restart counts as start-side). + Each attack carries the matched unit and verbs as its reason. Queries + (systemctl status/is-enabled, pacman -Qs/-Ss) are not instructions and + produce no ops; a rule's own reinstall (pacman -R x && pacman -S x) + is cross-rule by construction and never attacks itself. + +Pure module: no I/O, no execution, nothing written; deterministic by +construction (fixed iteration orders throughout). +""" +from __future__ import annotations + +import re +from typing import Any, Dict, List, Optional, Sequence, Tuple + +__all__ = ["CONTRADICTIONS", "ArgumentationFramework", + "PREFERRED_ENUMERATION_LIMIT", "arguments_from_report", + "conflict_resolution", "parse_command_ops", "render_conflict_lines", + "resolve", "structural_attacks", "table_attacks"] + +# Honesty over completeness: preferred-extension enumeration is exponential +# (2^n candidate subsets); above this many arguments the module refuses and +# says why, leaving the (polynomial) grounded verdict standing. +PREFERRED_ENUMERATION_LIMIT = 20 + +# The explicit contradiction table (see module docstring: intentionally +# empty — no real rules.d pair genuinely conflicts). Entry shapes, for the +# day a real pair ships: {"rules": [id_a, id_b], "reason", "citation"} for +# a MUTUAL contradiction (attack registered both ways), or +# {"attacker": id_a, "defender": id_b, "reason", "citation"} for a +# DIRECTED defeat (one-way; this is the shape that can produce a grounded +# winner with a defense set, since structural opposition is always +# symmetric and by itself can only yield undecided verdicts). +CONTRADICTIONS: Tuple[Dict[str, Any], ...] = () + +_SYSTEMCTL_VERBS = frozenset({"enable", "disable", "start", "stop", + "restart", "mask", "unmask"}) +_UP_VERBS = frozenset({"enable", "start", "restart", "unmask", "install"}) +_ENV_ASSIGNMENT_RE = re.compile(r"[A-Za-z_][A-Za-z0-9_]*=\S*") +_PACMAN_INSTALL_RE = re.compile(r"-S[yu]*") +_PACMAN_REMOVE_RE = re.compile(r"-R[snd]*") + + +# --------------------------------------------------------------------------- +# Dung's abstract framework + semantics +# --------------------------------------------------------------------------- + +class ArgumentationFramework: + """AF = (arguments, attacks); attacks are (attacker, defender) pairs. + + Semantics exactly per Dung 1995 (module docstring). All methods are + deterministic; unknown argument ids are REJECTED with ValueError. + """ + + def __init__(self, arguments: Sequence[str], + attacks: Sequence[Tuple[str, str]]) -> None: + self.arguments: List[str] = [] + seen: set = set() + for argument in arguments: + if not isinstance(argument, str) or not argument: + raise ValueError(f"argument ids must be non-empty strings, got {argument!r}") + if argument in seen: + raise ValueError(f"duplicate argument id {argument!r}") + seen.add(argument) + self.arguments.append(argument) + self._attackers: Dict[str, List[str]] = {a: [] for a in self.arguments} + self._attackees: Dict[str, List[str]] = {a: [] for a in self.arguments} + self._pairs: List[Tuple[str, str]] = [] + seen_pairs: set = set() + for pair in attacks: + if not isinstance(pair, (tuple, list)) or len(pair) != 2: + raise ValueError(f"attacks must be (attacker, defender) pairs, got {pair!r}") + attacker, defender = pair + if attacker not in self._attackers or defender not in self._attackees: + raise ValueError( + f"attack {pair!r} references an unknown argument " + f"(known: {self.arguments})") + if (attacker, defender) in seen_pairs: + raise ValueError( + f"duplicate attack edge {(attacker, defender)!r} — the " + "attack relation is a set; repeated edges are rejected, " + "not silently absorbed (the fusion module's duplicate-" + "vote convention)") + seen_pairs.add((attacker, defender)) + self._pairs.append((attacker, defender)) + self._attackers[defender].append(attacker) + self._attackees[attacker].append(defender) + + def _known(self, name: str) -> str: + if name not in self._attackers: + raise ValueError(f"unknown argument {name!r} (known: {self.arguments})") + return name + + + def attackees_of(self, argument: str) -> List[str]: + """The arguments that `argument` attacks, in declaration order.""" + return list(self._attackees[self._known(argument)]) + + def is_conflict_free(self, subset: Sequence[str]) -> bool: + """No member of `subset` attacks a member of `subset` (a self- + attacking member violates conflict-freedom on its own).""" + members = [self._known(a) for a in subset] + member_set = set(members) + for a in members: + if any(b in member_set for b in self._attackees[a]): + return False + return True + + def admissible(self, subset: Sequence[str]) -> bool: + """Dung's admissibility: conflict-free + every member defended by + the subset (each attacker is attacked by some subset member).""" + if not self.is_conflict_free(subset): + return False + members = [self._known(a) for a in subset] + member_set = set(members) + for a in members: + for attacker in self._attackers[a]: + if not any(attacker in self._attackees[m] for m in member_set): + return False + return True + + def characteristic(self, subset: Sequence[str]) -> List[str]: + """F(S) = the arguments defended by S (Dung's characteristic + function), in framework order.""" + members = [self._known(a) for a in subset] + member_set = set(members) + defended: List[str] = [] + for a in self.arguments: + attackers = self._attackers[a] + if all(any(attacker in self._attackees[m] for m in member_set) + for attacker in attackers): + defended.append(a) + return defended + + def grounded_extension(self) -> List[str]: + """The least fixed point of F, by iteration from the empty set + (Dung 1995); returned in framework order.""" + current: List[str] = [] + for _ in range(len(self.arguments) + 2): + nxt = self.characteristic(current) + if nxt == current: + return current + current = nxt + raise RuntimeError( + "characteristic-function iteration failed to stabilize within " + "n+2 rounds — internal invariant violation (F is monotone); " + "please report") + + def preferred_extensions(self) -> List[List[str]]: + """The maximal admissible sets, in include-first DFS discovery + order (deterministic; each extension in framework order). + + REFUSED with ValueError above PREFERRED_ENUMERATION_LIMIT + arguments — the enumeration is exponential; honesty over + completeness (the grounded verdict remains available). + """ + n = len(self.arguments) + if n > PREFERRED_ENUMERATION_LIMIT: + raise ValueError( + f"refused: preferred-extension enumeration over {n} arguments " + f"(> {PREFERRED_ENUMERATION_LIMIT}) is exponential (2^{n} " + "candidate subsets); honesty over completeness — the grounded " + "verdict remains available") + index = {a: i for i, a in enumerate(self.arguments)} + attackees_mask = [0] * n + attackers_mask = [0] * n + conflict_mask = [0] * n # both directions + the self bit + for attacker, defender in self._pairs: + i, j = index[attacker], index[defender] + attackees_mask[i] |= 1 << j + attackers_mask[j] |= 1 << i + conflict_mask[i] |= 1 << j + conflict_mask[j] |= 1 << i + + def admissible_mask(mask: int) -> bool: + # conflict-free holds by DFS construction; check defense only: + # every attacker of a member must be covered by the members' + # combined attackees. + cover = 0 + rest = mask + while rest: + low = rest & -rest + cover |= attackees_mask[low.bit_length() - 1] + rest ^= low + rest = mask + while rest: + low = rest & -rest + if attackers_mask[low.bit_length() - 1] & ~cover: + return False + rest ^= low + return True + + kept: List[int] = [] + + def record_if_maximal(mask: int) -> None: + if any(mask | k == k for k in kept): + return # subset of (or equal to) an already-kept extension + if admissible_mask(mask): + kept.append(mask) + + def search(i: int, included: int, blocked: int) -> None: + # Upper-bound prune: the best completion is included plus every + # still-addable argument; if even that cannot beat a kept + # extension, no completion of this branch is maximal. + available = 0 + for j in range(i, n): + if not (blocked >> j) & 1: + available |= 1 << j + if any((included | available) | k == k for k in kept): + return + if i == n: + record_if_maximal(included) + return + # Include-first (this ordering is what makes one-pass maximality + # filtering sound: any strict superset is always visited first). + if not (blocked >> i) & 1 and not (conflict_mask[i] >> i) & 1: + search(i + 1, included | (1 << i), blocked | conflict_mask[i]) + search(i + 1, included, blocked) + + search(0, 0, 0) + return [[self.arguments[j] for j in range(n) if (mask >> j) & 1] + for mask in kept] + + +# --------------------------------------------------------------------------- +# The structural conflict parser (deterministic; commands are inert strings) +# --------------------------------------------------------------------------- + +def _segments(command: str) -> List[str]: + """Split a command line on command separators (&& and ;).""" + return [part.strip() for part in re.split(r"&&|;", command) if part.strip()] + + +def _tokens(segment: str) -> List[str]: + """Whitespace tokens without sudo prefixes or env assignments.""" + tokens = [] + for token in segment.split(): + if token == "sudo": + continue + if _ENV_ASSIGNMENT_RE.fullmatch(token): + continue + tokens.append(token) + return tokens + + +def _normalize_unit(unit: str) -> str: + """Units are compared after stripping the .service suffix, so + 'bluetooth.service' and 'bluetooth' name the same unit.""" + if unit.endswith(".service"): + return unit[: -len(".service")] + return unit + + +def parse_command_ops(command: str) -> List[Dict[str, str]]: + """The (verb, unit, direction) instructions carried by one command. + + Recognized shapes only, deliberately small: systemctl verb units; + pacman -S/-R package lists (flags like -Ss search or -Q query are NOT + instructions); dnf/apt install/remove lists; rm paths. Everything else + (bash scripts, config writers, editors, read-only probes) yields no + ops — an unrecognized command is no instruction, never a guess. + """ + ops: List[Dict[str, str]] = [] + for segment in _segments(command): + tokens = _tokens(segment) + if not tokens: + continue + head = tokens[0] + if head == "systemctl": + verb: Optional[str] = None + units: List[str] = [] + for token in tokens[1:]: + if verb is None: + if token in _SYSTEMCTL_VERBS: + verb = token + elif not token.startswith("-"): + units.append(token) + if verb is not None: + for unit in units: + ops.append({"verb": verb, "unit": _normalize_unit(unit), + "direction": "up" if verb in _UP_VERBS else "down"}) + elif head == "pacman": + mode: Optional[str] = None + packages: List[str] = [] + for token in tokens[1:]: + if token.startswith("--"): + continue + if token.startswith("-"): + if _PACMAN_INSTALL_RE.fullmatch(token): + mode = "install" + elif _PACMAN_REMOVE_RE.fullmatch(token): + mode = "remove" + else: + mode = None # -Q/-Ss queries and friends: not instructions + elif mode is not None: + packages.append(token) + for package in packages: + ops.append({"verb": mode, "unit": package, + "direction": "up" if mode == "install" else "down"}) + elif head in ("dnf", "apt", "apt-get"): + if len(tokens) >= 2: + sub = tokens[1] + if sub == "install": + for package in tokens[2:]: + ops.append({"verb": "install", "unit": package, + "direction": "up"}) + elif sub in ("remove", "erase", "purge"): + for package in tokens[2:]: + ops.append({"verb": "remove", "unit": package, + "direction": "down"}) + elif head == "rm": + for token in tokens[1:]: + if not token.startswith("-"): + ops.append({"verb": "remove", "unit": token, + "direction": "down"}) + return ops + + +def _ops_by_unit(arguments: Sequence[Dict[str, Any]]) -> Dict[str, Dict[str, List[Dict[str, str]]]]: + """argument id -> unit -> ops (in command order), for pair scanning.""" + out: Dict[str, Dict[str, List[Dict[str, str]]]] = {} + for argument in arguments: + per_unit: Dict[str, List[Dict[str, str]]] = {} + for command in argument.get("fix_commands", []) or []: + for op in parse_command_ops(command): + per_unit.setdefault(op["unit"], []).append(op) + out[argument["id"]] = per_unit + return out + + +def structural_attacks(arguments: Sequence[Dict[str, Any]]) -> List[Dict[str, Any]]: + """Attacks between matched rules whose fix commands target the same + unit with opposing verbs. Cross-rule only (a rule's own reinstall + never attacks itself); each attack carries unit + verbs as its reason. + """ + attacks: List[Dict[str, Any]] = [] + ops = _ops_by_unit(arguments) + for i, a in enumerate(arguments): + for b in arguments[i + 1:]: + a_id, b_id = a["id"], b["id"] + for unit in sorted(set(ops[a_id]) & set(ops[b_id])): + # First opposing verb pair in command order (deterministic). + opposing = [ + (op_a, op_b) + for op_a in ops[a_id][unit] + for op_b in ops[b_id][unit] + if op_a["direction"] != op_b["direction"] + ] + if not opposing: + continue + op_a, op_b = opposing[0] + # Opposing instructions contradict each other mutually: + # each rule's fix rebuts the other's, so the attack is + # registered in BOTH directions with the same evidence. + attacks.append({ + "attacker": a_id, "defender": b_id, "source": "structural", + "unit": unit, "verbs": f"{op_a['verb']} vs {op_b['verb']}", + "reason": (f"fix commands oppose each other on unit {unit!r}: " + f"{a_id} runs {op_a['verb']}, {b_id} runs {op_b['verb']}"), + }) + attacks.append({ + "attacker": b_id, "defender": a_id, "source": "structural", + "unit": unit, "verbs": f"{op_b['verb']} vs {op_a['verb']}", + "reason": (f"fix commands oppose each other on unit {unit!r}: " + f"{b_id} runs {op_b['verb']}, {a_id} runs {op_a['verb']}"), + }) + return attacks + + +def table_attacks(arguments: Sequence[Dict[str, Any]], + contradictions: Optional[Sequence[Dict[str, Any]]] = None + ) -> List[Dict[str, Any]]: + # Late binding of the module-level table: the default is looked up at + # CALL time, so a patched/test/future table constant is actually + # consulted (a def-time default would freeze the empty shipped table + # into the signature forever). + if contradictions is None: + contradictions = CONTRADICTIONS + """Attacks from the explicit CONTRADICTIONS table. Entries referencing + rules not in this report simply do not apply (a contradiction between + two rules is irrelevant when only one of them matched). + + Two entry shapes, both requiring reason + citation: + - {"rules": [a, b], ...} — a MUTUAL contradiction: each rule's fix + rebuts the other's, so the attack is registered in both directions; + - {"attacker": a, "defender": b, ...} — a DIRECTED defeat: a's fix + defeats b's one-way (e.g. a documented supersession). Dung's attack + relation is directed, and this shape is what lets a grounded winner + carry a defense set (structural opposition is always symmetric, so + by itself it can only produce undecided outcomes — see the module + docstring's honesty note on symmetric fights). + """ + known = {argument["id"] for argument in arguments} + attacks: List[Dict[str, Any]] = [] + for entry in contradictions: + keys = set(entry) + if keys not in ({"rules", "reason", "citation"}, + {"attacker", "defender", "reason", "citation"}): + raise ValueError( + "CONTRADICTIONS entry must have exactly the keys " + "['reason', 'citation'] plus either ['rules'] (mutual pair) " + f"or ['attacker', 'defender'] (directed), got {sorted(keys)}") + if not isinstance(entry["reason"], str) or not entry["reason"]: + raise ValueError("CONTRADICTIONS entry needs a non-empty reason") + if not isinstance(entry["citation"], str) or not entry["citation"]: + raise ValueError("CONTRADICTIONS entry needs a non-empty citation") + if "rules" in entry: + pair = entry["rules"] + if (not isinstance(pair, list) or len(pair) != 2 + or not all(isinstance(x, str) and x for x in pair) + or pair[0] == pair[1]): + raise ValueError( + f"CONTRADICTIONS entry 'rules' must be two distinct rule ids, got {pair!r}") + a, b = pair + edges = ((a, b), (b, a)) + else: + a, b = entry["attacker"], entry["defender"] + if (not isinstance(a, str) or not a or not isinstance(b, str) + or not b or a == b): + raise ValueError( + "CONTRADICTIONS entry 'attacker'/'defender' must be two " + f"distinct rule ids, got {a!r} -> {b!r}") + edges = ((a, b),) + for attacker, defender in edges: + if attacker in known and defender in known: + attacks.append({"attacker": attacker, "defender": defender, + "source": "table", "unit": None, "verbs": None, + "reason": entry["reason"], + "citation": entry["citation"]}) + return attacks + + +# --------------------------------------------------------------------------- +# From a diagnose() report to a verdict +# --------------------------------------------------------------------------- + +def arguments_from_report(report: Dict[str, Any], + rules_by_id: Optional[Dict[str, Dict[str, Any]]] = None + ) -> List[Dict[str, Any]]: + """READ-ONLY: each matched rule id of a diagnose() result becomes one + argument, carrying its title and fix summary for rendering plus the + fix command strings for structural conflict detection. Candidates + without a rule body (and without a rules_by_id fallback) carry no + commands — nothing is guessed about their fixes.""" + rules_by_id = rules_by_id or {} + arguments: List[Dict[str, Any]] = [] + for candidate in report.get("candidates", []) or []: + if not isinstance(candidate, dict): + continue + rule = candidate.get("rule") + rule_id = rule.get("id") if isinstance(rule, dict) else None + if rule_id is None: + rule_id = candidate.get("id") + if not isinstance(rule_id, str) or not rule_id: + continue + source = rule if isinstance(rule, dict) else rules_by_id.get(rule_id) + if source is None: + arguments.append({"id": rule_id, "title": None, + "fix_summary": "", "fix_commands": []}) + continue + title = source.get("title") + steps = source.get("fix") or [] + texts = [str(step.get("text", "")) for step in steps if isinstance(step, dict)] + commands = [str(step["command"]) for step in steps + if isinstance(step, dict) and isinstance(step.get("command"), str)] + arguments.append({ + "id": rule_id, + "title": title if isinstance(title, str) else None, + "fix_summary": " | ".join(text for text in texts if text), + "fix_commands": commands, + }) + return arguments + + +def resolve(report: Dict[str, Any], + rules_by_id: Optional[Dict[str, Dict[str, Any]]] = None, + contradictions: Optional[Sequence[Dict[str, Any]]] = None + ) -> Dict[str, Any]: + """The Dung verdict over one diagnose() report's matched rules. + + Returns a verdict dict: status ("no-conflict" | "resolved" | + "undecided"), the grounded extension, per-argument status (in / out / + undecided relative to grounded), attack edges with reasons, winners + WITH their defense set, losers WITH their undefeated attackers — and + when the grounded extension leaves a conflict undecided (odd attack + cycles, symmetric fights), an explicit "undecided between N admissible + positions" note with abstain=True: no winner is ever silently chosen. + """ + if contradictions is None: + contradictions = CONTRADICTIONS + arguments = arguments_from_report(report, rules_by_id) + attacks = table_attacks(arguments, contradictions) + structural_attacks(arguments) + framework = ArgumentationFramework( + [a["id"] for a in arguments], + [(edge["attacker"], edge["defender"]) for edge in attacks]) + grounded = framework.grounded_extension() + grounded_set = set(grounded) + + out_set: set = set() + for member in grounded: + out_set.update(framework.attackees_of(member)) + out_set -= grounded_set # grounded is conflict-free; safety only + + by_id = {a["id"]: a for a in arguments} + statuses: Dict[str, str] = {} + for argument in framework.arguments: + if argument in grounded_set: + statuses[argument] = "in" + elif argument in out_set: + statuses[argument] = "out" + else: + statuses[argument] = "undecided" + + verdict: Dict[str, Any] = { + "status": "no-conflict" if not attacks else "resolved", + "grounded": grounded, + "arguments": [{"id": a["id"], "title": a["title"], + "fix_summary": a["fix_summary"], + "status": statuses[a["id"]]} for a in arguments], + "attack_edges": attacks, + "winners": [], + "losers": [], + "undecided": None, + "abstained": False, + } + if not attacks: + return verdict + + # Winners: accepted rules that actually defeated an attacker, with the + # defense set showing which attacker and how. + for member in grounded: + defense = [{"defeated": edge["defender"], + "how": edge["reason"]} + for edge in attacks + if edge["attacker"] == member] + if defense: + verdict["winners"].append({ + "id": member, "title": by_id[member]["title"], + "fix_summary": by_id[member]["fix_summary"], + "defense": defense}) + + # Losers: rejected rules, with the accepted (hence undefeated) rules + # that defeated them. + for argument in framework.arguments: + if statuses[argument] != "out": + continue + undefeated = [{"id": edge["attacker"], "how": edge["reason"]} + for edge in attacks + if edge["defender"] == argument + and edge["attacker"] in grounded_set] + verdict["losers"].append({ + "id": argument, "title": by_id[argument]["title"], + "fix_summary": by_id[argument]["fix_summary"], + "undefeated_attackers": undefeated}) + + # A conflict the grounded extension leaves undecided: an edge whose + # BOTH endpoints are undecided (grounded accepted neither side and + # defeated neither side). Then the module ABSTAINS — no winner. + undecided_edges = [edge for edge in attacks + if statuses[edge["attacker"]] == "undecided" + and statuses[edge["defender"]] == "undecided"] + if undecided_edges: + verdict["status"] = "undecided" + verdict["abstained"] = True + undecided_arguments = [a for a in framework.arguments + if statuses[a] == "undecided"] + positions: Optional[List[List[str]]] = None + note: str + try: + positions = framework.preferred_extensions() + listed = " | ".join("(the empty set)" if not p + else "(" + ", ".join(p) + ")" + for p in positions) + note = (f"undecided between {len(positions)} admissible " + f"position{'s' if len(positions) != 1 else ''}: {listed} — " + "abstaining from a winner") + except ValueError as exc: + note = (f"undecided, and preferred-extension enumeration was refused " + f"({exc}); only the grounded verdict is reported — " + "abstaining from a winner") + verdict["undecided"] = { + "arguments": undecided_arguments, + "positions": positions, + "note": note, + } + return verdict + + +def conflict_resolution(report: Dict[str, Any], + rules_by_id: Optional[Dict[str, Dict[str, Any]]] = None, + contradictions: Optional[Sequence[Dict[str, Any]]] = None + ) -> Optional[Dict[str, Any]]: + """READ-ONLY CLI helper: resolve(report) when the matched rules + actually conflict, else None (no conflicts -> no section rendered).""" + verdict = resolve(report, rules_by_id=rules_by_id, + contradictions=contradictions) + if verdict["status"] == "no-conflict": + return None + return verdict + + +def render_conflict_lines(verdict: Dict[str, Any]) -> List[str]: + """Render the conflict-resolution section (deterministic plain text).""" + by_id = {a["id"]: a for a in verdict["arguments"]} + lines = ["Conflict resolution (Dung 1995, Artificial Intelligence 77 — " + "grounded semantics; why one fix won, nothing auto-applied):"] + lines.append(" Conflicting matched rules:") + for edge in verdict["attack_edges"]: + lines.append(f" - {edge['attacker']} -> {edge['defender']}" + f" [{edge['source']}]: {edge['reason']}") + for winner in verdict["winners"]: + title = f": {winner['title']}" if winner.get("title") else "" + lines.append(f" Accepted (winner) {winner['id']}{title}") + for defense in winner["defense"]: + lines.append(f" defeats {defense['defeated']} ({defense['how']})") + for loser in verdict["losers"]: + title = f": {loser['title']}" if loser.get("title") else "" + lines.append(f" Rejected (loser) {loser['id']}{title}") + for attacker in loser["undefeated_attackers"]: + lines.append(f" defeated by {attacker['id']} ({attacker['how']})") + if verdict["status"] == "undecided" and verdict["undecided"]: + lines.append(" UNDECIDED — the grounded extension accepts no side of " + "the remaining conflict:") + lines.append(f" {verdict['undecided']['note']}") + lines.append(" No winner is chosen; both fixes are printed above — " + "the human decides.") + return lines diff --git a/plugins/caelestia-assistant/assistant/capabilities/diagnostics/cli.py b/plugins/caelestia-assistant/assistant/capabilities/diagnostics/cli.py new file mode 100755 index 0000000..d389c1c --- /dev/null +++ b/plugins/caelestia-assistant/assistant/capabilities/diagnostics/cli.py @@ -0,0 +1,9 @@ +"""CLI shim: python -m assistant.capabilities.diagnostics.cli + +Delegates to engine.main so the command surface stays in one place. +""" + +from .engine import main + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/plugins/caelestia-assistant/assistant/capabilities/diagnostics/drain.py b/plugins/caelestia-assistant/assistant/capabilities/diagnostics/drain.py new file mode 100644 index 0000000..5db6f79 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/capabilities/diagnostics/drain.py @@ -0,0 +1,366 @@ +"""diagnostics.drain — a streaming Drain log-template miner, wired in +FRONT of the rule engine so a line no signature matches gets templated +instead of silently discarded. + +He, Zhu, He & Lyu, "Drain: An Online Log Parsing Approach with Fixed +Depth Tree", IEEE ICSM 2017. The mechanism, adapted not invented: + + * PREPROCESS — tokens matching a known-shape regex (IPv4, decimal + numbers, long hex blobs) are masked to ``<*>``-style parameter + placeholders (the paper's masking step; the default patterns are + the paper's own examples, overridable per constructor); + * PARSE TREE — a fixed-depth trie: level 1 splits on the FIRST + token (a masked first token routes to the dedicated ``<*>`` + child, per the paper), level 2 splits on TOKEN COUNT, and the + leaf list holds the LogClusters; a candidate joins the leaf + cluster whose template is most position-wise similar, measured + by the paper's SimSeq (equal tokens at equal positions / length); + * MERGE — a candidate at or above ``sim_threshold`` (the paper's + simThresh, 0.4) updates its cluster: every divergent position + becomes ``<*>``; below it, a new cluster is born. + +One pass, bounded memory, no training, no model: the tree only ever +grows to ``max_children`` per node (beyond the cap the paper's own +fallback applies — the candidate routes to the node's ``<*>`` +child) and ``max_clusters`` total (past the cap a genuinely new +template is counted in the OVERFLOW bucket and reported as +unclustered — an honest capacity refusal, never a silent eviction). + +WHAT THIS IS NOT (the honesty the prompt asks for, stated twice): +Drain clusters SHAPES, not CAUSES. A template earning recurrence is a +signal that a HUMAN should consider writing a real diagnostic rule for +it — it is not a diagnosis, carries no fix, and joins no settings tool +(only a human-authored rule gets the settings reverse-join, because +only a rule asserts a root cause). Recurrence counts and first-seen +dates are bookkeeping for that human decision. + +Timestamps: ``update(line, when=...)`` records the CALLER-SUPPLIED +date string (determinism: nothing here reads the clock; live callers +pass ``datetime.now(timezone.utc).date().isoformat()``). A miner run +without dates reports counts only — honestly undated, never backdated. + +State moves only through plain dicts (``to_dict`` / ``from_dict``) for +the caller's learned-state JSON path (brain/state.py) — this module +writes NOTHING itself. Pure stdlib; no RNG; deterministic given the +input stream (leaf search scans clusters in insertion order, the +first at-or-above the threshold wins — the paper's own tie handling). +""" +from __future__ import annotations + +import re +from typing import Any, Dict, List, Optional, Sequence + +__all__ = [ + "STATE_KEY", "SHAPES_NOT_CAUSES", "DEFAULT_SIM_THRESHOLD", + "DEFAULT_MAX_CHILDREN", "DEFAULT_MAX_CLUSTERS", "MASK_TOKEN", + "DrainMiner", "mask_token", "mine", "augment_diagnosis", + "render_unmatched_lines", +] + +STATE_KEY = "drain_miner" + +SHAPES_NOT_CAUSES = ( + "Drain clusters shapes, not causes: a recurring template is a " + "candidate for a human-written diagnostic rule, not a diagnosis" +) + +DEFAULT_SIM_THRESHOLD = 0.4 +DEFAULT_MAX_CHILDREN = 12 +DEFAULT_MAX_CLUSTERS = 2048 +MASK_TOKEN = "<*>" + +# The paper's preprocessing masks parameters before the tree sees the +# line. These are the paper's own shape families (IPv4, decimal +# numbers, long hex blobs); callers may add domain patterns per +# constructor. Order matters: the first matching pattern wins. +DEFAULT_MASK_PATTERNS = ( + re.compile(r"\b\d{1,3}(?:\.\d{1,3}){3}\b"), # IPv4 + re.compile(r"\b[0-9a-fA-F]{8,}\b"), # hex blobs + re.compile(r"(? str: + """Mask ONE token: the first matching shape family wins. Empty + patterns list means no masking (caller's explicit choice).""" + for pattern in patterns: + if pattern.search(token): + return MASK_TOKEN + return token + + +class _Node: + """One parse-tree node: either an internal splitter (children) or a + leaf list of cluster ids. Bounded: children grow past the cap into + the node's ``<*>`` fallback child.""" + + __slots__ = ("children", "fallback", "leaf") + + def __init__(self) -> None: + self.children: Dict[str, "_Node"] = {} + self.fallback: Optional["_Node"] = None + self.leaf: List[int] = [] # cluster ids, insertion order + + +class DrainMiner: + """The streaming miner. ``update`` one line at a time (or batch via + ``mine``); serialize through ``to_dict`` / ``from_dict``.""" + + def __init__(self, + sim_threshold: float = DEFAULT_SIM_THRESHOLD, + max_children: int = DEFAULT_MAX_CHILDREN, + max_clusters: int = DEFAULT_MAX_CLUSTERS, + mask_patterns: Optional[Sequence[re.Pattern]] = None + ) -> None: + if not (0.0 < sim_threshold <= 1.0): + raise ValueError( + f"sim_threshold must be inside (0, 1], got {sim_threshold!r}") + if max_children < 1: + raise ValueError(f"max_children must be >= 1, got {max_children!r}") + if max_clusters < 1: + raise ValueError(f"max_clusters must be >= 1, got {max_clusters!r}") + self.sim_threshold = float(sim_threshold) + self.max_children = int(max_children) + self.max_clusters = int(max_clusters) + self.mask_patterns = (list(mask_patterns) if mask_patterns is not None + else list(DEFAULT_MASK_PATTERNS)) + self.root = _Node() + # clusters[i] = {"template": [tokens], "count": n, + # "first_seen": date-or-None, "last_seen": ..., + # "example": str} + self.clusters: List[Dict[str, Any]] = [] + self.overflow: Dict[str, int] = {} # template key -> count + self.n_lines = 0 + + # ------------------------------------------------------------------ + # similarity (the paper's SimSeq, over equal-count token lists) + # ------------------------------------------------------------------ + + @staticmethod + def _similarity(a: Sequence[str], b: Sequence[str]) -> float: + if not a or len(a) != len(b): + return 0.0 + equal = sum(1 for x, y in zip(a, b) if x == y) + return equal / len(a) + + # ------------------------------------------------------------------ + # traversal + # ------------------------------------------------------------------ + + def _route(self, tokens: List[str]) -> List[int]: + """Walk root -> first-token level -> token-count level; return + the leaf list. The paper's fixed-depth structure, with the + maxChild fallback into the ``<*>`` child.""" + node = self.root + first = tokens[0] if tokens else MASK_TOKEN + child_key = first + if child_key in node.children: + node = node.children[child_key] + elif len(node.children) >= self.max_children: + if node.fallback is None: + node.fallback = _Node() + node = node.fallback + else: + node = node.children.setdefault(child_key, _Node()) + + count_key = str(len(tokens)) + if count_key in node.children: + node = node.children[count_key] + elif len(node.children) >= self.max_children: + if node.fallback is None: + node.fallback = _Node() + node = node.fallback + else: + node = node.children.setdefault(count_key, _Node()) + return node.leaf + + def update(self, line: str, when: Optional[str] = None) -> Dict[str, Any]: + """One line in, its (possibly pre-existing) cluster out. ``when`` + is the caller-supplied ISO date string for first/last-seen + bookkeeping (None = undated, honestly). Empty lines are + REFUSED — there is no honest template for nothing.""" + if not line or not line.strip(): + raise ValueError("drain.update: empty line (nothing to template)") + tokens = [mask_token(tok, self.mask_patterns) + for tok in line.split()] + self.n_lines += 1 + leaf = self._route(tokens) + + best_id: Optional[int] = None + best_sim = -1.0 + for cid in leaf: + sim = self._similarity(self.clusters[cid]["template"], tokens) + if sim > best_sim: + best_sim = sim + best_id = cid + if best_id is not None and best_sim >= self.sim_threshold: + cluster = self.clusters[best_id] + cluster["count"] += 1 + cluster["template"] = [ + old if old == new else MASK_TOKEN + for old, new in zip(cluster["template"], tokens)] + cluster["last_seen"] = when if when is not None else cluster["last_seen"] + return self._cluster_row(cluster) + + if len(self.clusters) >= self.max_clusters: + key = " ".join(tokens) + self.overflow[key] = self.overflow.get(key, 0) + 1 + return {"cluster_id": None, "template": key, "count": + self.overflow[key], "first_seen": None, + "last_seen": None, "overflowed": True, + "example": line} + + cluster = { + "template": list(tokens), + "count": 1, + "first_seen": when, + "last_seen": when, + "example": line, + } + self.clusters.append(cluster) + leaf.append(len(self.clusters) - 1) + return self._cluster_row(cluster) + + # ------------------------------------------------------------------ + # reporting + # ------------------------------------------------------------------ + + @staticmethod + def _cluster_row(cluster: Dict[str, Any]) -> Dict[str, Any]: + return {"cluster_id": None, # ids are positional, not persisted + "template": " ".join(cluster["template"]), + "count": cluster["count"], + "first_seen": cluster.get("first_seen"), + "last_seen": cluster.get("last_seen"), + "overflowed": False, + "example": cluster.get("example")} + + def templates(self, min_count: int = 1) -> List[Dict[str, Any]]: + """All clusters (and any overflow templates) as report rows, + count descending, template ascending — deterministic. Rows are + freshly built (no positional ids leak).""" + rows = [self._cluster_row(c) for c in self.clusters] + for key, count in sorted(self.overflow.items()): + rows.append({"cluster_id": None, "template": key, + "count": count, "first_seen": None, + "last_seen": None, "overflowed": True, + "example": None}) + rows = [r for r in rows if r["count"] >= min_count] + rows.sort(key=lambda r: (-r["count"], r["template"])) + return rows + + # ------------------------------------------------------------------ + # persistence (plain dicts; the caller's learned-state JSON path) + # ------------------------------------------------------------------ + + def to_dict(self) -> Dict[str, Any]: + return { + "sim_threshold": self.sim_threshold, + "max_children": self.max_children, + "max_clusters": self.max_clusters, + "n_lines": self.n_lines, + "clusters": [dict(c) for c in self.clusters], + "overflow": dict(self.overflow), + } + + @classmethod + def from_dict(cls, state: Dict[str, Any]) -> "DrainMiner": + miner = cls(sim_threshold=state.get("sim_threshold", + DEFAULT_SIM_THRESHOLD), + max_children=state.get("max_children", + DEFAULT_MAX_CHILDREN), + max_clusters=state.get("max_clusters", + DEFAULT_MAX_CLUSTERS)) + miner.clusters = [dict(c) for c in state.get("clusters", [])] + miner.overflow = dict(state.get("overflow", {})) + miner.n_lines = int(state.get("n_lines", 0)) + # the parse tree itself is never persisted — rebuild leaf + # membership by re-routing each stored template (identical + # routing decisions, since routing is a pure function of the + # template tokens) + for cid, cluster in enumerate(miner.clusters): + leaf = miner._route(list(cluster["template"])) + if cid not in leaf: + leaf.append(cid) + return miner + + def capacity(self) -> Dict[str, Any]: + """The honest capacity report: how full the tree is, and whether + overflow is being dropped into the bucket.""" + return {"clusters": len(self.clusters), "max_clusters": self.max_clusters, + "overflowed_keys": len(self.overflow), + "overflowed_lines": sum(self.overflow.values())} + + +# --------------------------------------------------------------------------- +# Batch + rule-engine integration +# --------------------------------------------------------------------------- + + +def mine(lines: Sequence[str], miner: Optional[DrainMiner] = None, + when: Optional[str] = None) -> Dict[str, Any]: + """Batch convenience: feed every non-empty line through ``update``. + Returns the miner's capacity report plus the ranked templates — the + same rows ``templates()`` yields.""" + miner = miner if miner is not None else DrainMiner() + for line in lines: + if line.strip(): + miner.update(line, when) + return {"capacity": miner.capacity(), + "n_lines": miner.n_lines, + "templates": miner.templates(), + "note": SHAPES_NOT_CAUSES} + + +def augment_diagnosis(diagnosis: Dict[str, Any], text: str, + miner: Optional[DrainMiner] = None) -> Dict[str, Any]: + """The IN FRONT wiring: when the rule engine answered NO_MATCH (or + AMBIGUOUS — candidates exist but the engine refused to pick one), + the lines that no signature matched are TEMPLATED here instead of + being silently discarded. ``diagnosis`` gains one additive key, + ``unmatched_templates``: + + {"rows": [...], "note": SHAPES_NOT_CAUSES, "dated": bool} + + MATCH verdicts are untouched (a matched rule IS the diagnosis; the + template miner has nothing to add and would only dilute the + report). A caller-held persisted ``miner`` supplies recurrence and + first-seen dates across calls; the default stateless run counts + within THIS input only and says so. Nothing here joins a settings + tool: only human-authored rules earn the settings reverse-join, + because only a rule asserts a root cause.""" + verdict = diagnosis.get("verdict") + if verdict not in ("NO_MATCH", "AMBIGUOUS"): + return diagnosis + if miner is None: + miner = DrainMiner() + dated = False + else: + dated = any(row.get("first_seen") for row in miner.templates()) + lines = [ln for ln in text.splitlines() if ln.strip()] + for line in lines: + miner.update(line) + rows = miner.templates() + diagnosis["unmatched_templates"] = { + "rows": rows[:16], + "n_lines": len(lines), + "dated": dated, + "note": SHAPES_NOT_CAUSES, + } + return diagnosis + + +def render_unmatched_lines(unmatched: Dict[str, Any]) -> List[str]: + """The report block for ``unmatched_templates`` (engine.render_report + calls this). Plain text, nothing executable.""" + lines: List[str] = [] + lines.append("Unmatched-line templates (Drain, He et al. 2017 — shapes, not causes):") + for row in unmatched.get("rows", []): + when = row.get("first_seen") + seen = f", first seen {when}" if when else "" + flag = " [OVERFLOW — capacity cap reached]" if row.get("overflowed") else "" + lines.append(f" - [{row['count']}x{seen}]{flag} {row['template'][:160]}") + if not unmatched.get("rows"): + lines.append(" - (no recurring shape in this input)") + lines.append(f" Note: {unmatched.get('note', SHAPES_NOT_CAUSES)}.") + return lines diff --git a/plugins/caelestia-assistant/assistant/capabilities/diagnostics/engine.py b/plugins/caelestia-assistant/assistant/capabilities/diagnostics/engine.py new file mode 100755 index 0000000..d412150 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/capabilities/diagnostics/engine.py @@ -0,0 +1,745 @@ +"""Layer 1 diagnostic engine: load rules, match signatures, render a plan. + +Guarantees: +- Pure stdlib; no subprocess/os.system anywhere — this module has no way to + execute the commands it suggests. Suggested commands are inert strings. +- Deterministic: identical input always produces an identical report. No + fuzzy matching, no first-match-wins, no silent tie-breaking. +- Ambiguity is surfaced, not hidden: when two rules match within the margin, + the report lists the top candidates and asks a clarifying question. + +Matcher semantics: +- {"allOf": [leaves]} — gate: every required leaf must hold. +- {"anyOf": [leaves]} — met when at least one *required* member holds; + optional members add evidence only. +- Leaves: text_regex, text_substring, file_exists, cmd_output. + file_exists is the only probe the engine performs itself (os.path, read + only). cmd_output is satisfied only by output the user pasted. + +Scoring (fixed weights, no ML): + required text match +2 + required file_exists satisfied +3 + required cmd_output confirmed +3 + each optional leaf matched +1 + deterministic rule passing gate +2 + +Ranking is the stable tuple + (-score, deterministic-first, id). +""" + +from __future__ import annotations + +import glob +import json +import os +import re +import sys +from pathlib import Path +from typing import Any, Dict, List, Optional, Tuple + +from . import argumentation +from . import rete +from .settings_join import settings_tools_for_rule + +RULES_DIR = Path(__file__).resolve().parent / "rules.d" + +CONFIDENCE_RANK = {"deterministic": 0, "probable": 1} + +ANSI_RE = re.compile(r"\x1b\[[0-9;]*[A-Za-z]") + +# Only these variables are expanded inside file_exists paths; everything +# else is left literal so a typo can never point somewhere unintended. +ENV_ALLOWLIST = ["HOME", "XDG_CACHE_HOME", "XDG_CONFIG_HOME", "XDG_STATE_HOME", "XDG_RUNTIME_DIR"] + +COMMAND_PREFIX = "SUGGESTED_NOT_EXECUTED:" + +VALID_CATEGORIES = [ + "install", + "runtime-shell", + "runtime-lockscreen", + "config", + "network", + "kde", + "post-install", + "uninstall", + "update", + "folder-cleanup", +] + +VALID_SEVERITIES = ["critical", "high", "medium", "low", "info"] +VALID_RISKS = ["READ_ONLY", "STATE_CHANGING", "PRIVILEGED", "DESTRUCTIVE"] + + +class RuleError(ValueError): + """Raised when a rule file violates the schema.""" + + +# --------------------------------------------------------------------------- +# Rule validation (structural; used at load time) +# --------------------------------------------------------------------------- + + +def _walk_matchers(node: Dict[str, Any], depth: int = 1) -> List[Dict[str, Any]]: + """Collect leaves of a matcher tree; combinators nest at most one level.""" + if depth > 2: + raise ValueError("matcher tree nests deeper than one combinator level") + if "allOf" in node or "anyOf" in node: + members = node.get("allOf") or node.get("anyOf") or [] + leaves: List[Dict[str, Any]] = [] + for member in members: + if "allOf" in member or "anyOf" in member: + leaves.extend(_walk_matchers(member, depth + 1)) + else: + leaves.append(member) + return leaves + return [node] + + +def validate_rule(rule: Dict[str, Any], source: str = "") -> List[str]: + """Structural validation of one rule; returns a list of failures.""" + from . import risk as risk_mod + + failures: List[str] = [] + rule_id = rule.get("id", "") + + for field in ("id", "title", "category", "severity", "confidence", "matchers", "fix"): + if field not in rule: + failures.append(f"{source} {rule_id}: missing required field {field!r}") + if failures: + return failures + + if rule["category"] not in VALID_CATEGORIES: + failures.append(f"{source} {rule_id}: bad category {rule['category']!r}") + if rule["severity"] not in VALID_SEVERITIES: + failures.append(f"{source} {rule_id}: bad severity {rule['severity']!r}") + if rule["confidence"] not in CONFIDENCE_RANK: + failures.append(f"{source} {rule_id}: bad confidence {rule['confidence']!r}") + + try: + leaves = _walk_matchers(rule["matchers"]) + except ValueError as exc: + failures.append(f"{source} {rule_id}: {exc}") + return failures + + for leaf in leaves: + kind = leaf.get("type") + if kind == "text_regex": + try: + re.compile(leaf.get("pattern", "")) + except re.error as exc: + failures.append(f"{source} {rule_id}: invalid regex {leaf.get('pattern')!r}: {exc}") + elif kind == "text_substring": + if not isinstance(leaf.get("value"), str): + failures.append(f"{source} {rule_id}: text_substring missing value") + elif kind == "file_exists": + if "path" not in leaf: + failures.append(f"{source} {rule_id}: file_exists missing path") + elif leaf.get("expected", "present") not in ("present", "absent"): + failures.append(f"{source} {rule_id}: file_exists bad expected") + elif kind == "cmd_output": + if "command" not in leaf or "pattern" not in leaf: + failures.append(f"{source} {rule_id}: cmd_output needs command+pattern") + else: + failures.append(f"{source} {rule_id}: unknown matcher type {kind!r}") + + if not isinstance(rule["fix"], list) or not rule["fix"]: + failures.append(f"{source} {rule_id}: fix must be a non-empty list") + return failures + + for step in rule["fix"]: + if not isinstance(step, dict): + failures.append(f"{source} {rule_id}: fix steps must be objects") + continue + if "command" in step and step.get("command_risk") not in risk_mod.RISK_ORDER: + failures.append( + f"{source} {rule_id}: command step missing/invalid command_risk {step.get('command_risk')!r}" + ) + return failures + + +# --------------------------------------------------------------------------- +# Rule loading +# --------------------------------------------------------------------------- + + +def load_rules(rules_dir: Optional[Path] = None) -> List[Dict[str, Any]]: + """Load and validate every rules.d/*.json file, sorted by filename.""" + directory = Path(rules_dir) if rules_dir else RULES_DIR + rule_files = sorted(glob.glob(str(directory / "*.json"))) + if not rule_files: + raise RuleError(f"no rule files found in {directory}") + rules: List[Dict[str, Any]] = [] + seen_ids: set = set() + for path in rule_files: + with open(path, "r", encoding="utf-8") as handle: + envelope = json.load(handle) + if envelope.get("schema_version") != 1: + raise RuleError(f"{path}: unsupported schema_version") + for rule in envelope.get("rules", []): + validate_rule(rule, source=str(path)) + if rule["id"] in seen_ids: + raise RuleError(f"{path}: duplicate rule id {rule['id']}") + seen_ids.add(rule["id"]) + rules.append(rule) + return rules + + +# --------------------------------------------------------------------------- +# Input normalization +# --------------------------------------------------------------------------- + + +def normalize_input(text: str) -> str: + """Strip terminal noise so signatures match what the user meant.""" + text = ANSI_RE.sub("", text) + text = text.replace("\r\n", "\n").replace("\r", "\n") + text = re.sub(r"\n{3,}", "\n\n", text) + return text + + +# --------------------------------------------------------------------------- +# Matcher evaluation +# --------------------------------------------------------------------------- + + +def _expand_path(path: str) -> str: + """Expand ~ and the allow-listed XDG vars in a file probe path.""" + out = os.path.expanduser(path) + for var in ENV_ALLOWLIST: + token = f"${var}" + if token in out: + out = out.replace(token, os.environ.get(var, "")) + token = f"${{{var}}}" + if token in out: + out = out.replace(token, os.environ.get(var, "")) + return out + + +def _matched_lines(pattern: str, case_insensitive: bool, text: str) -> List[str]: + """Return the input lines a pattern matched, for evidence display.""" + flags = re.IGNORECASE if case_insensitive else 0 + lines: List[str] = [] + for line in text.split("\n"): + if re.search(pattern, line, flags): + lines.append(line.strip()) + return lines + + +TEXT_LEAF_TYPES = ("text_regex", "text_substring") + + +def eval_leaf(leaf: Dict[str, Any], text: str) -> Tuple[bool, Optional[str]]: + """Evaluate one matcher leaf. + + Returns (satisfied, evidence). For cmd_output leaves that the user has + not corroborated, returns (False, None) — an unresolved probe is treated + as unmet evidence, never as a hard gate failure (see module docstring). + """ + kind = leaf.get("type") + ci = bool(leaf.get("case_insensitive", False)) + + if kind == "text_regex": + pattern = leaf["pattern"] + flags = re.IGNORECASE if ci else 0 + hit = re.search(pattern, text, flags) is not None + evidence = _matched_lines(pattern, ci, text) + return hit, (evidence[0] if evidence else None) + + if kind == "text_substring": + value = leaf["value"] + if ci: + hit = value.lower() in text.lower() + line = next((ln for ln in text.split("\n") if value.lower() in ln.lower()), None) + else: + hit = value in text + line = next((ln for ln in text.split("\n") if value in ln), None) + return hit, line + + if kind == "file_exists": + expanded = _expand_path(leaf["path"]) + exists = os.path.exists(expanded) + expected = leaf.get("expected", "present") + satisfied = exists if expected == "present" else not exists + shown = "present" if exists else "absent" + return satisfied, f"{leaf['path']} -> {shown}" + + if kind == "cmd_output": + # Never executed. Satisfied only when the user's paste contains the + # command itself and its pattern matches the pasted output. + command = leaf["command"] + pattern = leaf["pattern"] + flags = re.IGNORECASE if bool(leaf.get("case_insensitive", True)) else 0 + if command in text and re.search(pattern, text, flags): + line = _matched_lines(re.escape(command), False, text) + return True, line[0] if line else command + return False, None + + raise RuleError(f"unknown matcher type: {kind!r}") + + +def _is_combinator(node: Dict[str, Any]) -> bool: + return isinstance(node, dict) and ("allOf" in node or "anyOf" in node) + + +def eval_matchers(node: Dict[str, Any], text: str) -> Tuple[bool, List[str], int]: + """Evaluate a matcher tree (combinators nested at most one level). + + Returns (gate_passed, evidence_lines, score_contribution). Scoring + follows the fixed weight table in the module docstring; required leaves + only contribute when satisfied, optional leaves contribute +1. + """ + evidence: List[str] = [] + score_contrib = 0 + + if _is_combinator(node): + kind = "allOf" if "allOf" in node else "anyOf" + members = node[kind] + passed = True + any_required = [m for m in members if bool(m.get("required", True))] + any_required_met = False + for member in members: + ok, ev, contrib = eval_matchers(member, text) + evidence.extend(ev) + score_contrib += contrib + required = bool(member.get("required", True)) + if required: + if not ok: + passed = False + else: + any_required_met = True + if kind == "anyOf": + # anyOf is met when at least one required member holds; a + # group of only optional members is met if any member matched. + passed = any_required_met if any_required else any( + bool(m.get("required", True)) is False and _leaf_ok(m, text) for m in members + ) + if not members: + passed = False + return passed, evidence, score_contrib + + # Plain leaf. + ok, ev = eval_leaf(node, text) + if ev: + evidence.append(ev) + required = bool(node.get("required", True)) + if required: + if ok: + if node.get("type") in TEXT_LEAF_TYPES: + score_contrib += 2 + else: + score_contrib += 3 # engine-verified or user-pasted evidence + elif ok: + score_contrib += 1 + return ok, evidence, score_contrib + + +def _leaf_ok(node: Dict[str, Any], text: str) -> bool: + ok, _ev, _score = eval_matchers(node, text) + return ok + + +# --------------------------------------------------------------------------- +# Scoring and decision +# --------------------------------------------------------------------------- + + +def score_rule(rule: Dict[str, Any], text: str) -> Optional[Dict[str, Any]]: + """Score one rule against normalized text. + + Returns None when the required gate fails, otherwise a result dict. + """ + passed, evidence, score = eval_matchers(rule["matchers"], text) + if not passed: + return None + + if rule.get("confidence") == "deterministic": + score += 2 + return { + "rule": rule, + "score": score, + "evidence": evidence, + } + + +def rank_results(results: List[Dict[str, Any]]) -> List[Dict[str, Any]]: + """Stable total ordering: score desc, deterministic first, id asc.""" + + def key(result: Dict[str, Any]) -> Tuple[Any, ...]: + rule = result["rule"] + return ( + -result["score"], + CONFIDENCE_RANK.get(rule.get("confidence", "probable"), 1), + rule["id"], + ) + + return sorted(results, key=key) + + +def diagnose(text: str, rules: Optional[List[Dict[str, Any]]] = None, top: int = 3) -> Dict[str, Any]: + """Run the full deterministic pipeline over one input blob. + + Verdicts: + MATCH — exactly one gate-passing rule, or a clear margin (>=2 + points) over the runner-up. + AMBIGUOUS — several candidates within the margin; report top N with + clarify probes. Never silently pick one. + NO_MATCH — nothing passed its gate; the honest answer is "I don't + know", plus pointers to diagnostic commands and Layer 2. + """ + normalized = normalize_input(text) + rules = rules if rules is not None else load_rules() + results = [] + for rule in rules: + result = score_rule(rule, normalized) + if result is not None: + results.append(result) + ranked = rank_results(results) + + # A4 — reverse lookup: attach the settings tools (if any) that address + # each matched rule's root cause, via the citation registry join. A + # pure, additive key: rules with no settings surface carry []. + for result in ranked: + result["settings_tools"] = settings_tools_for_rule(result["rule"])["tools"] + + if not ranked: + result = {"verdict": "NO_MATCH", "candidates": [], "top": None} + # exponential-build-4 A: lines no signature matched are TEMPLATED + # (Drain, He et al. 2017) instead of silently discarded — shapes, + # not causes, for a human to consider turning into a real rule. + from . import drain + return drain.augment_diagnosis(result, normalized) + + if len(ranked) == 1: + margin: Optional[int] = None + else: + margin = ranked[0]["score"] - ranked[1]["score"] + + single = len(ranked) == 1 or (margin is not None and margin >= 2) + if single: + return { + "verdict": "MATCH", + "candidates": ranked[:top], + "top": ranked[0], + "margin": margin, + } + return { + "verdict": "AMBIGUOUS", + "candidates": ranked[:top], + "top": ranked[0], + "margin": margin, + } + + +def _drain_lines(diagnosis: Dict[str, Any]) -> List[str]: + """exponential-build-4 A: the Drain template block for the report, + rendered only when the augment step actually attached templates.""" + from . import drain + unmatched = diagnosis.get("unmatched_templates") + if not unmatched: + return [] + return drain.render_unmatched_lines(unmatched) + + +# --------------------------------------------------------------------------- +# Rendering (plain text, human readable, nothing executable) +# --------------------------------------------------------------------------- + + +def _format_refs(rule: Dict[str, Any]) -> str: + parts: List[str] = [] + for ref in rule.get("references", []): + if ref.get("kind") == "doc": + parts.append(f"docs/TROUBLESHOOTING.md {ref.get('anchor', '')}".rstrip()) + elif ref.get("kind") == "issue": + closing = f", closing PR #{ref['closing_pr']}" if ref.get("closing_pr") else "" + parts.append(f"issue #{ref.get('number')} ({ref.get('state', '?')}{closing})") + return "; ".join(parts) if parts else "-" + + +def render_result(result: Dict[str, Any]) -> str: + rule = result["rule"] + conf = rule.get("confidence", "probable") + out: List[str] = [] + out.append(f"Rule {rule['id']} [{conf}/{rule.get('severity', '?')}]") + out.append(f" {rule.get('title', '')}") + evidence = result.get("evidence") or [] + if evidence: + out.append(" Evidence:") + for ev in evidence[:6]: + out.append(f" - {ev}") + fix_steps = rule.get("fix", []) + if fix_steps: + out.append(" Suggested fix (review every step; nothing is run for you):") + for idx, step in enumerate(fix_steps, start=1): + out.append(f" {idx}. {step.get('text', '')}") + command = step.get("command") + if command: + out.append(f" {COMMAND_PREFIX} {command}") + risk_tier = step.get("command_risk", "STATE_CHANGING") + out.append(f" [risk: {risk_tier}]") + if step.get("warning"): + out.append(f" WARNING: {step['warning']}") + if step.get("undo"): + out.append(f" undo: {step['undo']}") + refs = _format_refs(rule) + out.append(f" References: {refs}") + settings_tools = result.get("settings_tools") or settings_tools_for_rule(rule)["tools"] + if settings_tools: + listing = ", ".join( + f"{entry['tool']} ({entry['path']})" for entry in settings_tools + ) + out.append(f" Settings tools addressing this root cause: {listing}") + if rule.get("clarify_probe"): + out.append(f" Clarify: {rule['clarify_probe']}") + return "\n".join(out) + + +def render_report(diagnosis: Dict[str, Any]) -> str: + lines: List[str] = [] + lines.append("caelestia assistant — layer 1 diagnostics (deterministic rules)") + lines.append("Nothing was executed, nothing was sent anywhere; this is a printed plan only.") + lines.append("") + verdict = diagnosis["verdict"] + if verdict == "NO_MATCH": + lines.append("Verdict: NO known signature matched.") + lines.append("") + lines.extend(_drain_lines(diagnosis)) + lines.append("") + lines.append("Honest next steps instead of a guess:") + lines.append(" 1. Enable Debug Mode (Nexus -> About -> Advanced), reproduce, then run:") + lines.append(" SUGGESTED_NOT_EXECUTED: journalctl --user -u caelestia-shell --no-pager -n 200") + lines.append(" 2. Skim the catalog: docs/TROUBLESHOOTING.md (section 11 lists diagnostic commands).") + lines.append(" 3. If nothing fits, draft an issue report:") + lines.append(" SUGGESTED_NOT_EXECUTED: python3 -m assistant.capabilities.issues.cli draft --help") + return "\n".join(lines) + + if verdict == "MATCH": + lines.append(f"Verdict: MATCH (single strong candidate, margin {diagnosis.get('margin')} pts).") + else: + lines.append("Verdict: AMBIGUOUS — several rules fit; pick one or paste the probe output.") + lines.append("") + for idx, result in enumerate(diagnosis["candidates"], start=1): + lines.append(f"[{idx}] {render_result(result)}") + lines.append("") + + # Read-only enrichment (exponential-build-3 A1/A2): derived composite + # evidence (Rete, rete.py) and conflict resolution (Dung, + # argumentation.py) computed from THIS diagnosis without touching the + # matching semantics above — rendered only when they fire, nothing + # when they do not. + derived = rete.derived_evidence(diagnosis) + if derived is not None: + lines.extend(rete.render_derived_lines(derived)) + lines.append("") + conflicts = argumentation.conflict_resolution(diagnosis) + if conflicts is not None: + lines.extend(argumentation.render_conflict_lines(conflicts)) + lines.append("") + + lines.append("Commands above are suggestions to copy-paste after review. The assistant") + lines.append("cannot execute them, cannot reach the network, and never edits your config.") + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# CLI entry (python -m assistant.capabilities.diagnostics.cli) +# --------------------------------------------------------------------------- + + +def main(argv: Optional[List[str]] = None) -> int: + import argparse + + parser = argparse.ArgumentParser( + prog="caelestia-assist diagnose", + description="Deterministic troubleshooting for caelestia-kde (reads text, prints a plan, runs nothing).", + ) + sub = parser.add_subparsers(dest="cmd", required=True) + + diag = sub.add_parser("diagnose", help="match pasted text/logs against known signatures") + diag.add_argument("input", nargs="?", default="-", help="text/log file to read, or - for stdin") + diag.add_argument("--json", action="store_true", help="emit machine-readable JSON instead of text") + diag.add_argument("--top", type=int, default=3, help="max candidates shown when ambiguous") + + sub.add_parser("selfcheck", help="validate rule files and the no-executor safety pins") + + rp = sub.add_parser("rulepack", help="the signed rule-pack format: " + "export/import/list/render " + "(signatures live in YOUR " + "external tool)") + rp.add_argument("action", choices=["export", "import", "list", + "render", "rules-d", "forget"]) + rp.add_argument("target", nargs="?", default="", + help="export: output path; import: pack path (or - " + "for stdin); render/rules-d/forget: pack id") + rp.add_argument("--rulesets", default="", + help="export: comma-separated rules.d stems") + rp.add_argument("--id", default="", + help="export: the pack id (required)") + rp.add_argument("--signer", default="", + help="import: the identity YOU verified with your own " + "tool (recorded as a claim, never auto-trusted)") + + args = parser.parse_args(argv) + + if args.cmd == "rulepack": + # exponential-build-3 F1: the signed rule-pack surface. The + # module (diagnostics/rulepack.py) carries the full contract; + # this CLI is a thin router over it. + from . import rulepack + from assistant.capabilities.brain import state as brain_state + if args.action == "export": + if not args.rulesets or not args.id: + print("error: rulepack export needs --rulesets A,B and " + "--id NAME", file=sys.stderr) + return 2 + try: + pack = rulepack.export_pack( + Path(__file__).resolve().parent / "rules.d", + [s.strip() for s in args.rulesets.split(",") + if s.strip()], args.id) + except rulepack.RulePackError as exc: + print(f"error: {exc}", file=sys.stderr) + return 1 + text = json.dumps(pack, indent=2) + "\n" + if args.target in ("", "-"): + sys.stdout.write(text) + else: + Path(args.target).write_text(text, encoding="utf-8") + print(f"wrote pack {args.id!r} to {args.target} " + "(sign it with YOUR external tool before sharing)") + return 0 + if args.action == "import": + if not args.target: + print("error: rulepack import needs a pack path (or - " + "for stdin)", file=sys.stderr) + return 2 + raw = (sys.stdin.read() if args.target == "-" + else Path(args.target).read_text(encoding="utf-8")) + state = brain_state.load() + existing = [rec.get("id") for rec in + state.get(rulepack.STATE_KEY, []) or []] + try: + record = rulepack.import_pack(raw, existing, + signer=args.signer) + except rulepack.RulePackError as exc: + print(f"error: {exc}", file=sys.stderr) + return 1 + state.setdefault(rulepack.STATE_KEY, []).append(record) + brain_state.save(state) + print(f"imported pack {record['id']!r}: " + f"{record['rule_count']} rule(s), integrity + safety " + "verified; signer recorded as a CLAIM") + print("imported rules are review data, NOT live — see: " + "caelestia-assist rulepack list / render") + return 0 + if args.action == "list": + packs = rulepack.list_packs(brain_state.load()) + if not packs: + print("no rule packs imported; import one with " + "rulepack import FILE") + return 0 + for rec in packs: + signer = rec.get("signer") or "(none recorded)" + print(f" {rec['id']}: {rec['rule_count']} rule(s), " + f"signer {signer!r}, payload sha256 " + f"{str(rec.get('payload_sha256'))[:12]}") + return 0 + if args.action in ("render", "rules-d"): + state = brain_state.load() + record = next( + (rec for rec in state.get(rulepack.STATE_KEY, []) or [] + if rec.get("id") == args.target), None) + if record is None: + print(f"error: no imported pack named {args.target!r}", + file=sys.stderr) + return 1 + if args.action == "render": + print(rulepack.render_pack(record)) + else: + sys.stdout.write(rulepack.render_rules_d(record)) + return 0 + # forget + state = brain_state.load() + packs = state.get(rulepack.STATE_KEY, []) or [] + kept = [rec for rec in packs if rec.get("id") != args.target] + if len(kept) == len(packs): + print(f"error: no imported pack named {args.target!r}", + file=sys.stderr) + return 1 + state[rulepack.STATE_KEY] = kept + brain_state.save(state) + print(f"forgot pack {args.target!r}") + return 0 + + if args.cmd == "selfcheck": + from . import schema_lint + + failures = schema_lint.run_all_checks() + for failure in failures: + print(f"LINT FAIL: {failure}") + if failures: + return 1 + # Settings config-lint rule table (issue #120 Phase 1.1): the lint + # rule table itself must be structurally sound. If a real shell.json + # exists it is linted INFORMATIONALLY — findings about the user's + # config never fail the selfcheck (the assistant's health is what + # selfcheck verifies, not the user's config). + from assistant.capabilities.settings import lint as config_lint + rule_failures = config_lint.lint_rules_ok() + for failure in rule_failures: + print(f"LINT FAIL: settings lint rule table: {failure}") + if rule_failures: + return 1 + note = "" + try: + from assistant.capabilities.settings.cli import default_target + target = default_target() + if Path(target).exists(): + findings = config_lint.lint_file(target) + if findings: + note = (f"; config lint of {target}: {len(findings)} " + "finding(s) (informational — see: caelestia-assist " + "settings --lint)") + except (OSError, ValueError, ImportError): + pass + print("selfcheck OK: rule schema valid, risk tiers consistent, " + "safety pins clean, settings lint rules valid" + note) + return 0 + + if args.input == "-": + text = sys.stdin.read() + else: + with open(args.input, "r", encoding="utf-8", errors="replace") as handle: + text = handle.read() + + diagnosis = diagnose(text, top=args.top) + if args.json: + payload = { + "verdict": diagnosis["verdict"], + "candidates": [ + { + "id": r["rule"]["id"], + "title": r["rule"].get("title"), + "score": r["score"], + "confidence": r["rule"].get("confidence"), + "evidence": r["evidence"][:6], + } + for r in diagnosis["candidates"] + ], + } + # Read-only enrichment, same rule as the text renderer: keys are + # added ONLY when the enrichment actually fires. + derived = rete.derived_evidence(diagnosis) + if derived is not None: + payload["derived_evidence"] = derived + conflicts = argumentation.conflict_resolution(diagnosis) + if conflicts is not None: + payload["conflict_resolution"] = conflicts + print(json.dumps(payload, indent=2)) + else: + print(render_report(diagnosis)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/plugins/caelestia-assistant/assistant/capabilities/diagnostics/forecast.py b/plugins/caelestia-assistant/assistant/capabilities/diagnostics/forecast.py new file mode 100644 index 0000000..85cff74 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/capabilities/diagnostics/forecast.py @@ -0,0 +1,210 @@ +"""diagnostics.forecast — predictive hardware maintenance from the +telemetry time series (exponential-build-4 E). + +The gap: telemetry.py reads a snapshot; the battery/thermal advisor +trends a rate. Neither answers "trending toward failure in ~N days". +This module fits a LOCAL LINEAR TREND through a scalar series (SMART +reallocated-sector counts, thermal readings) with a STEADY-STATE +KALMAN filter (Kalman 1960, "A New Approach to Linear Filtering and +Prediction Problems", ASME J. Basic Engineering 82D — the standard +[constant level, constant slope] local-linear model, equations exactly +the textbook's, fixed gain F from the steady-state solution rather +than a per-step update), and projects the filtered level+slope +forward to the series' own alarm threshold. + +THE HONESTY THIS MODULE CARRIES (matching the battery/thermal +advisor's standard): + + * the interval around the projection is the IID-RESIDUAL interval: + sigma of the one-step INNOVATIONS (filter residuals) times the + horizon, student-t-free because no distribution is claimed — it + is labeled an INDICATION, not a probability of failure; + * a linear trend is a LOCAL model: the report says so, and a series + with fewer than MIN_POINTS points is refused outright rather than + fitted; + * SMART reallocated-sector counts can jump overnight (a failing + disk is nonlinear, sometimes abruptly) — the report carries that + caveat verbatim rather than smoothing over it; + * the projection never acts: it is a suggestion string for a human, + read-only like every telemetry consumer. + +Pure stdlib, no RNG, deterministic; state is plain dicts for the +caller's learned-state JSON path. Nothing here reads /proc or /sys — +the CALLER feeds series (telemetry.snapshot() is the live reader); +this keeps the module pure and the I/O enumerated. +""" +from __future__ import annotations + +import math +from typing import Any, Dict, List, Sequence + +__all__ = ["MIN_POINTS", "steady_state_kalman", "trend_projection", + "failure_horizon", "forecast_report"] + +MIN_POINTS = 6 + + +def steady_state_kalman(series: Sequence[float], q: float = 0.01, + r: float = 1.0) -> Dict[str, Any]: + """The [level, slope] local-linear Kalman filter over one series. + + State x = [level, slope]; transition x' = [level + slope, slope] + with process noise q on the slope; observation = level with noise + r. The fixed steady-state gain F solves the Riccati iteration to + convergence (|F_k+1 − F_k| < 1e-9) — after which every step is two + multiply-adds, which is the point of the steady-state form. + Returns the filtered levels, the one-step innovations (filter + residuals), and their sigma — the honesty input for every interval + this module reports.""" + if len(series) < MIN_POINTS: + raise ValueError( + f"a trend needs >= {MIN_POINTS} points; {len(series)} is " + "an honest refusal, not a confident straight line") + if q <= 0 or r <= 0: + raise ValueError("q and r must be positive") + + # Riccati iteration for the 2x2 steady-state gain (the [level, + # slope] system's P recursions, iterated to a fixed point) + p11 = p22 = 1.0 + p12 = 0.0 + gain = [0.0, 0.0] + for _ in range(200): + # predict: F = [[1, 1], [0, 1]] with slope process noise q + p11p = p11 + 2 * p12 + p22 + q + p12p = p12 + p22 + p22p = p22 + q + # innovation variance for a level observation + s = p11p + r + k1, k2 = p11p / s, p12p / s + if abs(k1 - gain[0]) < 1e-9 and abs(k2 - gain[1]) < 1e-9: + gain = [k1, k2] + break + gain = [k1, k2] + # update + p11 = (1 - k1) * p11p + p12 = (1 - k1) * p12p + p22 = p22p - k2 * p12p + + level = float(series[0]) + slope = 0.0 + levels: List[float] = [] + innovations: List[float] = [] + for value in series: + pred = level + slope + innovation = float(value) - pred + level = pred + gain[0] * innovation + slope = slope + gain[1] * innovation + levels.append(level) + innovations.append(innovation) + # sigma from the CONVERGED half of the innovations: the first few + # steps are the filter locking onto the slope, and folding their + # ramp into the noise would overstate the band (the honest band is + # the one the filter achieves once it has converged) + tail = innovations[len(innovations) // 2:] + sigma = (math.sqrt(sum(i * i for i in tail) / max(1, len(tail))) + if tail else 0.0) + return {"levels": levels, "slope": slope, "level": level, + "innovations": innovations, "sigma_innovation": sigma, + "gain": gain, "n": len(series)} + + +def trend_projection(fit: Dict[str, Any], horizon: int + ) -> Dict[str, Any]: + """Project the filtered [level, slope] forward ``horizon`` steps + with the iid-residual interval at 1 sigma (the interval GROWS + linearly with the horizon because the slope term accumulates the + one-step sigma — the linear-trend model's own honesty).""" + horizon = int(horizon) + if horizon < 1: + raise ValueError("horizon must be >= 1") + sigma = fit["sigma_innovation"] + slope = fit["slope"] + projections = [] + for h in range(1, horizon + 1): + value = fit["level"] + slope * h + projections.append({"step": h, "value": value, + "sigma": sigma * h}) + return {"projections": projections, "horizon": horizon, + "slope_per_step": slope} + + +def failure_horizon(fit: Dict[str, Any], threshold: float + ) -> Dict[str, Any]: + """When does the filtered trend cross ``threshold``? Returns the + step count and the honest verdicts: already past it, slope too + flat to say (within the noise), or crossing at step N with the + iid-residual caveat.""" + slope = fit["slope"] + level = fit["level"] + sigma = fit["sigma_innovation"] + if level >= threshold: + return {"crossed": True, "steps": 0, + "note": "already at or past the threshold — the trend " + "model is not needed for that"} + if slope <= 0: + return {"crossed": False, "steps": None, + "note": "non-increasing trend: no crossing is projected " + "(refusing to invent one)"} + # noise floor: a slope smaller than sigma/step is indistinguishable + # from flat over short horizons — say so instead of projecting + if abs(slope) < sigma / 3.0: + return {"crossed": False, "steps": None, + "note": "the slope is within the innovation noise — " + "no crossing is claimed (a flatter honest " + "answer than a confident number)"} + steps = (threshold - level) / slope + return {"crossed": False, "steps": round(steps, 1), + "sigma_per_step": sigma, + "note": "iid-residual indication: steps = (threshold − " + "level)/slope with sigma from the filter's own " + "innovations; a linear-trend LOCAL model, not a " + "failure probability"} + + +def forecast_report(series: Sequence[float], threshold: float, + unit: str = "count", q: float = 0.01, r: float = 1.0, + max_horizon: int = 90 + ) -> Dict[str, Any]: + """The full report for one series against one threshold: the Kalman + fit, the horizon, the 1-sigma band at the crossing, and the + suggestion string. Read-only by construction — the caller decides + what (if anything) to do with a suggestion; nothing acts here.""" + fit = steady_state_kalman(series, q=q, r=r) + horizon = failure_horizon(fit, threshold) + projection = (trend_projection(fit, min(int(horizon["steps"]) + 2, + max_horizon)) + if horizon.get("steps") else None) + if horizon.get("crossed"): + suggestion = (f"the series is already at/past the {unit} " + f"threshold {threshold} — inspect now; do not " + "wait for a trend") + elif horizon.get("steps"): + steps = horizon["steps"] + sigma = horizon.get("sigma_per_step", 0.0) + suggestion = (f"trending toward the {unit} threshold " + f"{threshold} in ~{steps:g} steps at the current " + f"rate (iid-residual band ±{sigma:.3g}/step) — " + "an indication from a LOCAL linear trend, not a " + "failure probability; SMART counters can jump " + "nonlinearly overnight") + else: + suggestion = (f"no crossing of the {unit} threshold " + f"{threshold} is projected: " + f"{horizon.get('note', '')}") + return { + "n_points": len(series), + "filtered_level": round(fit["level"], 4), + "slope_per_step": round(fit["slope"], 6), + "sigma_innovation": round(fit["sigma_innovation"], 6), + "horizon": horizon, + "projection": projection, + "suggestion": suggestion, + "caveats": [ + "LOCAL linear trend: honest near the end of the series, " + "not a physical failure model", + "the interval is the filter's own iid-residual band; " + "correlated noise is not modeled", + "SMART reallocated-sector counts can jump nonlinearly " + "overnight — re-check against the raw series", + ], + } diff --git a/plugins/caelestia-assistant/assistant/capabilities/diagnostics/fusion.py b/plugins/caelestia-assistant/assistant/capabilities/diagnostics/fusion.py new file mode 100644 index 0000000..f9e393d --- /dev/null +++ b/plugins/caelestia-assistant/assistant/capabilities/diagnostics/fusion.py @@ -0,0 +1,271 @@ +"""diagnostics.fusion — weighted-Bayes combination of the confidences the +troubleshooting engines already produce, into one ranked diagnosis. + +Three engines answer a troubleshooting question independently and each +attaches its own calibrated confidence to its own candidates: + +- the diagnostics rule engine (engine.py) — each rule carries its own + confidence; +- retrieval (retrieval/search.py) — BM25 scores over the repo's corpus; +- scan (scan/scanner.py) — streaming signature statistics over a log + stream. + +This module is a READ-ONLY DOWNSTREAM CONSUMER: it calls the engines, +reads their outputs, and never modifies them. The combination is +weighted Bayes in log-odds space — each source's confidence is one +likelihood-ratio update from a common prior, scaled by that source's +weight (with all weights equal and independent sources this reduces to +exactly the naive-Bayes likelihood-ratio product brain/naive_bayes.py +applies; the weighted form is the standard linear opinion pool in +log-odds space, Genest & Zidek 1986, "Combining probability +distributions", StatSci 1(1)). No source vote is invented: a source +with no evidence for a hypothesis ABSTAINS (its term is skipped), never +a silent 0.5. + +Score calibration, per source (all deterministic, all documented): +- diagnostics: a rule's qualitative tier ("deterministic"/"probable") + is NOT a probability and is never invented into one — the evidence + strength is the engine's own per-candidate match score, mapped + through the same saturating transform as every other unbounded score + (see below); candidates without a numeric score abstain; +- retrieval: BM25 is unbounded, so a fixed-scale saturating transform + c = s / (s + K) maps it into (0, 1) — monotone in the native score, + K a fixed documented constant (default 1.0), no fitting step; +- scan: the same transform over a pattern's hit DENSITY (hits per + line): one signature hit is prior-neutral (0.5), more hits are + stronger — the conservative reading of a stream statistic. + +One transform class for all three sources' unbounded native scores: +c = s / (s + K), monotone, deterministic, never claims certainty. + +Hypotheses are caller-keyed strings (a rule id, a doc id, or any label +the caller maps them to via ``hypothesis_map``). No fuzzy joining is +performed here — merging two engines' candidates into one hypothesis is +an explicit, auditable caller decision. + +Out-of-range values are REJECTED, never clamped (the settings layer's +own convention): a confidence outside (0, 1), a negative weight, or a +weight for an unknown source raises ValueError. +""" +from __future__ import annotations + +import math +from typing import Any, Dict, List, Optional + +__all__ = ["DEFAULT_WEIGHTS", "fuse", "from_diagnose", "from_retrieval", + "from_scan", "diagnose"] + +# Source trust, fixed and conservative by default: the deterministic, +# citation-pinned rule engine is worth twice a corpus or stream signal. +# Overridable per call; unknown or negative weights are rejected. +DEFAULT_WEIGHTS = {"diagnostics": 0.5, "retrieval": 0.25, "scan": 0.25} + +# Saturating-transform scale for the unbounded native scores (BM25 and +# scan hit counts): c = s / (s + K). K=1 makes exactly one unit of +# native evidence prior-neutral (0.5) — the conservative default. +DEFAULT_SCALE = 1.0 + +_EPS = 1e-9 + + +def _logit(p: float) -> float: + return math.log(p / (1.0 - p)) + + +def _sigmoid(x: float) -> float: + return 1.0 / (1.0 + math.exp(-x)) + + +def _check_confidence(source: str, hypothesis: str, c: Any) -> float: + try: + c = float(c) + except (TypeError, ValueError): + raise ValueError( + f"{source} confidence for {hypothesis!r} is not a number: {c!r}") + if not (0.0 < c < 1.0): + # certainty claims and zero-confidence noise are both refused: + # engines produce calibrated values strictly inside (0, 1) + raise ValueError( + f"{source} confidence for {hypothesis!r} must be strictly " + f"inside (0, 1), got {c} (rejected, never clamped)") + return c + + +def fuse(evidence: List[Dict[str, Any]], + weights: Optional[Dict[str, float]] = None, + prior: float = 0.5) -> Dict[str, Any]: + """Combine per-source confidences into one ranked diagnosis list. + + ``evidence``: [{"source": "diagnostics"|"retrieval"|"scan", + "hypothesis": str, "confidence": float in (0,1)}] + (the shape from_diagnose / from_retrieval / from_scan emit). Each + hypothesis's posterior log-odds is the prior log-odds plus the + weight-scaled likelihood ratios of every source that voted. + + Returns {"prior", "weights", "diagnoses": [{hypothesis, confidence, + sources, odds_multiplier}]} ranked by combined confidence desc with + a hypothesis-name tie-break (deterministic).""" + w = dict(DEFAULT_WEIGHTS if weights is None else weights) + for name, weight in w.items(): + if name not in DEFAULT_WEIGHTS: + raise ValueError(f"unknown source {name!r} in weights " + f"(known: {sorted(DEFAULT_WEIGHTS)})") + if float(weight) < 0.0: + raise ValueError(f"weight for {name!r} must be >= 0, " + f"got {weight}") + if not (0.0 < float(prior) < 1.0): + raise ValueError(f"prior must be strictly inside (0, 1), " + f"got {prior}") + + prior_logit = _logit(float(prior)) + by_hypothesis: Dict[str, Dict[str, float]] = {} + for item in evidence: + source = str(item.get("source", "")) + if source not in DEFAULT_WEIGHTS: + raise ValueError(f"unknown source {source!r} in evidence") + hypothesis = str(item.get("hypothesis", "")) + if not hypothesis: + raise ValueError("evidence item without a hypothesis") + c = _check_confidence(source, hypothesis, item.get("confidence")) + slot = by_hypothesis.setdefault(hypothesis, {}) + if source in slot: + raise ValueError( + f"source {source!r} voted twice for {hypothesis!r}") + slot[source] = c + + diagnoses: List[Dict[str, Any]] = [] + for hypothesis, slot in by_hypothesis.items(): + logit = prior_logit + contributions: Dict[str, float] = {} + for source, c in slot.items(): + delta = float(w[source]) * (_logit(c) - prior_logit) + contributions[source] = round(delta, 6) + logit += delta + diagnoses.append({ + "hypothesis": hypothesis, + "confidence": round(_sigmoid(logit), 4), + "sources": {s: round(c, 4) for s, c in sorted(slot.items())}, + "contributions": contributions, + # total likelihood ratio vs the prior — the honest magnitude + # of the combined evidence (1.0 when nothing voted) + "odds_multiplier": round(math.exp(logit - prior_logit), 4), + }) + diagnoses.sort(key=lambda d: (-d["confidence"], d["hypothesis"])) + return {"prior": prior, "weights": w, "diagnoses": diagnoses} + + +# --------------------------------------------------------------------------- +# Per-source collectors: read-only transformers of each engine's OWN output. +# --------------------------------------------------------------------------- + +def from_diagnose(diag_result: Dict[str, Any], + scale: float = DEFAULT_SCALE) -> List[Dict[str, Any]]: + """The diagnostics engine's candidates as fusion evidence. + + The evidence strength is the engine's own per-candidate match score + through the shared saturating transform (the rule's qualitative + ``confidence`` tier is a label, not a probability, and is never + invented into a number). Candidates without a numeric score abstain. + The engine's own output is only read, never modified.""" + out: List[Dict[str, Any]] = [] + for cand in diag_result.get("candidates", []): + rule = cand.get("rule") or {} + score = cand.get("score") + if not isinstance(score, (int, float)) or float(score) <= 0.0: + continue # no numeric match strength -> abstain, never guess + s = float(score) + out.append({"source": "diagnostics", + "hypothesis": str(rule.get("id", "")), + "confidence": s / (s + float(scale)), + "tier": rule.get("confidence")}) + return out + + +def from_retrieval(hits: List[Dict[str, Any]], + scale: float = DEFAULT_SCALE) -> List[Dict[str, Any]]: + """Retrieval's BM25 hits as fusion evidence (fixed-scale saturating + transform; monotone, deterministic, no fitting).""" + out: List[Dict[str, Any]] = [] + for hit in hits: + score = float(hit.get("score", 0.0)) + if score <= 0.0: + continue # a zero-scored doc is no evidence, not a vote + out.append({"source": "retrieval", + "hypothesis": f"doc:{hit.get('doc_id', hit.get('id'))}", + "confidence": score / (score + float(scale))}) + return out + + +def from_scan(scan_result: Dict[str, Any], + scale: float = DEFAULT_SCALE) -> List[Dict[str, Any]]: + """Scan's streaming signature statistics as fusion evidence: one + pattern hit is prior-neutral, more are stronger (conservative by + construction).""" + lines = max(1, int(scan_result.get("lines_scanned", 0))) + out: List[Dict[str, Any]] = [] + for hit in scan_result.get("pattern_hits", []): + hits = float(hit.get("hits", 0.0)) + if hits <= 0.0: + continue + # saturating transform over the hit DENSITY (hits per line), + # so a long stream needs proportionally more hits to move the + # same source weight + density = hits / lines + out.append({"source": "scan", + "hypothesis": f"pattern:{hit.get('pattern', '')}", + "confidence": density / (density + float(scale))}) + return out + + +# --------------------------------------------------------------------------- +# The one-call convenience (still read-only; the engines answer first). +# --------------------------------------------------------------------------- + +def diagnose(text: str, stream_text: Optional[str] = None, + patterns: Optional[List[str]] = None, k: int = 3, + hypothesis_map: Optional[Dict[str, str]] = None, + weights: Optional[Dict[str, float]] = None, + prior: float = 0.5, scale: float = DEFAULT_SCALE + ) -> Dict[str, Any]: + """Ask all engines, fuse their evidence, rank once. + + Runs diagnostics.engine.diagnose(text) and retrieval's search; scan + participates only when the caller supplies BOTH ``stream_text`` and + the signature ``patterns`` (the automaton is the caller's choice — + the same rule as the agent's scan dispatcher). ``hypothesis_map`` + optionally re-labels source items onto shared hypotheses + (e.g. {"doc:ISS-120": "vesktop-screencast"}); without it, each item + stays its own hypothesis — nothing is fuzzy-joined here. + + The engines' own result dicts are never modified: this module only + reads them.""" + from . import engine as diagnostics_engine + from assistant.capabilities.retrieval import search as retrieval_search + + evidence: List[Dict[str, Any]] = [] + + diag = diagnostics_engine.diagnose(text) + evidence.extend(from_diagnose(diag, scale=scale)) + + hits = retrieval_search.search(text, k=k) + evidence.extend(from_retrieval(hits, scale=scale)) + + scan_summary: Optional[Dict[str, Any]] = None + if stream_text is not None and patterns: + from assistant.capabilities.scan import Automaton + from assistant.capabilities.scan.scanner import scan_text + scan_summary = scan_text(stream_text, Automaton(list(patterns))) + evidence.extend(from_scan(scan_summary, scale=scale)) + + if hypothesis_map: + for item in evidence: + item["hypothesis"] = hypothesis_map.get( + item["hypothesis"], item["hypothesis"]) + + fused = fuse(evidence, weights=weights, prior=prior) + fused["inputs"] = { + "diagnostics_verdict": diag.get("verdict"), + "retrieval_hits": len(hits), + "scan_ran": scan_summary is not None, + } + return fused diff --git a/plugins/caelestia-assistant/assistant/capabilities/diagnostics/manifest.py b/plugins/caelestia-assistant/assistant/capabilities/diagnostics/manifest.py new file mode 100644 index 0000000..773d03f --- /dev/null +++ b/plugins/caelestia-assistant/assistant/capabilities/diagnostics/manifest.py @@ -0,0 +1,10 @@ +"""Manifest for the diagnostics capability: permissions, risk tier, budgets.""" +from assistant.capabilities._registry import CapManifest + +MANIFEST = CapManifest( + name="diagnostics", + permissions=("fs:read", "rules:read",), + risk_tier="read_only", + latency_budget_ms=400, + memory_budget_mb=40, +) diff --git a/plugins/caelestia-assistant/assistant/capabilities/diagnostics/rete.py b/plugins/caelestia-assistant/assistant/capabilities/diagnostics/rete.py new file mode 100644 index 0000000..a9cab19 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/capabilities/diagnostics/rete.py @@ -0,0 +1,598 @@ +"""diagnostics.rete — a forward-chaining Rete network beside the rule engine. + +Forgy 1982, "Rete: A Fast Algorithm for the Two-Variable Pattern Matching +Problem", Artificial Intelligence 19(1), pp. 17-37 — the classic Rete design, +as adapted here: + +- FACTS are JSON-serializable triples {"type": str, "key": str, + "value": str}; fact identity IS the triple (the first payload seen for a + triple wins). +- A PATTERN is the same shape with value "*" allowed as a WILDCARD matching + any value for that key (only the value component may be wildcarded). +- The ALPHA network keys one node per distinct pattern (type, key, + value-or-"*"), with an alpha MEMORY shared by every rule and premise + position using that pattern — the alpha-memory reuse property is pinned + by test (one assert feeds every consumer exactly once). +- The BETA network is a per-rule chain of JOIN nodes, each with a LEFT + memory (partial tokens) and a RIGHT memory (facts received from its + alpha node). Our patterns are constant triples with no variables that + bind across premises, so a join performs an unfiltered cross product of + its left tokens and right facts (stated plainly: no Forgy-style + variable-binding tests); the two memories still give the incremental, + assert-once propagation Rete exists for. +- A TERMINAL node per rule fires on each complete token (one fact consumed + per premise, in premise order) and asserts the rule's conclusion fact + carrying its derivation: the rule id plus the exact facts consumed. + +Derived-vs-given: a terminal's conclusion is recorded with source +"derived" and re-traverses the network exactly like an asserted fact +(source "given"). Re-deriving an already-present fact is a NO-OP — the +fact is not re-added and its first derivation is kept — which, together +with each distinct fact entering each alpha memory exactly once, +guarantees fixpoint termination for cyclic rule sets (pinned by test with +a deliberately cyclic rule pair). + +Honesty: a rule whose premises reference facts no producer supplies simply +never fires; zero premises matched means zero derived facts and no +invented conclusions. Rules with an EMPTY premise list are rejected at +construction — an unconditional "conclusion" is an invention, not a +derivation. Dormant rules are LISTED with their first unsatisfied premise +(dormant_rules()), never hidden. + +The shipped COMPOSITE_RULES derive composite conclusions from REAL rules.d +rule ids only: each premise is a match fact the CLI layer derives from the +engine's own gate-passing candidates, each conclusion is a new "derived" +fact, and each rationale/citation composes the underlying rules' own +claims and references (docs/TROUBLESHOOTING.md sections + issue numbers +exactly as the underlying rules carry them) — no new factual claim about +the shell is made here. + +Pure module: no I/O, no execution, nothing written; deterministic by +construction (every iteration follows insertion order). +""" +from __future__ import annotations + +import textwrap +from typing import Any, Dict, List, Optional, Sequence, Tuple + +__all__ = ["COMPOSITE_RULES", "ReteNetwork", "WILDCARD", "derive", + "derived_evidence", "facts_from_diagnosis", "render_derived_lines"] + +WILDCARD = "*" + +_FACT_KEYS = frozenset({"type", "key", "value"}) +_RULE_KEYS = frozenset({"id", "premises", "conclusion", "rationale", "citation"}) + +# Defensive cap: a rule set that can mint unboundedly many NEW distinct +# facts (e.g. a counter-incrementing conclusion) has no fixpoint; run() +# refuses to loop forever and says so instead of truncating silently. +_MAX_DERIVED = 10_000 + + +# --------------------------------------------------------------------------- +# Validation (strict: out-of-range is REJECTED with ValueError, never fixed) +# --------------------------------------------------------------------------- + +def _validate_triple(node: Any, role: str, allow_wildcard: bool) -> Tuple[str, str, str]: + """Validate one fact/pattern dict; returns its (type, key, value) triple.""" + if not isinstance(node, dict): + raise ValueError(f"{role} must be a dict, got {type(node).__name__}") + if set(node) != _FACT_KEYS: + raise ValueError( + f"{role} must have exactly the keys {sorted(_FACT_KEYS)}, " + f"got {sorted(node)}") + for part in ("type", "key", "value"): + value = node[part] + if not isinstance(value, str) or not value: + raise ValueError(f"{role} field {part!r} must be a non-empty string, got {value!r}") + if node["type"] == WILDCARD or node["key"] == WILDCARD: + raise ValueError( + f"{role}: only the VALUE component may be wildcarded ({WILDCARD!r}); " + f"got type={node['type']!r} key={node['key']!r}") + if node["value"] == WILDCARD and not allow_wildcard: + raise ValueError(f"{role} cannot carry the wildcard {WILDCARD!r} as its value") + return (node["type"], node["key"], node["value"]) + + +def _validate_rule(rule: Any, index: int) -> Dict[str, Any]: + """Validate one composite rule; returns it unchanged.""" + where = f"rules[{index}]" + if not isinstance(rule, dict): + raise ValueError(f"{where} must be a dict, got {type(rule).__name__}") + if set(rule) != _RULE_KEYS: + raise ValueError( + f"{where} must have exactly the keys {sorted(_RULE_KEYS)}, " + f"got {sorted(rule)}") + if not isinstance(rule["id"], str) or not rule["id"]: + raise ValueError(f"{where}: 'id' must be a non-empty string") + for text_field in ("rationale", "citation"): + if not isinstance(rule[text_field], str) or not rule[text_field]: + raise ValueError(f"{where} ({rule['id']}): {text_field!r} must be a non-empty string") + premises = rule["premises"] + if not isinstance(premises, list) or not premises: + raise ValueError( + f"{where} ({rule['id']}): 'premises' must be a NON-EMPTY list — a rule " + "with zero premises would fire unconditionally, and an unconditional " + "conclusion is an invention, not a derivation") + for i, premise in enumerate(premises): + _validate_triple(premise, f"{where} premise {i}", allow_wildcard=True) + _validate_triple(rule["conclusion"], f"{where} conclusion", allow_wildcard=False) + return rule + + +# --------------------------------------------------------------------------- +# Network nodes (private; the public surface is ReteNetwork below) +# --------------------------------------------------------------------------- + +class _AlphaNode: + """One distinct pattern; its memory holds every fact that ever matched.""" + + __slots__ = ("pattern", "memory", "successors") + + def __init__(self, pattern: Tuple[str, str, str]) -> None: + self.pattern = pattern + self.memory: List[Tuple[str, str, str]] = [] # arrival order + self.successors: List["_JoinNode"] = [] + + +class _JoinNode: + """One premise position of one rule; joins left tokens with right facts.""" + + __slots__ = ("premise", "alpha", "parent", "child", "terminal", + "left_memory", "right_memory") + + def __init__(self, premise: Tuple[str, str, str], alpha: _AlphaNode, + parent: Optional["_JoinNode"]) -> None: + self.premise = premise + self.alpha = alpha + self.parent = parent # None = this join reads the beta root + self.child: Optional["_JoinNode"] = None + self.terminal: Optional[_TerminalNode] = None + self.left_memory: List[Tuple[Tuple[str, str, str], ...]] = [] + self.right_memory: List[Tuple[str, str, str]] = [] + + +class _TerminalNode: + """End of one rule's beta chain; fires on each complete token.""" + + __slots__ = ("rule", "network") + + def __init__(self, rule: Dict[str, Any], network: "ReteNetwork") -> None: + self.rule = rule + self.network = network + + +# --------------------------------------------------------------------------- +# The network +# --------------------------------------------------------------------------- + +class ReteNetwork: + """A Rete network over one rule set; facts in, derived facts out. + + Typical use: assert the given facts, run() to fixpoint, then read the + derived facts (in derivation order), explain() any of them back to the + given facts, and list which rules stayed dormant. + """ + + def __init__(self, rules: Sequence[Dict[str, Any]]) -> None: + self._rules: List[Dict[str, Any]] = [] + self._rule_by_id: Dict[str, Dict[str, Any]] = {} + for index, raw in enumerate(rules): + rule = _validate_rule(raw, index) + if rule["id"] in self._rule_by_id: + raise ValueError(f"duplicate rule id {rule['id']!r}") + self._rules.append(rule) + self._rule_by_id[rule["id"]] = rule + + # Alpha nodes shared by pattern; beta chains per rule. + self._alpha: Dict[Tuple[str, str, str], _AlphaNode] = {} + self._terminals: List[_TerminalNode] = [] + for rule in self._rules: + joins: List[_JoinNode] = [] + for premise in rule["premises"]: + pattern = (premise["type"], premise["key"], premise["value"]) + alpha = self._alpha.get(pattern) + if alpha is None: + alpha = _AlphaNode(pattern) + self._alpha[pattern] = alpha + join = _JoinNode(pattern, alpha, joins[-1] if joins else None) + alpha.successors.append(join) + if joins: + joins[-1].child = join + joins.append(join) + terminal = _TerminalNode(rule, self) + joins[-1].terminal = terminal + self._terminals.append(terminal) + + # Working memory: triple -> record, in arrival order (given first, + # then derived in derivation order). + self._wm: Dict[Tuple[str, str, str], Dict[str, Any]] = {} + self._agenda: List[Tuple[str, str, str]] = [] + self._agenda_cursor = 0 + self._derived_order: List[Tuple[str, str, str]] = [] + self._terminal_log: List[Dict[str, Any]] = [] + self._fired: Dict[str, int] = {} + self._fired_order: List[str] = [] + + # -- assertion ----------------------------------------------------- + + def assert_fact(self, fact: Dict[str, str]) -> bool: + """Record one fact as GIVEN (source="given"). + + Returns True if the fact was new, False if an identical triple was + already present (a no-op: the fact does not re-enter any alpha + memory, so no terminal re-fires — pinned by test). The only other + source, "derived", is recorded by the network itself when a + terminal fires. + """ + triple = _validate_triple(fact, role="fact", allow_wildcard=False) + if triple in self._wm: + return False + self._wm[triple] = {"fact": {"type": triple[0], "key": triple[1], + "value": triple[2]}, + "source": "given", "derivation": None} + self._agenda.append(triple) + return True + + # -- inference ----------------------------------------------------- + + def run(self) -> List[Dict[str, str]]: + """Propagate the agenda to fixpoint; returns facts derived by THIS + call, in derivation order. + + Termination: each distinct fact enters each alpha memory at most + once, so each (token, fact) combination is emitted at most once; + a terminal whose conclusion is already present records the firing + and derives nothing. A rule set that mints unboundedly many NEW + distinct facts has no fixpoint; run() refuses at _MAX_DERIVED with + an explicit error rather than looping (or truncating) silently. + """ + start = len(self._derived_order) + while self._agenda_cursor < len(self._agenda): + triple = self._agenda[self._agenda_cursor] + self._agenda_cursor += 1 + self._route(triple) + if len(self._derived_order) > _MAX_DERIVED: + raise RuntimeError( + f"rete: refused to continue past {_MAX_DERIVED} derived " + "facts — this rule set mints unboundedly many new facts " + "and has no fixpoint; refusing rather than looping or " + "truncating silently (rule-authoring bug)") + return [self._wm[t]["fact"] for t in self._derived_order[start:]] + + def _route(self, triple: Tuple[str, str, str]) -> None: + """Send one fact to every alpha node whose pattern it matches.""" + for (ptype, pkey, pvalue), alpha in self._alpha.items(): + if triple[0] == ptype and triple[1] == pkey and ( + pvalue == WILDCARD or triple[2] == pvalue): + alpha.memory.append(triple) + for join in alpha.successors: + join.right_memory.append(triple) + if join.parent is None: + # Root join: the beta root contributes the empty + # token, so this fact alone completes premise 0. + self._pass_on(join, (triple,)) + else: + for token in list(join.left_memory): + self._pass_on(join, token + (triple,)) + + def _pass_on(self, join: _JoinNode, + token: Tuple[Tuple[str, str, str], ...]) -> None: + """A token has grown at `join`; send it downstream.""" + if join.child is not None: + child = join.child + child.left_memory.append(token) + for right in list(child.right_memory): + self._pass_on(child, token + (right,)) + elif join.terminal is not None: + self._conclude(join.terminal, token) + + def _conclude(self, terminal: _TerminalNode, + token: Tuple[Tuple[str, str, str], ...]) -> None: + """One rule's premises are all satisfied by `token`; fire.""" + rule = terminal.rule + conclusion = rule["conclusion"] + triple = (conclusion["type"], conclusion["key"], conclusion["value"]) + if triple in self._wm: + outcome = "already-present" # no-op: first derivation is kept + else: + self._wm[triple] = { + "fact": dict(conclusion), "source": "derived", + "derivation": {"rule": rule["id"], "premises": list(token)}, + } + self._derived_order.append(triple) + self._agenda.append(triple) + outcome = "derived" + self._terminal_log.append({ + "rule": rule["id"], "premises": list(token), + "conclusion": {"type": triple[0], "key": triple[1], + "value": triple[2]}, + "outcome": outcome, + }) + if rule["id"] not in self._fired: + self._fired_order.append(rule["id"]) + self._fired[rule["id"]] = self._fired.get(rule["id"], 0) + 1 + + # -- inspection ------------------------------------------------------ + + def facts(self) -> List[Dict[str, str]]: + """Every fact in working memory, in arrival order (given first).""" + return [record["fact"] for record in self._wm.values()] + + def explain(self, fact: Dict[str, str]) -> Dict[str, Any]: + """The full derivation tree of one fact, chained back to given facts. + + Returns {"fact", "source", "rule", "rationale", "citation", + "premises": [...]}. Given facts are leaves (rule None); derived + facts carry the rule that produced them and the trees of the exact + facts its premises consumed. Only the FIRST derivation of a fact is + recorded (re-derivations are no-ops), so the tree is a DAG by + construction; a cycle would be an internal invariant violation and + raises. Unknown facts are REJECTED with ValueError. + """ + triple = _validate_triple(fact, role="fact", allow_wildcard=False) + if triple not in self._wm: + raise ValueError( + f"cannot explain unknown fact {dict(fact)!r}: it was never " + "asserted or derived in this network") + return self._explain_triple(triple, ()) + + def _explain_triple(self, triple: Tuple[str, str, str], + seen: Tuple[Tuple[str, str, str], ...]) -> Dict[str, Any]: + if triple in seen: + raise RuntimeError( + f"derivation cycle detected at {triple!r} — internal " + "invariant violation (a derivation may only consume facts " + "that predate it); please report") + record = self._wm[triple] + node: Dict[str, Any] = { + "fact": record["fact"], "source": record["source"], + "rule": None, "rationale": None, "citation": None, + "premises": [], + } + if record["source"] == "derived": + derivation = record["derivation"] + rule = self._rule_by_id[derivation["rule"]] + node["rule"] = rule["id"] + node["rationale"] = rule["rationale"] + node["citation"] = rule["citation"] + node["premises"] = [ + self._explain_triple(p, seen + (triple,)) + for p in derivation["premises"] + ] + return node + + def alpha_memory(self, pattern: Dict[str, str]) -> List[Dict[str, str]]: + """The facts held by one pattern's alpha memory (shared across every + rule using that pattern — the Rete alpha-memory reuse surface).""" + triple = _validate_triple(pattern, role="pattern", allow_wildcard=True) + alpha = self._alpha.get(triple) + if alpha is None: + return [] + return [self._wm[t]["fact"] for t in alpha.memory] + + def terminal_log(self) -> List[Dict[str, Any]]: + """Every terminal firing, in firing order, with its outcome.""" + return [dict(entry) for entry in self._terminal_log] + + def fired_rules(self) -> List[str]: + """Rule ids that fired at least once, in first-fire order.""" + return list(self._fired_order) + + def dormant_rules(self) -> List[Dict[str, Any]]: + """Rules that never fired, each with its first unsatisfied premise. + + A rule is dormant when some premise pattern has no matching fact in + working memory (with no cross-premise variables this is exactly the + firing condition, so a dormant rule is a rule whose premises + reference facts no producer supplied — listed, not hidden). + """ + dormant: List[Dict[str, Any]] = [] + for rule in self._rules: + if rule["id"] in self._fired: + continue + missing: Optional[Dict[str, str]] = None + for pattern in rule["premises"]: + if not self._pattern_matched(pattern): + missing = {"type": pattern["type"], "key": pattern["key"], + "value": pattern["value"]} + break + if missing is None: + # Unreachable after a complete run (all premises matched + # implies the rule fired); reported rather than hidden. + dormant.append({"rule": rule["id"], "unsatisfied_premise": None, + "note": "premises satisfied but rule never " + "fired (internal inconsistency)"}) + else: + dormant.append({"rule": rule["id"], "unsatisfied_premise": missing}) + return dormant + + def _pattern_matched(self, pattern: Dict[str, str]) -> bool: + for (ftype, fkey, fvalue) in self._wm: + if (ftype == pattern["type"] and fkey == pattern["key"] + and (pattern["value"] == WILDCARD + or fvalue == pattern["value"])): + return True + return False + + +# --------------------------------------------------------------------------- +# The shipped composite rules (real rules.d ids only; citations compose the +# underlying rules' own references — no new factual claim about the shell) +# --------------------------------------------------------------------------- + +COMPOSITE_RULES: List[Dict[str, Any]] = [ + { + "id": "CR-color-war-001", + "premises": [ + {"type": "match", "key": "rule", "value": "CL-config-kmycolors-001"}, + {"type": "match", "key": "rule", "value": "CL-config-schemereset-001"}, + ], + "conclusion": {"type": "derived", "key": "combined-diagnosis", + "value": "legacy-color-service-plus-missing-scheme-handoff"}, + "rationale": ( + "Both documented color problems matched at once. " + "CL-config-kmycolors-001: the legacy kde-material-you-colors service " + "fights the shell's scheme pipeline (its fix: stop and disable that " + "service, confirm the apply-loop stopped, re-run the autostart step). " + "CL-config-schemereset-001: the color variant falls back to Tonal Spot " + "after reboot because the automatic scheme hand-off is off (its fix: " + "enable 'Automatic Color scheme', update the shell). The two fixes do " + "not conflict — one disables a legacy user service, the other enables " + "a shell setting — so both apply."), + "citation": ( + "docs/TROUBLESHOOTING.md §3.7 (issue #14) and §3.4 (issue #763) — " + "the references carried by CL-config-kmycolors-001 and " + "CL-config-schemereset-001"), + }, + { + "id": "CR-legacy-color-cleanup-001", + "premises": [ + {"type": "match", "key": "rule", "value": "CL-config-kmycolors-001"}, + {"type": "match", "key": "rule", "value": "CL-folder-cleanup-legacy-001"}, + ], + "conclusion": {"type": "derived", "key": "combined-fix", + "value": "disable-legacy-service-and-remove-stale-materialyou-schemes"}, + "rationale": ( + "Two matched rules converge on the same legacy migration. " + "CL-config-kmycolors-001 disables the kde-material-you-colors user " + "service; CL-folder-cleanup-legacy-001 also disables it and marks the " + "generated MaterialYou*.colors scheme files safe_to_delete: yes. One " + "disable satisfies both rules' service step; removing the stale " + "MaterialYou color files is the cleanup rule's own addition."), + "citation": ( + "docs/TROUBLESHOOTING.md §3.7 (issue #14) — the shared reference of " + "CL-config-kmycolors-001 and CL-folder-cleanup-legacy-001"), + }, + { + "id": "CR-color-war-002", + "premises": [ + {"type": "derived", "key": "combined-diagnosis", + "value": "legacy-color-service-plus-missing-scheme-handoff"}, + {"type": "match", "key": "rule", "value": "CL-folder-cleanup-legacy-001"}, + ], + "conclusion": {"type": "derived", "key": "migration-plan", + "value": "full-legacy-material-you-exit"}, + "rationale": ( + "With both color faults derived (CR-color-war-001) and the " + "legacy-cleanup rule also matched, the full documented migration is " + "in play. Every step is a fix step of one of the three underlying " + "rules: disable kde-material-you-colors (CL-config-kmycolors-001 / " + "CL-folder-cleanup-legacy-001), remove the stale MaterialYou*.colors " + "files (CL-folder-cleanup-legacy-001), enable 'Automatic Color " + "scheme' (CL-config-schemereset-001), re-run the autostart step " + "(CL-config-kmycolors-001)."), + "citation": ( + "docs/TROUBLESHOOTING.md §3.7, §3.4; issues #14, #763 — carried by " + "CL-config-kmycolors-001, CL-config-schemereset-001 and " + "CL-folder-cleanup-legacy-001"), + }, + { + "id": "CR-shell-unit-convergence-001", + "premises": [ + {"type": "match", "key": "rule", "value": "CL-runtime-shell-crashrecov-001"}, + {"type": "match", "key": "rule", "value": "CL-runtime-shell-nostart-001"}, + ], + "conclusion": {"type": "derived", "key": "convergence", + "value": "caelestia-shell-unit-recovery-path-agreed"}, + "rationale": ( + "Both matched rules route recovery through the same " + "caelestia-shell.service user unit. CL-runtime-shell-crashrecov-001 " + "restarts the unit after a crash (force-stopping the shell processes " + "first only if the restart hangs); CL-runtime-shell-nostart-001 " + "starts the unit when the shell never appeared, and only if it still " + "fails suggests running the shell in debug mode in a terminal. No " + "fix step in either rule opposes the other."), + "citation": ( + "docs/TROUBLESHOOTING.md §3.1 (issue #528) and issue #418 — the " + "references carried by CL-runtime-shell-nostart-001 and " + "CL-runtime-shell-crashrecov-001"), + }, +] + + +# --------------------------------------------------------------------------- +# Convenience + CLI enrichment (READ-ONLY consumers of engine.diagnose output) +# --------------------------------------------------------------------------- + +def derive(facts: Sequence[Dict[str, str]], + rules: Optional[Sequence[Dict[str, Any]]] = None) -> List[Dict[str, str]]: + """Assert `facts`, run to fixpoint, return the derived facts in + derivation order (rules default to the shipped COMPOSITE_RULES).""" + network = ReteNetwork(COMPOSITE_RULES if rules is None else rules) + for fact in facts: + network.assert_fact(fact) + return network.run() + + +def facts_from_diagnosis(diagnosis: Dict[str, Any]) -> List[Dict[str, str]]: + """READ-ONLY: one match fact per gate-passing candidate of a + diagnose() result — the only fact vocabulary the shipped composite + rules consume. The diagnosis is not modified.""" + facts: List[Dict[str, str]] = [] + for candidate in diagnosis.get("candidates", []) or []: + if not isinstance(candidate, dict): + continue + rule = candidate.get("rule") + rule_id = rule.get("id") if isinstance(rule, dict) else None + if rule_id is None: + rule_id = candidate.get("id") + if isinstance(rule_id, str) and rule_id: + facts.append({"type": "match", "key": "rule", "value": rule_id}) + return facts + + +def derived_evidence(diagnosis: Dict[str, Any], + rules: Optional[Sequence[Dict[str, Any]]] = None + ) -> Optional[Dict[str, Any]]: + """READ-ONLY enrichment payload for one diagnose() result; None when no + composite rule fired (zero premises matched -> nothing derived -> no + section rendered, per the honesty contract).""" + network = ReteNetwork(COMPOSITE_RULES if rules is None else rules) + for fact in facts_from_diagnosis(diagnosis): + network.assert_fact(fact) + derived = network.run() + if not derived: + return None + return { + "derived": [network.explain(fact) for fact in derived], + "dormant": network.dormant_rules(), + } + + +def render_derived_lines(payload: Dict[str, Any]) -> List[str]: + """Render the derived-evidence section (deterministic plain text).""" + lines = ["Derived evidence (Rete composite rules — Forgy 1982; derivations " + "from the matched rules above, not new matches):"] + index: Dict[Tuple[str, str, str], int] = {} + for position, node in enumerate(payload["derived"], start=1): + fact = node["fact"] + index[(fact["type"], fact["key"], fact["value"])] = position + for position, node in enumerate(payload["derived"], start=1): + fact = node["fact"] + lines.append(f" [{position}] {fact['type']} / {fact['key']} = {fact['value']}") + lines.append(f" via {node['rule']} ({node['citation']})") + lines.append(textwrap.fill( + node["rationale"] or "", width=86, + initial_indent=" because ", subsequent_indent=" ")) + rendered_premises = [] + for premise in node["premises"]: + pf = premise["fact"] + key = (pf["type"], pf["key"], pf["value"]) + suffix = f" (derived, see [{index[key]}])" if key in index else "" + rendered_premises.append( + f"{pf['type']} / {pf['key']} = {pf['value']}{suffix}") + lines.append(" premises: " + "; ".join(rendered_premises)) + dormant = payload.get("dormant") or [] + if dormant: + lines.append(" Dormant composite rules (premises not satisfied by this " + "report; listed, not hidden):") + for entry in dormant: + premise = entry.get("unsatisfied_premise") + if premise is None: + lines.append(f" - {entry['rule']} ({entry.get('note', 'no matching facts')})") + else: + lines.append( + f" - {entry['rule']} (missing premise: " + f"{premise['type']} / {premise['key']} = {premise['value']})") + return lines diff --git a/plugins/caelestia-assistant/assistant/capabilities/diagnostics/risk.py b/plugins/caelestia-assistant/assistant/capabilities/diagnostics/risk.py new file mode 100755 index 0000000..0e402e7 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/capabilities/diagnostics/risk.py @@ -0,0 +1,198 @@ +"""Static risk classification for suggested commands. + +The engine never runs anything; this module exists so that (a) the schema +lint can verify every rule declares a risk tier at least as severe as what +the command text implies, and (b) the renderer can label each step so a +human knows what they are about to copy-paste. + +Severity ladder (ordered): + READ_ONLY < STATE_CHANGING < PRIVILEGED < DESTRUCTIVE + +Classification policy (deliberately conservative): +- Literal catastrophic shapes (mkfs, dd to a device, fork bombs, curl|sh, + chmod 777 /, shred, wipefs) are DESTRUCTIVE. +- rm: recursive deletion is DESTRUCTIVE unless EVERY target is scoped to a + regenerable location (~/.cache, $XDG_CACHE_HOME, $XDG_RUNTIME_DIR); + non-recursive rm is STATE_CHANGING. +- sudo/pkexec/package-removal/service-disable/killall are PRIVILEGED. +- Known read-only verbs and --version/--status probes are READ_ONLY. +- Anything unrecognised defaults to STATE_CHANGING, never to READ_ONLY. +""" + +from __future__ import annotations + +import re +from typing import Optional + +RISK_ORDER = { + "READ_ONLY": 0, + "STATE_CHANGING": 1, + "PRIVILEGED": 2, + "DESTRUCTIVE": 3, +} + +# Deny-list seeds drawn from the real rule corpus (Task 3-b inventory) and +# docs/TROUBLESHOOTING.md. +_DESTRUCTIVE_LITERALS = [ + r"mkfs(\.\w+)?\s", + r"dd\s+[^\n]*of=/dev/", + r":\(\)\s*\{[^}]*\}\s*;\s*:", # fork bomb + r"chmod\s+(-R\s+)?777\s+/(?:\s|$)", + r"curl[^|]*\|\s*(sudo\s+)?(ba)?sh(\s|$)", + r"wget[^|]*\|\s*(sudo\s+)?(ba)?sh(\s|$)", + r">\s*/dev/(sd|nvme|hd)", + r">\s*/dev/mem", + r"shred\s", + r"wipefs\s", + r"--no-preserve-root", + # find's -delete performs recursive unlinking; must never classify as + # READ_ONLY even though bare `find` is on the read-only list. + r"find\s[^\n;|]*\s-delete\b", +] + +# Anchor shared by the PRIVILEGED / STATE_CHANGING lists: the verb must not +# be glued to a word character, but any other preceding character (backtick, +# quote, "$(", separator) still counts. The old (^|\s|;|&&|\|\|) anchor let +# `sudo ...` / $(rm ...) dodge classification. Over-matching is the +# acceptable failure mode. The READ_ONLY list deliberately keeps its STRICT +# anchor: loosening it would widen READ_ONLY, the unsafe direction. +_VERB_ANCHOR = r"(?:^|[^\w-])" + +_PRIVILEGED = [ + _VERB_ANCHOR + r"(sudo|pkexec|doas)\s", + _VERB_ANCHOR + r"pacman\s+(-R|-Rs|-Rdd|-S(y|c|yy))", + _VERB_ANCHOR + r"(dnf|apt|apt-get)\s+(install|remove|purge|upgrade|update|autoremove)", + _VERB_ANCHOR + r"paru\s+-[RS]", + _VERB_ANCHOR + r"gpasswd\s", + _VERB_ANCHOR + r"usermod\s", + _VERB_ANCHOR + r"systemctl\s+(--user\s+|--system\s+|\S+\s+)?disable", + _VERB_ANCHOR + r"killall\s", + _VERB_ANCHOR + r"pkill\s(-9|\s)", +] + +_READ_ONLY = [ + r"(^|\s|;|&&|\|\|)(cat|ls|head|tail|grep|rg|stat|file|wc)\s", + r"(^|\s|;|&&|\|\|)(du|df)\s", + r"(^|\s|;|&&|\|\|)find\s", + r"(^|\s|;|&&|\|\|)journalctl\s", + r"(^|\s|;|&&|\|\|)systemctl\s+(--user\s+)?(status|is-active|is-enabled|show|list-unit-files)", + r"(^|\s|;|&&|\|\|)kreadconfig\d?\s", + r"(^|\s|;|&&|\|\|)pgrep\s", + r"(^|\s|;|&&|\|\|)systemd-cgtop\s", + r"(^|\s|;|&&|\|\|)qdbus6?\s+[^\n]*Introspect", + r"git(\s+-C\s+\S+)?\s+(status|log|diff|ls-remote|branch|remote)", + r"(^|\s|;|&&|\|\|)(pacman|dnf|apt|apt-get|paru)\s+(-Q|-Qi|-Qs|-Ss|search|list|show|info)", + r"(^|\s|;|&&|\|\|)echo\s", + r"(^|\s|;|&&|\|\|)env(\s|$)", + r"--version(\s*$|\s*&&)", # any tool's --version probe + # Repo diagnostic scripts: verified read-only checkers. + r"bash\s+\S*(check-workspace-tracker|list-plugins|menu_perf_stats)\.sh", + # Per-card GPU read loop from the #616 rule. + r"for\s+f\s+in\s+/sys/class/drm", + # Reading shell state for reports. + r"du\s+-[a-zA-Z]*a", +] + +_STATE_CHANGING = [ + _VERB_ANCHOR + r"kwriteconfig\d?\s", + _VERB_ANCHOR + r"systemctl\s+(--user\s+)?(restart|start|stop|enable)", + _VERB_ANCHOR + r"qdbus6?\s+org\.kde\.KWin\s+/KWin\s+reconfigure", + _VERB_ANCHOR + r"kbuildsycoca\d?\s", + _VERB_ANCHOR + r"lookandfeeltool\s+--apply", + _VERB_ANCHOR + r"rm\s", + _VERB_ANCHOR + r"sed\s+[^|\n]*-i", + _VERB_ANCHOR + r"kill\s", + _VERB_ANCHOR + r"git\s+(stash|checkout|reset|clean|submodule)", + _VERB_ANCHOR + r"bash\s+(update\.sh|scripts/setup\.sh|scripts/|~/.config/quickshell)", + _VERB_ANCHOR + r"\$EDITOR\s", + _VERB_ANCHOR + r"(nano|vim|nvim|kate|micro)\s", + _VERB_ANCHOR + r"ccache\s+-C", +] + +# rm targets scoped to these prefixes are regenerable caches / volatile +# runtime state: recursive deletion there is STATE_CHANGING, not DESTRUCTIVE. +# Stored lowercase and compared against target.lower() so odd spellings +# ("RM", "${xdg_runtime_dir") cannot dodge the scope check. +_CACHE_SCOPED_PREFIXES = tuple( + prefix.lower() + for prefix in ( + "~/.cache/", + "$XDG_CACHE_HOME/", + "${XDG_CACHE_HOME", + "$XDG_RUNTIME_DIR/", + "${XDG_RUNTIME_DIR", + "/tmp/", + ) +) + + +def _classify_rm(text: str) -> Optional[str]: + """Classify a command that contains rm; None if there is no rm. + + The anchor matches rm after start/whitespace/;/&/|/backtick/"$(" /quote so + neither a prefix word ("then rm -rf /") nor punctuation wrapping + ("`rm -rf /`", "$(rm -rf /etc)") can dodge classification. Matching is + case-insensitive: "RM -RF /" and "rm -Rf" (uppercase -R IS recursive) + must not slip through. Over-classification is the acceptable failure + mode; under-classification is not. + """ + if not re.search(r"(?:^|[^\w-])rm\s", text, re.IGNORECASE): + return None + for pattern in _DESTRUCTIVE_LITERALS: + if re.search(pattern, text, re.IGNORECASE): + return "DESTRUCTIVE" + # Collect rm invocations with their flags and targets. + for match in re.finditer(r"(?:^|[^\w-]\s*)rm\s+([^\n]+)", text, re.IGNORECASE): + rest = match.group(1) + tokens = rest.strip().split() + flags = "".join(tok for tok in tokens if tok.startswith("-")) + targets = [tok.strip("\"'`") for tok in tokens if not tok.startswith("-")] + recursive = "r" in flags.lower() # -r AND -R are both recursive + if not recursive: + continue + if targets and all( + any(t.lower().startswith(prefix) for prefix in _CACHE_SCOPED_PREFIXES) + for t in targets + ): + return "STATE_CHANGING" # scoped to regenerable cache/runtime state + return "DESTRUCTIVE" + return "STATE_CHANGING" # plain non-recursive rm + + +def classify(command: str) -> str: + """Return the most severe risk tier the command text implies. + + All matching is case-insensitive ("RM -RF /" expresses the same intent + as "rm -rf /"; missing a destructive shape because of letter case would + be under-classification). Terminal escape sequences are stripped first so + ANSI-wrapped flags cannot dodge the rm analysis. The most severe + matching tier wins. + """ + text = re.sub(r"\x1b\[[0-9;]*[A-Za-z]", "", command.strip()) + + rm_risk = _classify_rm(text) + if rm_risk == "DESTRUCTIVE": + return "DESTRUCTIVE" + + for pattern in _DESTRUCTIVE_LITERALS: + if re.search(pattern, text, re.IGNORECASE): + return "DESTRUCTIVE" + for pattern in _PRIVILEGED: + if re.search(pattern, text, re.IGNORECASE): + return "PRIVILEGED" + if rm_risk == "STATE_CHANGING": + return "STATE_CHANGING" + for pattern in _READ_ONLY: + if re.search(pattern, text, re.IGNORECASE): + return "READ_ONLY" + for pattern in _STATE_CHANGING: + if re.search(pattern, text, re.IGNORECASE): + return "STATE_CHANGING" + # Conservative default: anything unrecognised is treated as state + # changing, never as safe. + return "STATE_CHANGING" + + +def at_least_as_severe(declared: str, classified: str) -> bool: + """True when the declared tier is >= the classified tier.""" + return RISK_ORDER[declared] >= RISK_ORDER[classified] diff --git a/plugins/caelestia-assistant/assistant/capabilities/diagnostics/robust_baseline.py b/plugins/caelestia-assistant/assistant/capabilities/diagnostics/robust_baseline.py new file mode 100644 index 0000000..55d48ca --- /dev/null +++ b/plugins/caelestia-assistant/assistant/capabilities/diagnostics/robust_baseline.py @@ -0,0 +1,164 @@ +"""diagnostics.robust_baseline — a ROBUST Mahalanobis-distance baseline +over the telemetry layer's numeric metrics, so "is this machine behaving +like itself lately?" has a distribution-free-ish, outlier-resistant +answer instead of a mean/variance guess that the outliers it hunts +would poison. + +The method (each piece cited): + +- center = coordinate-wise MEDIAN, scale = 1.4826 x MAD (the median + absolute deviation with its Gaussian-consistency constant) — the + robust substitution for mean/stdev, per Leys, Klein, Bernard & + Laurent 2013, "Detecting outliers: Do not use standard deviation + around the mean, use absolute deviation around the median"; +- distance = the Mahalanobis distance with that diagonal robust + scatter (Mahalanobis 1936, "On the generalised distance in + statistics"): MD(x) = sqrt(sum_c ((x_c - median_c) / scale_c)^2); +- the p-value tail uses the EXISTING stats.chi2_sf primitive (MD^2 ~ + chi-square(k) under the stated independence/normality approximation + — the caveat travels with the report). + +Honesty rules (the reason this module exists in THIS repo): + +- a coordinate whose history never moved (MAD = 0) is EXCLUDED and + NAMED, never given a fake scale so the arithmetic keeps working; +- a sample coordinate that is absent (no battery, no thermal zone on + this machine) is excluded and counted, never imputed; +- if fewer than half of the baseline's kept coordinates are present in + the sample, the distance is REFUSED (thin evidence), not computed + from a rump; +- fewer than ``min_samples`` history rows is a refusal up front. + +Pure functions over caller-supplied numbers: this module never reads +/proc or /sys itself (the telemetry layer owns that read-only surface +and the caller hands the flattened vectors in). Deterministic, no RNG, +no clock, no I/O. +""" +from __future__ import annotations + +import math +from typing import Any, Dict, List, Sequence + +__all__ = ["flatten_snapshot", "robust_baseline", "mahalanobis", + "MIN_SAMPLES"] + +MIN_SAMPLES = 8 # a median over fewer rows is thin evidence by definition + +# The Gaussian-consistency constant for the MAD (Leys et al. 2013). +_MAD_TO_SIGMA = 1.4826 + + +def flatten_snapshot(snapshot: Dict[str, Any]) -> Dict[str, float]: + """The numeric metrics one telemetry.snapshot() contributes to the + baseline: load averages, memory used-ratio, mean thermal zone + temperature. Battery capacity is DELIBERATELY excluded — it cycles + by design, so it is a poor drift signal (documented, not an + oversight). Only available probes contribute; a desktop without a + battery simply has fewer coordinates.""" + out: Dict[str, float] = {} + load = snapshot.get("loadavg") or {} + if load.get("available"): + out["load1"] = float(load["load1"]) + out["load5"] = float(load["load5"]) + out["load15"] = float(load["load15"]) + mem = snapshot.get("meminfo") or {} + if mem.get("available") and mem.get("used_ratio") is not None: + out["mem_used_ratio"] = float(mem["used_ratio"]) + thermal = snapshot.get("thermal") or {} + temps = [z["temp_c"] for z in (thermal.get("zones") or []) + if isinstance(z, dict) and z.get("temp_c") is not None] + if temps: + out["thermal_mean_c"] = round(sum(temps) / len(temps), 3) + return out + + +def robust_baseline(history: Sequence[Dict[str, float]], + min_samples: int = MIN_SAMPLES) -> Dict[str, Any]: + """The robust center/scale per coordinate from the history rows + (caller-supplied flattened snapshots). Degenerate coordinates (MAD + = 0: the metric never moved) are excluded and NAMED.""" + if len(history) < min_samples: + raise ValueError( + f"need >= {min_samples} history rows for a robust baseline " + f"(got {len(history)}) — refusing to baseline on thin data") + coords: Dict[str, List[float]] = {} + for row in history: + for key, value in (row or {}).items(): + if isinstance(value, (int, float)) and not isinstance(value, bool): + coords.setdefault(key, []).append(float(value)) + if not coords: + raise ValueError("history rows contain no numeric coordinates") + center: Dict[str, float] = {} + scale: Dict[str, float] = {} + n: Dict[str, int] = {} + degenerate: List[str] = [] + for key in sorted(coords): + vals = sorted(coords[key]) + m = len(vals) + median = vals[m // 2] if m % 2 else (vals[m // 2 - 1] + vals[m // 2]) / 2.0 + mad = sorted(abs(v - median) for v in vals)[m // 2] + n[key] = m + if mad <= 0: + degenerate.append(key) # never moved: no honest scale exists + continue + center[key] = median + scale[key] = round(_MAD_TO_SIGMA * mad, 6) + if not center: + raise ValueError( + "every coordinate is degenerate (MAD = 0) — no honest " + "distance exists; the history shows no variation at all") + return {"center": center, "scale": scale, "n": n, + "kept": sorted(center), "degenerate": degenerate, + "n_history_rows": len(history), + "method": ("robust Mahalanobis: median center + 1.4826 x MAD " + "scale (Leys et al. 2013), diagonal scatter " + "(Mahalanobis 1936)")} + + +def mahalanobis(sample: Dict[str, float], + baseline: Dict[str, Any], + p_threshold: float = 0.01) -> Dict[str, Any]: + """The robust Mahalanobis distance of one sample from the baseline, + with per-coordinate contributions and the chi-square tail p-value + from the EXISTING stats primitive. Missing coordinates are excluded + and counted; fewer than half present is a refusal (thin evidence); + the verdict threshold is stated, the p-value is reported, and the + approximation caveat travels with the answer.""" + center = baseline.get("center") or {} + scale = baseline.get("scale") or {} + if not center: + raise ValueError("baseline has no kept coordinates") + used: Dict[str, float] = {} + missing: List[str] = [] + contributions: Dict[str, float] = {} + for key in sorted(center): + if key not in sample or sample[key] is None: + missing.append(key) + continue + value = float(sample[key]) + z = (value - center[key]) / scale[key] + used[key] = value + contributions[key] = round(z * z, 4) + if len(used) * 2 < len(center): + raise ValueError( + f"sample covers {len(used)} of {len(center)} baseline " + "coordinates — too thin to place honestly (refusing, not " + "extrapolating)") + md = math.sqrt(sum(contributions.values())) + k = len(used) + from assistant.capabilities.genius import stats as stats_mod # lazy: the layer boundary stays explicit + p = stats_mod.chi2_sf(md * md, k) + top = sorted(contributions.items(), key=lambda kv: (-kv[1], kv[0]))[:5] + return { + "distance": round(md, 4), + "coordinates_used": k, + "missing_in_sample": missing, + "top_contributions": dict(top), + "p_value": p, + "p_threshold": p_threshold, + "verdict": ("anomalous" if p is not None and p < p_threshold + else "within-baseline"), + "note": ("MD^2 ~ chi-square(k) assumes independent coordinates " + "and roughly Gaussian behavior per coordinate — the " + "p-value is an approximation, reported not worshipped"), + } diff --git a/plugins/caelestia-assistant/assistant/capabilities/diagnostics/rulepack.py b/plugins/caelestia-assistant/assistant/capabilities/diagnostics/rulepack.py new file mode 100644 index 0000000..25cd6ec --- /dev/null +++ b/plugins/caelestia-assistant/assistant/capabilities/diagnostics/rulepack.py @@ -0,0 +1,297 @@ +"""diagnostics.rulepack — the signed rule-pack format (exponential- +build-3 F1): share troubleshooting rules WITHOUT giving anyone a way +to smuggle auto-execution past the fences. + +THE FORMAT. A pack is one JSON document: + + {"schema_version": 1, + "pack": {"id": "...", "rulesets": [...], "rule_count": N, + "payload_sha256": ""}, + "payload": []} + +The payload is the SAME document shape assistant/diagnostics/rules.d +ships (schema_version / ruleset / provenance / rules), so a pack is +literally a bundle of existing ruleset files plus a manifest. + +SIGNING HAPPENS OUTSIDE — deliberately, and identically to the +lexicon-diff contract (cortex/lexicon_diff.py): the assistant does no +cryptography. The exporter writes canonical, byte-stable bytes; the +SHARER detaches an Ed25519 signature with a tool they already trust +(minisign / sq / gpg) over the pack FILE; the RECIPIENT verifies that +signature with their own tool BEFORE importing. The assistant's part +of the contract is two independent checks it CAN do honestly: + +- INTEGRITY (in-module): the manifest's payload_sha256 must equal the + sha256 of the canonical serialization of the embedded payload, so a + pack whose rules were edited after the manifest was written cannot + import even if nobody checks the signature; +- SAFETY (in-module): every rule in the payload passes the SAME + structural validation the built-in rulesets pass at load time + (engine.validate_rule, including the schema checks) plus the safety + lint the selfcheck runs (schema_lint.validate_rule_safety, including + the forbidden-key scan that makes auto-execution inexpressible). + A pack that fails ANY check is refused whole — no partial imports. + +IDENTITY IS A CLAIM, NOT A FACT: ``--signer`` records the name the +user verified with their external tool, exactly like lexicon import; +trust in that name stays a human judgment the assistant never makes. + +CONSENT: importing a pack stores it in the brain state as REVIEWABLE +DATA under "imported_rule_packs" (the existing state write path — +no new file, no new mechanism). Imported rules are deliberately NOT +live: the engine loads rules.d only, and wiring community rules into +live matching is a maintainer policy decision, not an import side +effect. ``render`` prints a pack's rules as a rules.d-ready document; +placing that file into rules.d is a human action and stays one. + +Pure module: no execution, no network, no RNG, no I/O beyond the +explicit paths its callers pass — canonical bytes are deterministic +for fixed input (pinned by test). +""" +from __future__ import annotations + +import hashlib +import json +from pathlib import Path +from typing import Any, Dict, List, Optional, Sequence, Union + +__all__ = ["RulePackError", "canonical_bytes", "payload_sha256", + "export_pack", "import_pack", "list_packs", "render_pack", + "render_rules_d"] + +PACK_SCHEMA_VERSION = 1 +STATE_KEY = "imported_rule_packs" + + +class RulePackError(ValueError): + """Every refusal (bad pack shape, hash mismatch, safety failure, + duplicate id, unknown ruleset) — the caller renders the reason; + nothing is guessed and nothing is partially imported.""" + + +# --------------------------------------------------------------------------- +# canonical bytes + integrity +# --------------------------------------------------------------------------- + +def canonical_bytes(payload: Any) -> bytes: + """The byte-stable serialization a signature can rest on: + sorted keys, no insignificant whitespace, ASCII-escaped, UTF-8. + Same input -> same bytes, always (pinned by test).""" + return json.dumps(payload, sort_keys=True, separators=(",", ":"), + ensure_ascii=True).encode("utf-8") + + +def payload_sha256(payload: Any) -> str: + return hashlib.sha256(canonical_bytes(payload)).hexdigest() + + +# --------------------------------------------------------------------------- +# export (build a shareable pack from shipped rulesets) +# --------------------------------------------------------------------------- + +def export_pack(rules_dir: Union[str, Path], rulesets: Sequence[str], + pack_id: str, source_note: str = "" + ) -> Dict[str, Any]: + """Bundle the named rulesets (rules.d file STEMS, e.g. + ``"config_kde"``) into a pack document. Every bundled ruleset is + read from ``rules_dir`` and every rule validated through the + ordinary structural + safety gates FIRST — an exporter ships only + rules that would survive import themselves. Unknown stems are + refused with the directory's actual listing.""" + if not pack_id or not isinstance(pack_id, str): + raise RulePackError("pack_id must be a non-empty string") + directory = Path(rules_dir) + available = sorted(p.stem for p in directory.glob("*.json")) + missing = [name for name in rulesets if name not in available] + if missing: + raise RulePackError( + f"unknown ruleset stem(s) {missing}; available in " + f"{directory}: {available}") + from .engine import validate_rule + from . import schema_lint + payload: List[Dict[str, Any]] = [] + rule_count = 0 + for stem in rulesets: + path = directory / f"{stem}.json" + try: + doc = json.loads(path.read_text(encoding="utf-8")) + except (OSError, ValueError) as exc: + raise RulePackError( + f"ruleset {stem!r} cannot be read ({exc})") from exc + if doc.get("schema_version") != 1: + raise RulePackError( + f"ruleset {stem!r}: unsupported schema_version " + f"{doc.get('schema_version')!r}") + failures: List[str] = [] + for rule in doc.get("rules", []): + failures.extend(validate_rule(rule, source=str(path))) + failures.extend( + schema_lint.validate_rule_safety(rule, str(path))) + if failures: + raise RulePackError( + f"ruleset {stem!r} failed validation and cannot be " + f"exported: {'; '.join(failures[:3])}") + payload.append(doc) + rule_count += len(doc.get("rules", [])) + manifest = { + "id": pack_id, + "rulesets": list(rulesets), + "rule_count": rule_count, + "payload_sha256": payload_sha256(payload), + "source_note": str(source_note or ""), + } + return {"schema_version": PACK_SCHEMA_VERSION, "pack": manifest, + "payload": payload} + + +# --------------------------------------------------------------------------- +# import (verify + store as reviewable data) +# --------------------------------------------------------------------------- + +def import_pack(pack: Union[str, Path, Dict[str, Any]], + existing_ids: Optional[Sequence[str]] = None, + signer: str = "") -> Dict[str, Any]: + """Verify one pack document and return the RECORD to store (the + caller persists it in the brain state — this module writes + nothing). Accepts a path, the pack's JSON text, or the parsed + dict. Checks, in order: document shape; payload hash INTEGRITY + (manifest sha256 == sha256 of canonical payload bytes); every + ruleset's schema_version; every rule's STRUCTURAL validity and + SAFETY lint (the same gates the built-ins pass); duplicate pack + id (refused — delete first, never a silent overwrite). Returns + the record: the manifest plus "payload", the claimed ``signer`` + (identity is a claim verified outside), and the validation stamp + (sha256 of the whole canonical pack — the audit trail).""" + if isinstance(pack, (str, Path)): + text = str(pack) + looks_like_json = text.lstrip().startswith("{") + path = Path(text) + if looks_like_json or not path.exists(): + try: + doc = json.loads(text) + except ValueError as exc: + raise RulePackError( + f"the pack is not valid JSON and not a readable " + f"file ({exc})") from exc + else: + try: + doc = json.loads(path.read_text(encoding="utf-8")) + except (OSError, ValueError) as exc: + raise RulePackError( + f"the pack file cannot be read ({exc})") from exc + else: + doc = pack + if not isinstance(doc, dict) \ + or doc.get("schema_version") != PACK_SCHEMA_VERSION \ + or not isinstance(doc.get("pack"), dict) \ + or not isinstance(doc.get("payload"), list): + raise RulePackError( + "not a rule pack: expected a document with schema_version " + f"{PACK_SCHEMA_VERSION}, a 'pack' manifest object, and a " + "'payload' list") + manifest = doc["pack"] + payload = doc["payload"] + pack_id = manifest.get("id") + if not isinstance(pack_id, str) or not pack_id: + raise RulePackError("the pack manifest has no id") + if existing_ids and pack_id in existing_ids: + raise RulePackError( + f"a pack named {pack_id!r} is already imported; remove it " + "first (rulepack forget) — imports never silently overwrite") + # integrity: the manifest hash is the whole point of the format + stated = manifest.get("payload_sha256") + actual = payload_sha256(payload) + if stated != actual: + raise RulePackError( + f"payload hash mismatch: manifest says {stated!r}, payload " + f"hashes to {actual!r} — the payload was modified after the " + "manifest was written; refusing") + if manifest.get("rule_count") != sum( + len(d.get("rules", [])) for d in payload): + raise RulePackError( + "manifest rule_count does not match the payload's rules") + # safety: the same gates the built-ins pass, nothing weaker + from .engine import validate_rule + from . import schema_lint + seen_rule_ids: set = set() + for doc_i, ruleset in enumerate(payload): + source = f"pack {pack_id!r} ruleset #{doc_i}" + if ruleset.get("schema_version") != 1: + raise RulePackError( + f"{source}: unsupported schema_version " + f"{ruleset.get('schema_version')!r}") + for rule in ruleset.get("rules", []): + failures = list(validate_rule(rule, source=source)) + failures.extend(schema_lint.validate_rule_safety(rule, source)) + if failures: + raise RulePackError( + f"{source}: rule refused — {'; '.join(failures)}; " + "the pack imports whole or not at all") + if rule["id"] in seen_rule_ids: + raise RulePackError( + f"{source}: duplicate rule id {rule['id']}") + seen_rule_ids.add(rule["id"]) + record = { + "id": pack_id, + "rulesets": manifest.get("rulesets", []), + "rule_count": manifest.get("rule_count", 0), + "payload_sha256": actual, + "pack_sha256": hashlib.sha256(canonical_bytes(doc)).hexdigest(), + "signer": str(signer or ""), + "payload": payload, + } + return record + + +def list_packs(state: Dict[str, Any]) -> List[Dict[str, Any]]: + """The stored pack records, oldest import first (copies, without + the bulky payload — the review view).""" + out = [] + for rec in state.get(STATE_KEY, []) or []: + out.append({k: v for k, v in rec.items() if k != "payload"}) + return out + + +# --------------------------------------------------------------------------- +# render (the review + human-placement surfaces) +# --------------------------------------------------------------------------- + +def render_pack(record: Dict[str, Any]) -> str: + """The human REVIEW view of one imported pack: id, claimed signer, + hashes, rulesets, and every rule id + title + severity.""" + lines = [f"rule pack {record.get('id')!r}", + f" claimed signer: {record.get('signer') or '(none recorded)'}" + " (identity is a claim — verify signatures with YOUR " + "external tool)", + f" payload sha256: {record.get('payload_sha256')}", + f" pack sha256 : {record.get('pack_sha256')}"] + for ruleset in record.get("payload", []): + name = ruleset.get("ruleset", "?") + lines.append(f" ruleset {name} " + f"({len(ruleset.get('rules', []))} rules):") + for rule in ruleset.get("rules", []): + lines.append(f" [{rule.get('severity', '?')}] " + f"{rule.get('id')}: {rule.get('title', '')}") + lines.append("imported rules are REVIEW DATA, not live: the engine " + "loads rules.d only; 'rulepack render' prints a " + "rules.d-ready file and PLACING it is a human action") + return "\n".join(lines) + + +def render_rules_d(record: Dict[str, Any]) -> str: + """The pack's rules as ONE rules.d-ready JSON document (stdout + text — this module never writes files). The human who decides to + trust a pack writes this to rules.d themselves; that decision is + the consent step and it stays human.""" + merged: Dict[str, Any] = { + "schema_version": 1, + "ruleset": f"imported-pack:{record.get('id')}", + "provenance": { + "imported_from_pack": record.get("id"), + "pack_payload_sha256": record.get("payload_sha256"), + "claimed_signer": record.get("signer") or "(none)", + }, + "rules": [rule for ruleset in record.get("payload", []) + for rule in ruleset.get("rules", [])], + } + return json.dumps(merged, indent=2) + "\n" diff --git a/plugins/caelestia-assistant/assistant/capabilities/diagnostics/rules.d/config_kde.json b/plugins/caelestia-assistant/assistant/capabilities/diagnostics/rules.d/config_kde.json new file mode 100755 index 0000000..2c6a4e5 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/capabilities/diagnostics/rules.d/config_kde.json @@ -0,0 +1,198 @@ +{ + "schema_version": 1, + "ruleset": "caelestia-layer1-config-kde", + "provenance": { + "generated_from": ["docs/TROUBLESHOOTING.md sections 3.3, 3.4, 3.7, 3.8, 5.1", "issues #14, #763, #6, #641, #416, #616"], + "repo_commit": "f91f4ec9" + }, + "rules": [ + { + "id": "CL-config-kmycolors-001", + "title": "kde-material-you-colors fights the shell: scheme resets to Material You Dark / screen flashes every second", + "category": "config", + "severity": "high", + "confidence": "deterministic", + "matchers": { + "anyOf": [ + { "type": "text_substring", "value": "kde-material-you-colors", "case_insensitive": true }, + { "type": "text_substring", "value": "material you dark", "case_insensitive": true }, + { "allOf": [ + { "type": "text_regex", "pattern": "screen flashes|flashing", "case_insensitive": true }, + { "type": "text_regex", "pattern": "every second|constantly|repeatedly", "case_insensitive": true } + ] } + ] + }, + "fix": [ + { "text": "Stop and disable the legacy color service — it is not part of this port and fights the shell's scheme pipeline.", "command": "systemctl --user disable --now kde-material-you-colors", "command_risk": "PRIVILEGED", "warning": "Disables a user service. This is the documented fix; the shell's own scheme engine replaces it." }, + { "text": "Confirm the apply-loop actually stopped.", "command": "pgrep -af plasma-apply-colorscheme", "command_risk": "READ_ONLY" }, + { "text": "Re-run the autostart step: it removes the service and leftover MaterialYou color files.", "command": "bash scripts/10-autostart.sh", "command_risk": "STATE_CHANGING" } + ], + "references": [ + { "kind": "doc", "anchor": "#37-screen-flashes-and-the-shell-stutters-every-second" }, + { "kind": "issue", "number": 14, "state": "closed" } + ] + }, + { + "id": "CL-config-schemereset-001", + "title": "Color variant falls back to Tonal Spot after every reboot/login", + "category": "config", + "severity": "medium", + "confidence": "deterministic", + "matchers": { + "allOf": [ + { "type": "text_substring", "value": "tonal spot", "case_insensitive": true }, + { "type": "text_regex", "pattern": "reboot|restart|log ?in|login|logout|log ?out", "case_insensitive": true } + ] + }, + "fix": [ + { "text": "Enable the automatic scheme hand-off: Nexus -> Colors -> Advanced Colors -> 'Automatic Color scheme' ON." }, + { "text": "Update the shell — the reset-after-restart bug was fixed on dev (maintainer marked it fixed).", "command": "bash update.sh", "command_risk": "STATE_CHANGING" } + ], + "references": [ + { "kind": "doc", "anchor": "#34-colors-not-applying" }, + { "kind": "issue", "number": 763, "state": "closed" } + ] + }, + { + "id": "CL-kde-bluez-001", + "title": "Bluetooth adapter turns on then immediately off; nothing pairs", + "category": "kde", + "severity": "medium", + "confidence": "deterministic", + "matchers": { + "allOf": [ + { "type": "text_substring", "value": "bluetooth", "case_insensitive": true }, + { "anyOf": [ + { "type": "text_substring", "value": "turns on then turns off", "case_insensitive": true }, + { "type": "text_substring", "value": "nothing pairs", "case_insensitive": true }, + { "type": "text_substring", "value": "won't pair", "case_insensitive": true } + ] } + ] + }, + "fix": [ + { "text": "This was a missing/misconfigured bluez stack, not a shell bug. Install the stack and enable the service.", "command": "sudo pacman -Sy bluez bluez-utils && sudo systemctl enable --now bluetooth.service", "command_risk": "PRIVILEGED", "warning": "Uses sudo; installs packages and enables a system service." }, + { "text": "If the KDE Bluetooth settings app also fails, it is a system/service problem — do not chase it through the shell config." } + ], + "references": [{ "kind": "issue", "number": 6, "state": "closed" }] + }, + { + "id": "CL-kde-thumbs-001", + "title": "Bar/taskbar thumbnails or launcher entries broken — desktop cache stale", + "category": "kde", + "severity": "low", + "confidence": "probable", + "matchers": { + "allOf": [ + { "type": "text_regex", "pattern": "thumbnails? (not|stop|stopped|aren'?t|isn'?t) (working|showing|appearing)|screencast preview", "case_insensitive": true } + ], + "anyOf": [ + { "type": "file_exists", "path": "~/.local/share/applications/quickshell.desktop", "expected": "present", "required": false }, + { "type": "text_substring", "value": "after update", "case_insensitive": true, "required": false } + ] + }, + "fix": [ + { "text": "Rebuild the KDE application cache, then ask KWin to reconfigure.", "command": "kbuildsycoca6 --noincremental", "command_risk": "STATE_CHANGING" }, + { "text": "Reconfigure KWin.", "command": "qdbus6 org.kde.KWin /KWin reconfigure", "command_risk": "STATE_CHANGING" }, + { "text": "If the quickshell desktop file is missing (thumbnails/screencast interfaces registered through it), re-run the autostart step.", "command": "ls ~/.local/share/applications/quickshell.desktop", "command_risk": "READ_ONLY" } + ], + "references": [{ "kind": "doc", "anchor": "#33-window-thumbnails--screencast-not-working" }] + }, + { + "id": "CL-kde-wstrack-001", + "title": "Workspace pills/tracker not running (KWin effect enabled but not loaded)", + "category": "kde", + "severity": "medium", + "confidence": "deterministic", + "matchers": { + "allOf": [ + { "type": "text_regex", "pattern": "workspace (pills|tracker)|workspace_tracker", "case_insensitive": true }, + { "type": "text_regex", "pattern": "not (running|loading|loaded|working)", "case_insensitive": true } + ] + }, + "fix": [ + { "text": "Run the repo's own checker; exit code 3 means enabled-but-not-loaded.", "command": "bash ~/.config/quickshell/caelestia/scripts/check-workspace-tracker.sh", "command_risk": "READ_ONLY" }, + { "text": "Rebuild/reinstall the effect via the updater, then log out and back in — KWin only loads effects at startup.", "command": "bash update.sh", "command_risk": "STATE_CHANGING" }, + { "text": "Verify the D-Bus service is introspectable after login.", "command": "qdbus6 org.kde.KWin /Caelestia/Workspaces org.freedesktop.DBus.Introspectable.Introspect", "command_risk": "READ_ONLY" } + ], + "references": [{ "kind": "doc", "anchor": "#38-workspace-tracker-effect-stops-loading-after-a-kde-update" }] + }, + { + "id": "CL-kde-fullscreen-001", + "title": "Gamescope games launch in half the screen (fullscreen broken)", + "category": "kde", + "severity": "low", + "confidence": "deterministic", + "matchers": { + "allOf": [ + { "type": "text_substring", "value": "gamescope", "case_insensitive": true }, + { "type": "text_regex", "pattern": "half of the screen|not fullscreen|half.?screen", "case_insensitive": true } + ] + }, + "fix": [ + { "text": "Update to latest dev — the fullscreen handling for gamescope-launched games was fixed after the report." }, + { "text": "Per-session workaround from the thread: toggle 'Dodge windows' for the game window." }, + { "text": "The thread's maintainer workaround edits the Shortcuts.qml file directly; it is overwritten by updates, so prefer updating.", "command": "$EDITOR ~/.config/quickshell/caelestia/modules/Shortcuts.qml", "command_risk": "STATE_CHANGING", "warning": "Edits an installed shell file in place; updates overwrite or conflict with it." } + ], + "references": [{ "kind": "issue", "number": 641, "state": "closed" }] + }, + { + "id": "CL-kde-monfocus-001", + "title": "Launcher opens on the monitor with the fullscreen video; alt-tab stops responding", + "category": "kde", + "severity": "low", + "confidence": "deterministic", + "matchers": { + "allOf": [ + { "type": "text_regex", "pattern": "fullscreen.{0,80}(monitor|screen|output)", "case_insensitive": true }, + { "type": "text_regex", "pattern": "launcher|alt.?tab|overview", "case_insensitive": true } + ] + }, + "fix": [ + { "text": "Update to latest dev: multi-monitor fullscreen focus fixes landed the same day this was reported; the video-wallpaper root cause is tracked alongside it." }, + { "text": "Check your current commit first.", "command": "git -C ~/caelestia-kde log --oneline -1", "command_risk": "READ_ONLY" } + ], + "references": [ + { "kind": "issue", "number": 416, "state": "closed" }, + { "kind": "issue", "number": 409, "state": "closed" } + ] + }, + { + "id": "CL-kde-gpumulti-001", + "title": "GPU widget shows roughly half the real usage (averaged across every DRM card)", + "category": "kde", + "severity": "low", + "confidence": "deterministic", + "matchers": { + "allOf": [ + { "type": "text_regex", "pattern": "gpu.{0,60}(widget|usage|stat|percentage)", "case_insensitive": true }, + { "anyOf": [ + { "type": "text_substring", "value": "/sys/class/drm" }, + { "type": "text_regex", "pattern": "averag|half|wrong|incorrect|both gpus|two gpus", "case_insensitive": true } + ] } + ] + }, + "fix": [ + { "text": "Verify per-card usage yourself — the old build averaged every card, so a 100% dGPU next to an idle iGPU showed ~50%.", "command": "for f in /sys/class/drm/card*/device/gpu_busy_percent; do echo \"$f: $(cat $f)\"; done", "command_risk": "READ_ONLY" }, + { "text": "Update to latest dev: the per-card averaging bug was fixed after being reported." } + ], + "references": [{ "kind": "issue", "number": 616, "state": "closed" }] + }, + { + "id": "CL-config-darkly-001", + "title": "Darkly window decoration/theme fails to apply", + "category": "config", + "severity": "low", + "confidence": "deterministic", + "matchers": { + "allOf": [ + { "type": "text_regex", "pattern": "lookandfeeltool --apply \\\"Darkly\\\" failed|darkly.{0,40}(not applied|unchanged|failed)", "case_insensitive": true } + ] + }, + "fix": [ + { "text": "Apply the decoration directly through kwin config, then reconfigure.", "command": "kwriteconfig6 --file kwinrc --group org.kde.kdecoration2 --key library org.kde.darkly && kwriteconfig6 --file kwinrc --group org.kde.kdecoration2 --key theme @darkly", "command_risk": "STATE_CHANGING" }, + { "text": "Reconfigure KWin.", "command": "qdbus6 org.kde.KWin /KWin reconfigure", "command_risk": "STATE_CHANGING" } + ], + "references": [{ "kind": "doc", "anchor": "#51-darkly-theme-not-applied" }] + } + ] +} diff --git a/plugins/caelestia-assistant/assistant/capabilities/diagnostics/rules.d/folder_cleanup.json b/plugins/caelestia-assistant/assistant/capabilities/diagnostics/rules.d/folder_cleanup.json new file mode 100755 index 0000000..f4a5155 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/capabilities/diagnostics/rules.d/folder_cleanup.json @@ -0,0 +1,153 @@ +{ + "schema_version": 1, + "ruleset": "caelestia-layer1-folder-cleanup", + "provenance": { + "generated_from": [ + "shell/utils/Paths.qml (imagecache, notifimagecache)", + "shell/plugin/src/Caelestia/Services/clipboardmanager.cpp (runtime clipboard dir)", + "shell/plugin/src/Caelestia/Services/weather.cpp (cache files)", + "docs/TROUBLESHOOTING.md sections 2.4, 3.4, 8.4, 9.6, 10.1", + "shell/utils/Paths.qml + userpaths.hpp (user media dirs)" + ], + "repo_commit": "f91f4ec9" + }, + "notes_on_shape": "Cleanup rules report sizes and suggest commands; the assistant NEVER deletes. Every rule states safe_to_delete per target: yes | ask_first | never.", + "rules": [ + { + "id": "CL-folder-cleanup-cache-001", + "title": "Free space: clean the shell's regenerable caches", + "category": "folder-cleanup", + "severity": "info", + "confidence": "deterministic", + "matchers": { + "anyOf": [ + { "type": "text_regex", "pattern": "free (up )?space|disk (full|usage)|clean.{0,20}cache|clear.{0,20}cache", "case_insensitive": true }, + { "type": "text_substring", "value": "cache bloat", "case_insensitive": true } + ] + }, + "fix": [ + { "text": "First look before deleting: measure each cache (all are regenerated on demand).", "command": "du -sh ~/.cache/caelestia/imagecache ~/.cache/caelestia/weather_cache.json ~/.cache/caelestia/cities.json 2>/dev/null", "command_risk": "READ_ONLY" }, + { "text": "Image cache (thumbnails, notification art) — safe_to_delete: yes, regenerated by ImageCacher.", "command": "rm -rf ~/.cache/caelestia/imagecache", "command_risk": "STATE_CHANGING", "warning": "Regenerated on demand; expect brief re-downloads/re-renders." }, + { "text": "Clipboard image cache — safe_to_delete: yes (tmpfs runtime dir, volatile anyway).", "command": "rm -rf \"${XDG_RUNTIME_DIR:-/tmp}/clipboard\"", "command_risk": "STATE_CHANGING", "warning": "Clears clipboard images for this session only." } + ], + "notes": "Doc anchor is a redirect: TROUBLESHOOTING.md has no dedicated cache/state section; section 11 (Diagnostic Commands Reference) is the closest useful target (cache/log paths and cache-refresh commands).", + "references": [{ "kind": "doc", "anchor": "#11-diagnostic-commands-reference" }] + }, + { + "id": "CL-folder-cleanup-build-001", + "title": "Free space: ccache and build logs from the installer (can reach gigabytes)", + "category": "folder-cleanup", + "severity": "info", + "confidence": "deterministic", + "matchers": { + "anyOf": [ + { "type": "text_regex", "pattern": "ccache|caelestia-kde.{0,30}cache", "case_insensitive": true }, + { "type": "text_regex", "pattern": "free (up )?space|disk (full|usage)", "case_insensitive": true } + ] + }, + "fix": [ + { "text": "Measure: ccache is capped at 8G by the installer; logs and failed_* files are tiny.", "command": "du -sh ~/.cache/caelestia-kde/ccache ~/.cache/caelestia-kde 2>/dev/null", "command_risk": "READ_ONLY" }, + { "text": "Trim ccache safely (keeps the tool working, drops old objects).", "command": "ccache -C", "command_risk": "STATE_CHANGING", "warning": "Clears the compiler cache; the next shell build recompiles from scratch (slower once)." }, + { "text": "safe_to_delete: never — ~/.config/caelestia-kde/install.env holds your install record; keep it." } + ], + "notes": "Doc anchor is the doc's only ccache section (stats/sizing). The installer overrides CCACHE_DIR to ~/.cache/caelestia-kde/ccache (8G cap, scripts/08-build-shell.sh), not section 1.4's default ~/.cache/ccache.", + "references": [{ "kind": "doc", "anchor": "#14-ccache-not-speeding-up-rebuilds" }] + }, + { + "id": "CL-folder-cleanup-updater-001", + "title": "Free space: updater repo clones (re-cloned automatically)", + "category": "folder-cleanup", + "severity": "info", + "confidence": "deterministic", + "matchers": { + "allOf": [ + { "type": "text_regex", "pattern": "free (up )?space|clean.{0,30}(updater|repo)", "case_insensitive": true } + ] + }, + "fix": [ + { "text": "Measure both known clone locations.", "command": "du -sh ~/.config/caelestia-update/repo ~/.cache/caelestia-update-repo 2>/dev/null", "command_risk": "READ_ONLY" }, + { "text": "safe_to_delete: yes — but the next update re-clones (slower first run).", "command": "rm -rf ~/.config/caelestia-update/repo ~/.cache/caelestia-update-repo", "command_risk": "DESTRUCTIVE", "warning": "Recursive force delete outside the cache scope. Updater logs live here; delete only when no update is running (see pgrep suggestion in the lock rule)." } + ], + "references": [{ "kind": "doc", "anchor": "#101-fixing-caelestia-updater-recommended" }] + }, + { + "id": "CL-folder-cleanup-state-001", + "title": "Organize: where the shell keeps state (scheme, wallpaper pointer) — mostly keep", + "category": "folder-cleanup", + "severity": "info", + "confidence": "deterministic", + "matchers": { + "anyOf": [ + { "type": "text_substring", "value": "where does caelestia store", "case_insensitive": true }, + { "type": "text_substring", "value": "shell state", "case_insensitive": true }, + { "type": "text_regex", "pattern": "organize|reorganize|tidy", "case_insensitive": true } + ] + }, + "fix": [ + { "text": "State lives in ${XDG_STATE_HOME:-~/.local/state}/caelestia/: scheme.json, wallpaper/path.txt, matugen/, theme/, whatsnew.json.", "command": "du -ah \"${XDG_STATE_HOME:-$HOME/.local/state}/caelestia\" 2>/dev/null | sort -rh | head -n 20", "command_risk": "READ_ONLY" }, + { "text": "safe_to_delete: ask_first — deleting scheme.json or wallpaper/path.txt reverts the desktop to the default palette on the next reseed; that is the documented reset path, not cleanup." }, + { "text": "Your content (never delete by rule): ~/Pictures/Screenshots, ~/Videos/Recordings, ~/Pictures/Wallpapers (override with CAELESTIA_WALLPAPERS_DIR). The assistant can report sizes/counts but never touches these.", "command": "du -sh ~/Pictures/Screenshots ~/Videos/Recordings ~/Pictures/Wallpapers 2>/dev/null", "command_risk": "READ_ONLY" } + ], + "notes": "Doc anchor is a redirect: TROUBLESHOOTING.md has no section on the XDG state directory; section 3.4 documents the scheme/wallpaper-pointer behavior (default palette when the pointer is missing, reseed via 'caelestia scheme set -n dynamic').", + "references": [{ "kind": "doc", "anchor": "#34-colors-not-applying" }] + }, + { + "id": "CL-folder-cleanup-wallpapers-001", + "title": "Organize wallpapers: report duplicates by name/size (report-only)", + "category": "folder-cleanup", + "severity": "info", + "confidence": "deterministic", + "matchers": { + "allOf": [ + { "type": "text_substring", "value": "wallpaper", "case_insensitive": true }, + { "type": "text_regex", "pattern": "duplicate|organize|tidy|clean|sort", "case_insensitive": true } + ] + }, + "fix": [ + { "text": "Report same-name/same-size pairs in the wallpaper dir (respects CAELESTIA_WALLPAPERS_DIR).", "command": "find \"${CAELESTIA_WALLPAPERS_DIR:-$HOME/Pictures/Wallpapers}\" -type f -printf '%s %p\\n' 2>/dev/null | sort -n | awk 'NR>1 && $1==prev {print \"duplicate-size: \" $2 \" and \" prevp} {prev=$1; prevp=$2}'", "command_risk": "READ_ONLY" }, + { "text": "Report-only rule: the assistant will not move or delete wallpapers — dedup decisions are yours. Set the folder via Nexus -> Appearance -> Wallpaper." } + ], + "notes": "Doc anchor is a redirect: TROUBLESHOOTING.md has no wallpaper-folder section; section 3.4's 'caelestia wallpaper -f ~/Pictures/Wallpapers/one.png' is the doc's only reference to the default wallpaper directory.", + "references": [{ "kind": "doc", "anchor": "#34-colors-not-applying" }] + }, + { + "id": "CL-folder-cleanup-legacy-001", + "title": "Clean leftovers from the legacy Material You setup (documented removals)", + "category": "folder-cleanup", + "severity": "low", + "confidence": "deterministic", + "matchers": { + "allOf": [ + { "anyOf": [ + { "type": "file_exists", "path": "~/.config/systemd/user/kde-material-you-colors.service", "expected": "present" }, + { "type": "text_regex", "pattern": "MaterialYou.{0,20}\\.colors|kde-material-you", "case_insensitive": true } + ] } + ] + }, + "fix": [ + { "text": "Check what is actually running/installed first.", "command": "systemctl --user status kde-material-you-colors; pgrep -af kde-material-you", "command_risk": "READ_ONLY" }, + { "text": "Disable the legacy service (see the color-conflict rule for the full fix).", "command": "systemctl --user disable --now kde-material-you-colors", "command_risk": "PRIVILEGED", "warning": "Disables a user service (documented migration step)." }, + { "text": "safe_to_delete: yes — stale generated color schemes.", "command": "rm -f ~/.local/share/color-schemes/MaterialYou*.colors", "command_risk": "STATE_CHANGING", "warning": "Removes generated MaterialYou color scheme files only." } + ], + "references": [{ "kind": "doc", "anchor": "#37-screen-flashes-and-the-shell-stutters-every-second" }] + }, + { + "id": "CL-folder-cleanup-shortcuts-001", + "title": "Reset the stolen-shortcuts ledger (ask first — it records your shortcut conflicts)", + "category": "folder-cleanup", + "severity": "info", + "confidence": "deterministic", + "matchers": { + "allOf": [ + { "type": "text_substring", "value": "stolen-shortcuts", "case_insensitive": true } + ] + }, + "fix": [ + { "text": "Look at it before touching it.", "command": "cat ~/.config/caelestia/stolen-shortcuts.json 2>/dev/null | head -n 40", "command_risk": "READ_ONLY" }, + { "text": "safe_to_delete: ask_first — deleting resets the recorded shortcut conflicts; the collision index rebuilds from defaults.", "command": "rm -f ~/.config/caelestia/stolen-shortcuts.json", "command_risk": "STATE_CHANGING", "warning": "Your recorded shortcut-theft resolutions are forgotten." }, + { "text": "If shortcuts misbehave after that, check the global shortcut daemon.", "command": "systemctl --user status plasma-kglobalaccel", "command_risk": "READ_ONLY" } + ], + "references": [{ "kind": "doc", "anchor": "#54-keyboard-shortcut-conflicts" }] + } + ] +} diff --git a/plugins/caelestia-assistant/assistant/capabilities/diagnostics/rules.d/idle_throttle.json b/plugins/caelestia-assistant/assistant/capabilities/diagnostics/rules.d/idle_throttle.json new file mode 100644 index 0000000..82baa4d --- /dev/null +++ b/plugins/caelestia-assistant/assistant/capabilities/diagnostics/rules.d/idle_throttle.json @@ -0,0 +1,41 @@ +{ + "schema_version": 1, + "ruleset": "idle-throttle", + "provenance": { + "generated_from": "Issue #120 Phase 2.3: a deterministic idle-state throttling rule. The proposal side (reduce blur/animation while the machine sits idle, revert on activity) mirrors the shipped battery-saver and gaming presets' exact tool calls, so every suggested change is already a validated registry tool. Read-only: the engine never executes anything; the settings changes ride the ledger propose/approve flow via assistant/brain/settings_bridge.py, and the round-trip is pinned by assistant/diagnostics/tests/test_idle_throttle.py.", + "repo_commit": "issue-120-phase-2" + }, + "rules": [ + { + "id": "CL-idle-throttle-001", + "title": "Battery drains while the machine sits idle: throttle blur/animation, revert on resume", + "category": "config", + "severity": "medium", + "confidence": "deterministic", + "matchers": { + "allOf": [ + { "anyOf": [ + { "type": "text_regex", "pattern": "(?i)(idle|overnight|suspend(ed)?|away).{0,80}(battery|drain|discharge|power)" }, + { "type": "text_regex", "pattern": "(?i)(battery|power).{0,80}(idle|overnight|suspend(ed)?|away)" }, + { "type": "text_regex", "pattern": "(?i)save power|power sav(e|ing)|battery life" } + ] } + ] + }, + "fix": [ + { "text": "Deterministic idle-throttle proposal (issue #120 phase 2.3): while the machine sits idle, blur compositing and long animations are the cheapest visible power sinks. The exact reductions below are the shipped battery-saver preset's own tool calls — nothing invented. Propose them as a pair in the ledger (brain settings propose), approve when you actually walk away, and propose the revert when you are back." }, + { "text": "Propose the throttle (dry-run preview, nothing written):", "command": "python3 -m assistant.capabilities.brain settings propose --file ~/.config/caelestia/shell.json --call setBlurEnabled=false --call setAnimationSpeed=0.25 --reason 'idle throttle: reduce blur and animation while away'", "command_risk": "STATE_CHANGING" }, + { "text": "Propose the revert for when activity resumes (blur back on, animations back to your normal speed — 1.0 is the shipped default):", "command": "python3 -m assistant.capabilities.brain settings propose --file ~/.config/caelestia/shell.json --call setBlurEnabled=true --call setAnimationSpeed=1.0 --reason 'idle throttle revert: activity resumed'", "command_risk": "STATE_CHANGING" }, + { "text": "Approve/reject the pending proposals with: brain ledger list, then brain ledger approve ID (approve applies through the gated applier with a backup; reject discards)." }, + { "text": "The one-shot, no-ledger equivalent is the battery-saver preset: caelestia-assist settings 'battery saver' --apply (multi-change, so it previews and asks for --confirm first)." } + ], + "undo": [ + { "text": "caelestia-assist settings --restore puts the single backup slot back, or --undo-id ID reverts one specific change from the bounded history." } + ], + "clarify_probe": "Paste `cat /sys/class/power_supply/BAT*/capacity` before and after the idle window (a plain read) — if the drop is under ~3% the drain is not the compositor and this rule is not your answer.", + "references": [ + { "kind": "issue", "number": 120, "state": "open" }, + { "kind": "doc", "anchor": "assistant/settings/tools.json — battery-saver and gaming presets (setBlurEnabled/setAnimationSpeed citations)" } + ] + } + ] +} diff --git a/plugins/caelestia-assistant/assistant/capabilities/diagnostics/rules.d/install.json b/plugins/caelestia-assistant/assistant/capabilities/diagnostics/rules.d/install.json new file mode 100755 index 0000000..03adfcd --- /dev/null +++ b/plugins/caelestia-assistant/assistant/capabilities/diagnostics/rules.d/install.json @@ -0,0 +1,234 @@ +{ + "schema_version": 1, + "ruleset": "caelestia-layer1-install", + "provenance": { + "generated_from": ["docs/TROUBLESHOOTING.md sections 1, 2, 6, 8.4, 8.6, 10.1", "issue #6 (pacman signature failure thread)"], + "repo_commit": "f91f4ec9" + }, + "rules": [ + { + "id": "CL-install-buildtools-001", + "title": "C++ installer TUI cannot compile: build tools (g++/cmake) missing", + "category": "install", + "severity": "high", + "confidence": "deterministic", + "matchers": { + "allOf": [ + { "type": "text_regex", "pattern": "(g\\+\\+|cc|gcc|cmake): command not found", "case_insensitive": true } + ] + }, + "fix": [ + { + "text": "Arch: install the base-devel group (g++, make, cmake and friends).", + "command": "sudo pacman -S --needed base-devel cmake", + "command_risk": "PRIVILEGED", + "warning": "Uses sudo; review the package list before confirming.", + "undo": "pacman -Rs cmake base-devel (rarely desired)" + }, + { + "text": "Fedora: install the C++ toolchain and CMake.", + "command": "sudo dnf install gcc-c++ cmake make", + "command_risk": "PRIVILEGED", + "warning": "Uses sudo; review before confirming." + }, + { + "text": "Debian/Ubuntu: install build-essential and CMake.", + "command": "sudo apt install build-essential cmake", + "command_risk": "PRIVILEGED", + "warning": "Uses sudo; review before confirming." + }, + { + "text": "Re-run the installer afterwards: bash scripts/setup.sh (it resumes from where it stopped)." + } + ], + "references": [{ "kind": "doc", "anchor": "#11-c-installer-compilation-fails" }] + }, + { + "id": "CL-install-fatal-001", + "title": "Installer died with [FATAL] Failed to build the Caelestia installer — read the build log first", + "category": "install", + "severity": "high", + "confidence": "deterministic", + "matchers": { + "allOf": [ + { "type": "text_regex", "pattern": "\\[FATAL\\] Failed to build the Caelestia installer" } + ] + }, + "fix": [ + { + "text": "Read the full build log — the real compiler error is in there, not in the TUI line.", + "command": "cat /tmp/caelestia_build.log | tail -n 100", + "command_risk": "READ_ONLY" + }, + { + "text": "If the log shows an old compiler, check the version (GCC 10+ required, C++20 project).", + "command": "g++ --version", + "command_risk": "READ_ONLY" + }, + { + "text": "After fixing the root cause, re-run setup: bash scripts/setup.sh" + } + ], + "references": [{ "kind": "doc", "anchor": "#11-c-installer-compilation-fails" }] + }, + { + "id": "CL-install-qmlmeta-001", + "title": "Shell build missing QML module metadata (Caelestia/Config qmldir not deployed)", + "category": "install", + "severity": "high", + "confidence": "deterministic", + "matchers": { + "allOf": [ + { "type": "text_regex", "pattern": "\\[ERR\\] Missing QML module metadata" }, + { "type": "text_substring", "value": "qmldir", "required": false } + ] + }, + "fix": [ + { + "text": "This is a stale/partial build artifact problem. Rebuild the shell from a clean tree.", + "command": "rm -rf shell/build shell/plugin/build && bash scripts/08-build-shell.sh", + "command_risk": "DESTRUCTIVE", + "warning": "Deletes the two build directories (regenerated by the next build). Your configs are not touched.", + "undo": "Not needed: build dirs are regenerated." + }, + { + "text": "Verify the plugin landed in the expected QML import path before starting the shell.", + "command": "ls ~/.local/lib/qt6/qml/Caelestia/Config/", + "command_risk": "READ_ONLY" + } + ], + "references": [{ "kind": "doc", "anchor": "#13-missing-qml-module-metadata-after-build" }] + }, + { + "id": "CL-install-crlf-001", + "title": "Line ending normalization step failed (CRLF in scripts)", + "category": "install", + "severity": "medium", + "confidence": "deterministic", + "matchers": { + "allOf": [ + { "type": "text_regex", "pattern": "\\[FATAL\\] Line ending normalization step failed" } + ] + }, + "fix": [ + { "text": "Install dos2unix so the step can fix the files, then re-run setup.", "command": "sudo pacman -S --needed dos2unix", "command_risk": "PRIVILEGED", "warning": "Uses sudo; review before confirming." }, + { "text": "Or answer 'n' when the installer offers to skip normalization; the rest of the install can proceed." } + ], + "references": [{ "kind": "doc", "anchor": "#23-crlf--dos2unix-failure" }] + }, + { + "id": "CL-install-pacsig-001", + "title": "pacman refuses to sync: invalid package signature from a mirror (keyring/mirror problem)", + "category": "install", + "severity": "high", + "confidence": "deterministic", + "matchers": { + "allOf": [ + { "type": "text_regex", "pattern": "error: .*: signature from .* is invalid" }, + { "type": "text_regex", "pattern": "failed to synchronize all databases|error: failed to commit transaction", "required": false } + ] + }, + "fix": [ + { "text": "Fix the keyring/mirror first, exactly as your distro documents it. On CachyOS/Arch this is usually the keyring, not this repo.", "command": "sudo pacman -Sy archlinux-keyring cachyos-keyring", "command_risk": "PRIVILEGED", "warning": "Uses sudo; adjust the keyring package names to your distro before running." }, + { "text": "Then refresh databases and only then re-run the installer — the maintainer's guidance in the thread was: fix signatures first, then rerun setup.", "command": "sudo pacman -Syu", "command_risk": "PRIVILEGED", "warning": "This performs a full system upgrade; review the package list." }, + { "text": "Re-run: bash scripts/setup.sh" } + ], + "references": [ + { "kind": "doc", "anchor": "#21-arch-linux--yay-failures" }, + { "kind": "issue", "number": 6, "state": "closed" } + ] + }, + { + "id": "CL-install-matugen-001", + "title": "matugen is not installed — color generation cannot run", + "category": "install", + "severity": "medium", + "confidence": "deterministic", + "matchers": { + "allOf": [ + { "type": "text_substring", "value": "matugen is not installed", "case_insensitive": true } + ] + }, + "fix": [ + { "text": "Arch: matugen is in the extra repository.", "command": "sudo pacman -S --needed matugen", "command_risk": "PRIVILEGED", "warning": "Uses sudo; review before confirming." }, + { "text": "Fedora: install via cargo (no distro package).", "command": "cargo install matugen", "command_risk": "STATE_CHANGING" } + ], + "references": [{ "kind": "doc", "anchor": "#21-arch-linux--yay-failures" }] + }, + { + "id": "CL-network-submodule-001", + "title": "src/dots submodule is empty — installer cannot deploy dotfiles", + "category": "network", + "severity": "high", + "confidence": "deterministic", + "matchers": { + "allOf": [ + { "type": "text_regex", "pattern": "\\[ERR\\] src/dots is still empty" } + ] + }, + "fix": [ + { "text": "Clone the upstream caelestia dotfiles into the submodule path.", "command": "git -C ~/caelestia-kde submodule update --init --recursive src/dots", "command_risk": "STATE_CHANGING" }, + { "text": "Then re-run the submodule deploy step.", "command": "bash scripts/02a-submodules.sh", "command_risk": "STATE_CHANGING" }, + { "text": "In a VM with a read-only shared folder (e.g. /mnt/hgfs), move the checkout to a real filesystem first; the docs call this out as a known trap." }, + { "text": "Behind a proxy, export http_proxy/https_proxy before re-running so git can fetch." } + ], + "references": [{ "kind": "doc", "anchor": "#62-git--submodule-failures" }] + }, + { + "id": "CL-update-stalepkg-001", + "title": "Upgrade replaced packages the running session still has in memory (logout/login or reboot needed)", + "category": "update", + "severity": "medium", + "confidence": "deterministic", + "matchers": { + "allOf": [ + { "type": "text_regex", "pattern": "The upgrade replaced packages the running session still has loaded in memory" } + ] + }, + "fix": [ + { "text": "The upgrade already applied; nothing is re-downloaded. Save your work." }, + { "text": "Log out and back in (or reboot) so the session loads the new libraries, then re-run the installer/update." } + ], + "references": [{ "kind": "doc", "anchor": "#86-installer-stops-after-a-system-upgrade" }] + }, + { + "id": "CL-post-install-lockfile-001", + "title": "Installer/update refuses to start: stale caelestia setup/update lock file", + "category": "post-install", + "severity": "medium", + "confidence": "deterministic", + "matchers": { + "allOf": [ + { "type": "text_substring", "value": "already running", "case_insensitive": true }, + { "type": "text_regex", "pattern": "caelestia-(setup|update)\\.lock", "required": false } + ] + }, + "fix": [ + { "text": "First confirm no installer/update process is actually alive (use Ctrl+C to stop one politely, not SIGKILL).", "command": "pgrep -af 'setup.sh|update.sh|caelestia-install'", "command_risk": "READ_ONLY" }, + { "text": "Only if nothing shows up, remove the stale lock.", "command": "rm -f \"${XDG_RUNTIME_DIR:-/tmp}/caelestia-setup.lock\" \"${XDG_RUNTIME_DIR:-/tmp}/caelestia-update.lock\"", "command_risk": "STATE_CHANGING", "warning": "Never remove the lock while an install is genuinely running." } + ], + "references": [{ "kind": "doc", "anchor": "#84-stale-lock-files" }] + }, + { + "id": "CL-update-updatercache-001", + "title": "Updater appears stuck cloning the repo — reset its local clone", + "category": "update", + "severity": "medium", + "confidence": "probable", + "matchers": { + "allOf": [ + { "type": "text_regex", "pattern": "updater.{0,40}(stuck|hang|frozen|no progress)|restart the process", "case_insensitive": true }, + { "anyOf": [ + { "type": "file_exists", "path": "~/.config/caelestia-update/repo", "expected": "present" }, + { "type": "file_exists", "path": "~/.cache/caelestia-update-repo", "expected": "present" } + ] } + ] + }, + "fix": [ + { "text": "Wait first — slow mirrors make the clone look hung; the docs recommend waiting before assuming stuck." }, + { "text": "If it truly is stuck, delete the updater's local clone; it re-clones on the next run.", "command": "rm -rf ~/.config/caelestia-update/repo ~/.cache/caelestia-update-repo", "command_risk": "DESTRUCTIVE", "warning": "Removes the updater's git clone (re-fetched automatically). Your shell settings are not stored here." } + ], + "references": [{ "kind": "doc", "anchor": "#101-fixing-caelestia-updater-recommended" }] + } + ] +} diff --git a/plugins/caelestia-assistant/assistant/capabilities/diagnostics/rules.d/known_regressions.json b/plugins/caelestia-assistant/assistant/capabilities/diagnostics/rules.d/known_regressions.json new file mode 100644 index 0000000..1eceef5 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/capabilities/diagnostics/rules.d/known_regressions.json @@ -0,0 +1,66 @@ +{ + "schema_version": 1, + "ruleset": "known-regressions", + "provenance": { + "generated_from": "Issue #120 Phase 4.4: deterministic rules fingerprinting two real, documented upstream regressions. Rule 1 cites upstream issue #629 (installer flips ccache in /etc/makepkg.conf permanently; closed 2026-09-06) - verified against the upstream issue body. Rule 2 fingerprints the dual-updater state-desync symptom; the mission brief called it '#818', but upstream issue #818 is unrelated ('CAELESTIA-KDE OVERHAUL', a PR-template issue) - the actual, verified issue is #565 ('Two independent update mechanisms share version-tracking state but pull from different repo checkouts', still OPEN), so the rule cites #565 and the discrepancy is recorded in the CHANGELOG.", + "repo_commit": "issue-120-phase-4" + }, + "rules": [ + { + "id": "CL-regression-ccache-629", + "title": "AUR/makepkg builds changed behavior after Caelestia: the installer enabled ccache system-wide (old installers, unreverted on uninstall)", + "category": "install", + "severity": "medium", + "confidence": "deterministic", + "matchers": { + "allOf": [ + { "anyOf": [ + { "type": "text_regex", "pattern": "(?i)(aur|makepkg).{0,100}(slow|cache miss|disk space|build time|behav)", "case_insensitive": true }, + { "type": "text_regex", "pattern": "(?i)makepkg\\.conf.{0,100}(changed|modif|ccache|enabled)", "case_insensitive": true }, + { "type": "text_substring", "value": "!ccache/ccache" } + ] }, + { "type": "text_regex", "pattern": "(?i)ccache|makepkg", "case_insensitive": true } + ] + }, + "fix": [ + { "text": "Upstream issue #629 (closed 2026-09-06): Caelestia's installer ran `sed -i 's/!ccache/ccache/' /etc/makepkg.conf` once, silently, and uninstall never reverted it. If you never enabled ccache yourself, check the file:", "command": "grep BUILDENV /etc/makepkg.conf", "command_risk": "READ_ONLY" }, + { "text": "To re-disable it (adjust the exact BUILDENV syntax to your file):", "command": "sudo sed -i 's/^BUILDENV=(\\([^)]*\\)ccache /\\1!ccache /' /etc/makepkg.conf", "command_risk": "PRIVILEGED", "warning": "Uses sudo and edits a system-wide file; review the line first with the grep above." }, + { "text": "Note: older uninstallers never touched /etc/makepkg.conf, so this system-wide change outlives Caelestia. Nothing in this assistant executes any of this; these are inert suggestions only." } + ], + "clarify_probe": "Paste the BUILDENV line from /etc/makepkg.conf (grep BUILDENV /etc/makepkg.conf) - if ccache is already prefixed with !, this rule is not your answer.", + "references": [ + { "kind": "issue", "number": 629, "state": "closed" } + ] + }, + { + "id": "CL-regression-dualupdater-565", + "title": "Update state desync: Nexus pending-commit count does not match your clone / uncommitted changes lost after 'Install Updates' (dual-updater symptom, PRE-fix versions)", + "category": "update", + "severity": "high", + "confidence": "probable", + "matchers": { + "allOf": [ + { "type": "text_regex", "pattern": "(?i)(nexus|install updates|updates page|check.updates|updater).{0,140}(pending|count|mismatch|wrong|stale|doesn'?t match|lost|overwrote|disappeared)", "case_insensitive": true }, + { "anyOf": [ + { "type": "text_regex", "pattern": "(?i)(uncommitted|local|my).{0,40}(changes?|edits?|work).{0,80}(lost|gone|overwritten|discarded|reverted)", "case_insensitive": true }, + { "type": "text_regex", "pattern": "(?i)current_commit.{0,100}(mismatch|different|wrong|stale)", "case_insensitive": true }, + { "type": "file_exists", "path": "~/.config/caelestia-update/repo", "expected": "present" } + ] } + ] + }, + "fix": [ + { "text": "Upstream issue #565 (OPEN): two updaters write the same version-tracking files from different checkouts. `update.sh` deploys from your real clone; the Nexus 'Install Updates' button (caelestia-update) deploys from a private shadow clone at ~/.config/caelestia-update/repo. Alternating between them desyncs the pending-commit badge and can overwrite uncommitted work." }, + { "text": "Check which commit the shell thinks it is running vs. your real clone:", "command": "cat ~/.config/quickshell/caelestia/.current_commit; git -C ~/caelestia-dots-kde rev-parse HEAD", "command_risk": "READ_ONLY" }, + { "text": "Pick ONE updater path and stick to it: dev-workflow users should use update.sh from their clone and avoid the Nexus button (or vice versa); the two must not alternate until upstream fixes the shared state.", "command_risk": "READ_ONLY" }, + { "text": "Before any future update: commit or stash local edits in your real clone first - the shadow-clone path does not stash them for you." } + ], + "undo": [ + { "text": "If uncommitted edits were overwritten, check `git -C ~/caelestia-dots-kde reflog` and `git stash list` - but note the shadow clone never touched the real clone's git state, so recovery depends on your own history." } + ], + "clarify_probe": "Paste the output of: cat ~/.config/quickshell/caelestia/.current_commit && git -C ~/caelestia-dots-kde rev-parse HEAD - and confirm which updater ran last (update.sh from your clone, or the Nexus 'Install Updates' button).", + "references": [ + { "kind": "issue", "number": 565, "state": "open" } + ] + } + ] +} diff --git a/plugins/caelestia-assistant/assistant/capabilities/diagnostics/rules.d/runtime.json b/plugins/caelestia-assistant/assistant/capabilities/diagnostics/rules.d/runtime.json new file mode 100755 index 0000000..b040ae3 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/capabilities/diagnostics/rules.d/runtime.json @@ -0,0 +1,171 @@ +{ + "schema_version": 1, + "ruleset": "caelestia-layer1-runtime", + "provenance": { + "generated_from": ["docs/TROUBLESHOOTING.md sections 3.1, 3.3.1, 4.1", "issues #333, #528, #418, #461, #402"], + "repo_commit": "f91f4ec9" + }, + "rules": [ + { + "id": "CL-runtime-shell-nostart-001", + "title": "Widgets never appear / shell does not start after login", + "category": "runtime-shell", + "severity": "critical", + "confidence": "deterministic", + "matchers": { + "anyOf": [ + { "type": "text_regex", "pattern": "quickshell: command not found" }, + { "type": "text_substring", "value": "blank screen at login", "case_insensitive": true }, + { "type": "text_substring", "value": "widgets not appearing", "case_insensitive": true }, + { + "type": "cmd_output", + "command": "systemctl --user is-enabled caelestia-shell.service", + "pattern": "disabled" + } + ] + }, + "fix": [ + { "text": "Check the user unit state and whether it is enabled.", "command": "systemctl --user status caelestia-shell.service && systemctl --user is-enabled caelestia-shell.service", "command_risk": "READ_ONLY" }, + { "text": "Quickstart check: log out and back in, or start the shell directly.", "command": "systemctl --user start caelestia-shell.service", "command_risk": "STATE_CHANGING" }, + { "text": "If it still fails, run the shell in debug mode in a terminal and read the first error line.", "command": "QML2_IMPORT_PATH=$HOME/.local/lib/qt6/qml quickshell -d -n -p ~/.config/quickshell/caelestia/shell.qml", "command_risk": "STATE_CHANGING", "warning": "This replaces the service-managed shell until you stop it; prefer the systemd unit afterwards." } + ], + "references": [ + { "kind": "doc", "anchor": "#31-shell-doesnt-start-after-login" }, + { "kind": "issue", "number": 528, "state": "closed" } + ] + }, + { + "id": "CL-runtime-shell-qmlerr-001", + "title": "Unrecognized pragma / DBus UnknownObjectPath after an update (fixed on dev — update the shell)", + "category": "runtime-shell", + "severity": "high", + "confidence": "deterministic", + "matchers": { + "allOf": [ + { "anyOf": [ + { "type": "text_regex", "pattern": "Unrecognized pragma \\\"DefaultEnv QS_NO_RELOAD_POPUP=1\\\"" }, + { "type": "text_regex", "pattern": "org\\.freedesktop\\.DBus\\.Error\\.UnknownObject" }, + { "type": "text_substring", "value": "No such object path '/component/caelestia'" } + ] } + ] + }, + "fix": [ + { "text": "This exact pair of errors was fixed on the dev branch. Update through the shell: Nexus -> Updates -> branch 'dev' -> Install Updates." }, + { "text": "Or from a terminal:", "command": "bash update.sh", "command_risk": "STATE_CHANGING" }, + { "text": "Restart through the unit afterwards.", "command": "systemctl --user restart caelestia-shell.service", "command_risk": "STATE_CHANGING" } + ], + "references": [ + { "kind": "issue", "number": 333, "state": "closed" } + ] + }, + { + "id": "CL-runtime-shell-noqt-001", + "title": "Quickshell errors/won't open right after updating to latest dev — reinstall the quickshell binary", + "category": "runtime-shell", + "severity": "high", + "confidence": "probable", + "matchers": { + "allOf": [ + { "type": "text_regex", "pattern": "(updated|upgraded).{0,60}(quickshell|dev version)", "case_insensitive": true }, + { "type": "text_regex", "pattern": "(error|won'?t open|does not open|fails to open|crash)", "case_insensitive": true } + ] + }, + "fix": [ + { "text": "In the reported case the quickshell binary itself was stale/corrupt after the update; reinstalling it fixed it.", "command": "sudo pacman -R quickshell-git && sudo pacman -S quickshell-git", "command_risk": "PRIVILEGED", "warning": "Removes and reinstalls the quickshell package (AUR name may differ on your system — check 'pacman -Qs quickshell' first).", "undo": "paru -S aur/quickshell-git" }, + { "text": "Check which quickshell package you actually have before removing anything.", "command": "pacman -Qs quickshell", "command_risk": "READ_ONLY" }, + { "text": "Then restart the shell unit.", "command": "systemctl --user restart caelestia-shell.service", "command_risk": "STATE_CHANGING" } + ], + "clarify_probe": "Paste the exact first error line from 'journalctl --user -u caelestia-shell -n 50' — it separates this from the pragma error rule.", + "references": [{ "kind": "issue", "number": 528, "state": "closed" }] + }, + { + "id": "CL-runtime-shell-crashrecov-001", + "title": "'Quickshell has crashed' dialog / window switcher stops listing windows (KWinActiveWindowBridge crash)", + "category": "runtime-shell", + "severity": "critical", + "confidence": "deterministic", + "matchers": { + "anyOf": [ + { "type": "text_substring", "value": "Quickshell has crashed", "case_insensitive": true }, + { "type": "text_substring", "value": "window switcher no longer shows windows", "case_insensitive": true }, + { "type": "text_regex", "pattern": "kwinactivewindowbridge.{0,40}crash", "case_insensitive": true } + ] + }, + "fix": [ + { "text": "Restart the shell through the systemd unit (the clean path — same environment it started with).", "command": "systemctl --user restart caelestia-shell.service", "command_risk": "STATE_CHANGING" }, + { "text": "If the unit restart hangs, force-stop the shell processes first, then restart.", "command": "killall quickshell; killall qs; systemctl --user restart caelestia-shell.service", "command_risk": "PRIVILEGED", "warning": "Kills the shell processes; any unsaved shell-side state is lost.", "undo": "systemctl --user start caelestia-shell.service" }, + { "text": "Only as a last resort (config corruption suspected), reset the shell config — this wipes your Nexus customizations.", "command": "rm -rf ~/.config/caelestia ~/.config/quickshell/caelestia", "command_risk": "DESTRUCTIVE", "warning": "This is the documented full reset: ALL shell settings, keybinds and AI config return to defaults. Back up ~/.config/caelestia first.", "undo": "Restore the backup you made before running this." } + ], + "references": [{ "kind": "issue", "number": 418, "state": "closed" }] + }, + { + "id": "CL-runtime-shell-memcrash-001", + "title": "Random app crashes (Chromium/Electron, Discord, Steam) alongside the shell — memory pressure pattern", + "category": "runtime-shell", + "severity": "high", + "confidence": "probable", + "matchers": { + "allOf": [ + { "type": "text_regex", "pattern": "random(ly)?\\s+(apps?\\s+)?crash", "case_insensitive": true }, + { "type": "text_regex", "pattern": "chromium|chrome|spotify|discord|steam|vesktop|helium", "case_insensitive": true } + ] + }, + "fix": [ + { "text": "In the resolved report this was the shell's memory growth; updating to latest dev plus keeping Live previews and the overview OFF stopped it." }, + { "text": "Measure before changing anything — is the shell process actually growing?", "command": "systemd-cgtop -m; grep VmRSS /proc/$(pgrep -n quickshell)/status; systemctl show user@$(id -u).service -p MemoryPeak", "command_risk": "READ_ONLY" }, + { "text": "Update to latest dev (Nexus -> Updates, branch dev), then keep bar 'Live window previews' and Overview disabled until the next release." } + ], + "clarify_probe": "Does 'systemd-cgtop -m' show the user slice climbing into swap during the crashes? (Paste the output.)", + "references": [{ "kind": "issue", "number": 461, "state": "closed" }] + }, + { + "id": "CL-runtime-shell-vesktop-001", + "title": "Vesktop/Discord freezes when screen sharing or camera turns on (KWin screencast conflict)", + "category": "runtime-shell", + "severity": "high", + "confidence": "deterministic", + "matchers": { + "allOf": [ + { "type": "text_regex", "pattern": "vesktop|discord|screen.?shar|screenshar|webcam|camera", "case_insensitive": true }, + { "anyOf": [ + { "type": "text_regex", "pattern": "zkde_screencast_unstable_v1" }, + { "type": "text_substring", "value": "freeze", "case_insensitive": true }, + { "type": "text_substring", "value": "freezes vesktop", "case_insensitive": true } + ] } + ] + }, + "fix": [ + { "text": "Disable live window previews: Nexus -> Taskbar -> 'Live window previews' toggle OFF." }, + { "text": "Or set it directly in the shell settings (opens an editor; the shell applies it live).", "command": "$EDITOR ~/.config/caelestia/shell.json # set \"bar\": { \"livePreviews\": false }", "command_risk": "STATE_CHANGING" }, + { "text": "Restart through the systemd unit so the change lands in the environment the shell started with.", "command": "systemctl --user restart caelestia-shell.service", "command_risk": "STATE_CHANGING", "warning": "Do NOT substitute 'caelestia shell -d': daemonising points the shell's stdio at /dev/null and apps launched from the shell inherit a dead stdout — that is the exact Vesktop deadlock from the issue." } + ], + "references": [ + { "kind": "doc", "anchor": "#331-screen-sharing--camera-freezes-vesktop-or-other-apps" }, + { "kind": "issue", "number": 402, "state": "closed", "closing_pr": 586 } + ] + }, + { + "id": "CL-runtime-lockscreen-lockpkg-001", + "title": "Stock Breeze lock screen appears instead of the Caelestia one", + "category": "runtime-lockscreen", + "severity": "medium", + "confidence": "deterministic", + "matchers": { + "anyOf": [ + { "type": "text_regex", "pattern": "(stock )?breeze lock screen", "case_insensitive": true }, + { + "type": "cmd_output", + "command": "kreadconfig6 --file plasmashellrc --group Shell --key ShellPackage", + "pattern": "org\\.kde\\.plasma\\.desktop|breeze" + } + ] + }, + "fix": [ + { "text": "Point the Plasma shell package back at caelestia and clear the greeter theme override.", "command": "kwriteconfig6 --file plasmashellrc --group Shell --key ShellPackage caelestia.desktop", "command_risk": "STATE_CHANGING" }, + { "text": "Remove the stale greeter theme key.", "command": "kwriteconfig6 --file kscreenlockerrc --group Greeter --key Theme --delete", "command_risk": "STATE_CHANGING" }, + { "text": "Log out and back in — the autostart script self-heals the lock screen on the next login." } + ], + "references": [{ "kind": "doc", "anchor": "#41-lock-screen-greeter-diagnostic" }] + } + ] +} diff --git a/plugins/caelestia-assistant/assistant/capabilities/diagnostics/schema_lint.py b/plugins/caelestia-assistant/assistant/capabilities/diagnostics/schema_lint.py new file mode 100755 index 0000000..52f786d --- /dev/null +++ b/plugins/caelestia-assistant/assistant/capabilities/diagnostics/schema_lint.py @@ -0,0 +1,149 @@ +"""Safety lint for Layer 1: the checks that go beyond structure. + +Structural validation lives in engine.validate_rule (run at load time). +This module adds the safety-specific layer: + +1. Forbidden-key scan — a rule cannot even *express* auto-execution: keys + matching auto_run/exec/execute/invoke/spawn/eval are rejected. +2. Risk consistency — every fix step that carries a command must declare a + command_risk tier at least as severe as what the risk classifier infers + from the command text (over-declaring is allowed, under-declaring is a + lint failure); PRIVILEGED/DESTRUCTIVE steps must carry a warning. +3. Import policy — the assistant's own Python must not import subprocess, + os.system, sockets, or anything else that could execute or transmit; +""" + +from __future__ import annotations + +import ast +import json +import re +from pathlib import Path +from typing import Any, Dict, List + +from . import engine +from . import risk + +ASSISTANT_DIR = Path(__file__).resolve().parents[2] +FORBIDDEN_KEY_RE = re.compile(r"(auto_?run|exec|execute|invoke|spawn|eval)", re.IGNORECASE) + +FORBIDDEN_IMPORTS = ( + "subprocess", + "socket", + "http", + "urllib", + "urllib2", + "requests", + "pty", + "shutil", + "ctypes", + "multiprocessing", + "asyncio", + "ftplib", + "telnetlib", + "smtplib", + "xmlrpc", + "webbrowser", +) + +FORBIDDEN_OS_ATTRS = ("system", "popen", "execv", "execve", "execvp", "spawnv", "spawnve", "fork") + +# Per-module quarantine carve-outs (the DBus proposal's exemption pattern, +# applied to every module that must import something the allow-list +# rejects BY NAME for all other files). Each entry names the ONE module +# allowed a named import; the set is pinned by test +# (diagnostics/tests/test_safety_lint.py) and every addition requires a +# matching the package rationale (see module docstrings) entry and a capability kill-switch defaulting to +# off in the module itself. This is a quarantine, never a relaxation: +# every other module in assistant/ stays under the zero-tolerance rule. +_QUARANTINED_IMPORTS: Dict[str, frozenset] = { + "executor/runner.py": frozenset({"subprocess"}), + "dbus_surface.py": frozenset({"subprocess"}), +} + + +def validate_rule_safety(rule: Dict[str, Any], source: str) -> List[str]: + """Safety checks on one rule beyond structural validation.""" + failures: List[str] = list(engine.validate_rule(rule, source=source)) + rule_id = rule.get("id", "") + + for key in rule: + if FORBIDDEN_KEY_RE.search(str(key)): + failures.append( + f"{source} {rule_id}: forbidden key {key!r} (rules cannot express auto-execution)" + ) + + try: + leaves = engine._walk_matchers(rule["matchers"]) + except ValueError: + leaves = [] + for leaf in leaves: + for key in leaf: + if FORBIDDEN_KEY_RE.search(str(key)): + failures.append(f"{source} {rule_id}: forbidden matcher key {key!r}") + + for step in rule.get("fix", []): + if not isinstance(step, dict): + continue + command = step.get("command") + if command is None: + continue + if not isinstance(command, str): + failures.append(f"{source} {rule_id}: command must be a string") + continue + declared = step.get("command_risk") + if declared not in risk.RISK_ORDER: + continue # structural check already reported this + classified = risk.classify(command) + if not risk.at_least_as_severe(declared, classified): + failures.append( + f"{source} {rule_id}: declared risk {declared} is weaker than classified " + f"{classified} for command {command[:60]!r}" + ) + if declared in ("DESTRUCTIVE", "PRIVILEGED") and not step.get("warning"): + failures.append(f"{source} {rule_id}: {declared} command requires a warning") + return failures + + +def check_rule_files() -> List[str]: + """Validate every rules.d/*.json file; also ensures ids are unique.""" + failures: List[str] = [] + seen: Dict[str, str] = {} + rule_files = sorted(engine.RULES_DIR.glob("*.json")) + if not rule_files: + return ["no rule files found"] + for path in rule_files: + try: + with open(path, "r", encoding="utf-8") as handle: + envelope = json.load(handle) + except json.JSONDecodeError as exc: + failures.append(f"{path}: invalid JSON: {exc}") + continue + if envelope.get("schema_version") != 1: + failures.append(f"{path}: schema_version must be 1") + for rule in envelope.get("rules", []): + failures.extend(validate_rule_safety(rule, source=path.name)) + rid = rule.get("id", "?") + if rid in seen: + failures.append(f"{path}: duplicate rule id {rid} (also in {seen[rid]})") + seen[rid] = path.name + return failures + + +def _iter_py_files() -> List[Path]: + root = ASSISTANT_DIR + return sorted(p for p in root.rglob("*.py") if "__pycache__" not in p.parts) + + +def run_all_checks() -> List[str]: + """Run every lint; returns the combined failure list.""" + failures: List[str] = [] + failures.extend(check_rule_files()) + return failures + + +if __name__ == "__main__": + problems = run_all_checks() + for problem in problems: + print(f"LINT FAIL: {problem}") + raise SystemExit(1 if problems else 0) diff --git a/plugins/caelestia-assistant/assistant/capabilities/diagnostics/settings_join.py b/plugins/caelestia-assistant/assistant/capabilities/diagnostics/settings_join.py new file mode 100644 index 0000000..fbcbb8a --- /dev/null +++ b/plugins/caelestia-assistant/assistant/capabilities/diagnostics/settings_join.py @@ -0,0 +1,141 @@ +"""Reverse lookup: matched diagnostic rule -> settings tools (A4, Tier A). + +The closed loop this module closes: Layer 1 (diagnostics) answers "what is +broken"; the settings layer (issue #120) answers "change this setting". +When a rule's ROOT CAUSE is addressable by a settings tool, the report can +now say so — "the settings tools addressing this root cause are X, Y" — +instead of leaving the user to guess the connection. + +The join is EXACT and VOLUNTEERED-ONLY, by design: + +- a rule's ``references`` entries of kind ``doc`` whose anchor names + ``assistant/settings/tools.json`` carry tool names explicitly + (e.g. CL-idle-throttle-001's anchor: "assistant/settings/tools.json — + battery-saver and gaming presets (setBlurEnabled/setAnimationSpeed + citations)"); +- tool NAMES (``setFooBar``) and registry PATHS (``bar.scale``) matched + word-exactly inside the rule's fix texts and notes. + +It deliberately does NOT join on noun vocabulary or fuzzy similarity: +"Bar/taskbar thumbnails ... broken" (CL-kde-thumbs-001) mentions +"thumbnails", a noun of ``setLivePreviews`` — but that rule's root cause +is desktop-cache staleness, and suggesting "turn live previews off" would +be a wrong fix delivered confidently. A join that guesses is worse than +no join; only references the rule itself volunteered are trusted. + +Every mention resolves through the settings layer's own citation +registry (``tool_by_name`` / ``tool_by_path`` over tools.json — the +generated, per-tool-citation-verified, drift-guarded artifact), so every +cross-reference that leaves this module is a real tools.json id by +construction. Mentions that do NOT resolve are reported separately +(``unresolved``) rather than silently dropped — a rule naming a +nonexistent tool is a content bug someone should see. + +PURE module: reads nothing from disk (callers pass the rule dicts the +engine already loaded); deterministic; no I/O, no execution. +""" + +from __future__ import annotations + +import re +from typing import Any, Dict, List + +from assistant.adapters.caelestia.registry import tool_by_name, tool_by_path + +__all__ = ["settings_tools_for_rule", "rules_for_tool", "SETTINGS_REGISTRY_ANCHOR"] + +SETTINGS_REGISTRY_ANCHOR = "assistant/settings/tools.json" + +_TOOL_NAME_RE = re.compile(r"\b(set[A-Z][A-Za-z0-9]+)\b") +_TOOL_PATH_RE = re.compile( + r"\b((?:bar|appearance|launcher|notifs|dock|overview|osd|sidebar|greeter)" + r"(?:\.[a-z][a-z0-9]*)+)\b" +) + +# Keys of the rule whose text participates in the join (fix step texts and +# notes — the places a rule explains its own fix). Matchers and titles are +# deliberately excluded: they describe the SYMPTOM, not the fix, and a +# symptom word joining to a tool is the wrong-fix hazard above. +_TEXT_KEYS = ("notes",) + + +def _texts(rule: Dict[str, Any]) -> List[str]: + """The rule's own fix/notes text surfaces as a flat string list.""" + out: List[str] = [] + for step in rule.get("fix", []) or []: + if isinstance(step, dict): + out.append(str(step.get("text", ""))) + for key in _TEXT_KEYS: + value = rule.get(key) + if isinstance(value, str): + out.append(value) + elif isinstance(value, list): + out.extend(str(v) for v in value) + return out + + +def _anchor_texts(rule: Dict[str, Any]) -> List[str]: + return [ + str(ref.get("anchor", "")) + for ref in rule.get("references", []) or [] + if isinstance(ref, dict) and ref.get("kind") == "doc" + ] + + +def settings_tools_for_rule(rule: Dict[str, Any]) -> Dict[str, Any]: + """The reverse lookup for ONE rule. + + Returns ``{"tools": [{"tool", "path", "found_in"}...], + "unresolved": [mention, ...]}`` — ``tools`` entries resolve + to real tools.json ids (verified via the citation registry); mentions + that did not resolve land in ``unresolved`` for human review. + """ + joined: Dict[str, Dict[str, Any]] = {} + unresolved: List[str] = [] + + def _join(name: str, found_in: str) -> None: + spec = tool_by_name(name) + if spec is None: + unresolved.append(name) + return + if name not in joined: + joined[name] = {"tool": spec.name, "path": spec.path, + "found_in": found_in} + + # 1. References that point INTO the settings registry itself. + for anchor in _anchor_texts(rule): + if SETTINGS_REGISTRY_ANCHOR not in anchor: + continue + for match in _TOOL_NAME_RE.finditer(anchor): + _join(match.group(1), f"reference: {anchor[:60]}...") + + # 2. Exact tool names / registry paths volunteered in fix + notes text. + for text in _texts(rule): + for match in _TOOL_NAME_RE.finditer(text): + _join(match.group(1), "fix/notes text") + for match in _TOOL_PATH_RE.finditer(text): + path = match.group(1) + spec = tool_by_path(path) + if spec is None: + unresolved.append(path) + continue + if spec.name not in joined: + joined[spec.name] = {"tool": spec.name, "path": spec.path, + "found_in": "fix/notes text"} + + return {"tools": [joined[k] for k in sorted(joined)], + "unresolved": sorted(set(unresolved))} + + +def rules_for_tool(tool_name: str, + rules: List[Dict[str, Any]]) -> List[str]: + """The other direction: which rules' fixes reference this tool. + + Useful for impact analysis before changing a tool ("which diagnostic + rules mention it?"). Returns rule ids, sorted.""" + out: List[str] = [] + for rule in rules: + joined = settings_tools_for_rule(rule) + if any(entry["tool"] == tool_name for entry in joined["tools"]): + out.append(str(rule.get("id", "?"))) + return sorted(out) diff --git a/plugins/caelestia-assistant/assistant/capabilities/diagnostics/stacking.py b/plugins/caelestia-assistant/assistant/capabilities/diagnostics/stacking.py new file mode 100644 index 0000000..0fd1c8a --- /dev/null +++ b/plugins/caelestia-assistant/assistant/capabilities/diagnostics/stacking.py @@ -0,0 +1,208 @@ +"""diagnostics.stacking — stacked generalization over the fusion pool +(exponential-build-4 D). + +Wolpert, "Stacked Generalization", Neural Networks 5(2), 1992: instead +of combining the confidences several engines emit with a FIXED rule +(here: fusion.py's weighted log-odds pool with hand-set weights), train +a META-LEARNER on level-1 data — the engines' own outputs — and let the +learned combiner do the mixing. The honest discipline the paper adds +and this module keeps: the meta-learner must be trained on outputs the +engines produced OUT OF SAMPLE (cross-validation), not on the same +rows they fit — combining in-sample outputs just memorizes the pool. + +What is stacked here: the three fusion sources (diagnostics rule +scores, retrieval BM25 saturations, scan hit densities) per hypothesis. +The level-2 learning target is each source's EMPIRICAL RELIABILITY — +the fraction of labeled rows where that source's own top pick was the +correct hypothesis — and the learned weight is the reliability's lift +over chance (1/K hypotheses), floored at 0, normalized to the pool's +total. A build-4 finding is recorded here honestly: the tempting +per-source logistic of (log-odds edge, "was the top pick right") is +CIRCULAR — the label is true exactly when the edge is positive, for +any source including a random one, so no fit on that pair can measure +reliability. The chance-lift statistic is the non-circular level-2 +learner, and the k-fold evaluate() is what makes the choice empirical. +The weights are DROP-IN for +``fusion.fuse(weights=stacked_weights(rows)["weights"])``: same +log-odds space, same weight semantics, interpretable by construction. + +SELECTABLE, NOT A REPLACEMENT: the fixed pool stays fusion.py's +default. ``evaluate`` runs the k-fold comparison — held-out Brier for +fixed-pool vs stacked — and reports BOTH with row counts. With few +labeled rows the stacked fit is thin and the report says so; a stacked +win is an empirical claim measured per call, never asserted. +Deterministic: round-robin folds in the rows' given order; the +logistic fit is fixed-iteration gradient descent, no RNG. Pure +functions, no I/O, no source is modified — fusion.py stays untouched. +""" +from __future__ import annotations + +import math +from typing import Any, Dict, List, Optional, Sequence, Tuple + +__all__ = ["stacked_weights", "evaluate", "SOURCES"] + +SOURCES = ("diagnostics", "retrieval", "scan") + +_ITERATIONS = 300 +_RATE = 0.08 +_FOLDS = 5 +_MIN_ROWS_FOR_STACKING = 12 + + +def _logit(p: float) -> float: + p = min(max(float(p), 1e-9), 1.0 - 1e-9) + return math.log(p / (1.0 - p)) + + +def _sigmoid(z: float) -> float: + z = max(-35.0, min(35.0, z)) + return 1.0 / (1.0 + math.exp(-z)) + + +def stacked_weights(rows: Sequence[Dict[str, Any]]) -> Dict[str, Any]: + """Fit the level-2 combiner, return per-source weights shaped for + ``fusion.fuse(weights=...)`` (normalized to the fixed pool's total + of 1.0). + + weight_s = max(0, reliability_s − 1/K) where reliability_s is the + empirical fraction of labeled rows where source s's own top pick + was the correct hypothesis, K the row's hypothesis count. The + floor is honest: a source right no more often than chance has no + vote; a source below chance is not asked to vote against itself + (fusion refuses negative weights), it is dropped and recorded. A + source with too few usable rows gets the pool's neutral 0.25 and a + thin-evidence flag — an abstention, not a fitted guess. + """ + if len(rows) < _MIN_ROWS_FOR_STACKING: + return { + "weights": {s: 0.25 for s in SOURCES}, + "n_rows": len(rows), + "thin": True, + "note": f"fewer than {_MIN_ROWS_FOR_STACKING} labeled rows: " + "a stacked fit would be a guess — the fixed pool's " + "neutral weights are returned instead", + } + lifts: Dict[str, Optional[float]] = {} + dropped: List[str] = [] + thin_sources: List[str] = [] + for source in SOURCES: + hits, trials, k = _reliability(rows, source) + if trials < max(4, _MIN_ROWS_FOR_STACKING // 2): + lifts[source] = None + thin_sources.append(source) + continue + chance = 1.0 / max(2, k) + lift = (hits / trials) - chance + if lift <= 0: + dropped.append(source) + lifts[source] = 0.0 + else: + lifts[source] = lift + positive = {s: v for s, v in lifts.items() if v} + if not positive: + weights = {s: 0.25 for s in SOURCES} + else: + total = sum(v for v in lifts.values() if v) + weights = {s: (round(lifts[s] / total, 4) if lifts[s] + else 0.0) for s in SOURCES} + return {"weights": weights, "n_rows": len(rows), "thin": False, + "thin_sources": thin_sources, "dropped_no_lift": dropped, + "note": "level-2 weights = empirical reliability of each " + "source's top pick minus chance (Wolpert 1992's " + "stacked discipline; the build-4 circularity finding " + "is in the module docstring) — drop-in for " + "fusion.fuse(weights=...)"} + + +def _reliability(rows: Sequence[Dict[str, Any]], source: str + ) -> Tuple[int, int, int]: + """(hits, trials, hypotheses) for one source: how often its own + top pick was the correct hypothesis, and the hypothesis count K.""" + hits = trials = 0 + k = 0 + for row in rows: + conf = row.get("confidences") or {} + correct = row.get("correct") + per = conf.get(source) or {} + if correct not in per or not per: + continue + k = max(k, len(per)) + trials += 1 + hits += 1 if max(per, key=lambda h: per[h]) == correct else 0 + return hits, trials, k + + +def evaluate(rows: Sequence[Dict[str, Any]], folds: int = _FOLDS + ) -> Dict[str, Any]: + """The k-fold comparison the selectable contract requires. Per + fold: learn weights on the training rows (stacked) against the + fixed DEFAULT pool, then on each test row compute the pooled + probability that the CORRECT hypothesis beats its best rival, + p = sigmoid(Σ_s w_s·logit(c_s,correct) + − max_r Σ_s w_s·logit(c_s,r)), + and score the Brier of (p, 1). Lower Brier = the combiner put more + probability on the truth. Both Briers are reported with row counts; + the winner is the measured one, per call — never asserted.""" + from .fusion import DEFAULT_WEIGHTS # the fixed pool being compared + + usable = [r for r in rows + if any(r.get("correct") in (r.get("confidences") or {}).get(s) or {} + for s in SOURCES)] + n = len(usable) + if n < _MIN_ROWS_FOR_STACKING: + return {"n": n, "folds": 0, "brier_fixed": None, + "brier_stacked": None, "winner": None, + "note": "not enough labeled rows to compare anything " + "honestly — bring more labeled routing history"} + fold_of = {i: i % folds for i in range(n)} + fixed_errors: List[float] = [] + stacked_errors: List[float] = [] + for f in range(folds): + train = [r for i, r in enumerate(usable) if fold_of[i] != f] + test = [r for i, r in enumerate(usable) if fold_of[i] == f] + if not train or not test: + continue + stacked = stacked_weights(train)["weights"] + for row in test: + conf = row.get("confidences") or {} + correct = row.get("correct") + if correct is None: + continue + hypotheses = sorted({h for s in SOURCES + for h in (conf.get(s) or {})}) + + def pooled(h: str, weights: Dict[str, float]) -> float: + acc = 0.0 + for s in SOURCES: + per = conf.get(s) or {} + c = per.get(h) + if c is None: + continue # a source with no opinion abstains + acc += weights.get(s, 0.0) * _logit(c) + return acc + + for weights, sink in ((DEFAULT_WEIGHTS, fixed_errors), + (stacked, stacked_errors)): + own = pooled(correct, weights) + rivals = [pooled(h, weights) for h in hypotheses + if h != correct] + if not rivals: + continue + p = _sigmoid(own - max(rivals)) + sink.append((1.0 - p) ** 2) + brier_fixed = (round(sum(fixed_errors) / len(fixed_errors), 4) + if fixed_errors else None) + brier_stacked = (round(sum(stacked_errors) / len(stacked_errors), 4) + if stacked_errors else None) + winner = None + if brier_fixed is not None and brier_stacked is not None: + winner = ("stacked" if brier_stacked < brier_fixed else + "fixed_pool" if brier_fixed < brier_stacked else "tie") + return {"n": n, "folds": folds, "brier_fixed": brier_fixed, + "brier_stacked": brier_stacked, "winner": winner, + "note": "held-out Brier of the pooled correct-vs-best-rival " + "probability, k-fold (round-robin over the given " + "order, deterministic); a one-stream win is " + "evidence, not a conclusion — the fixed pool stays " + "the default"} diff --git a/plugins/caelestia-assistant/assistant/capabilities/diagnostics/telemetry.py b/plugins/caelestia-assistant/assistant/capabilities/diagnostics/telemetry.py new file mode 100644 index 0000000..c948e2b --- /dev/null +++ b/plugins/caelestia-assistant/assistant/capabilities/diagnostics/telemetry.py @@ -0,0 +1,249 @@ +"""Read-only telemetry probes (issue #120 Phase 3.1) — plain file reads. + +The ONLY telemetry channel this assistant has: /proc and /sys files read +on demand via open()/pathlib — the same "file probes" precedent Layer 1 +already uses for file_exists matchers. No daemon, no poller, no inotify: +every function here runs when a diagnostic verb, a report, or a dreamtime +batch job calls it, and costs one file read. + +Probes (each takes an explicit path/glob parameter so tests can point it +at fixture files; the defaults are the real kernel interfaces): + +- loadavg /proc/loadavg -> 1/5/15-minute load +- meminfo /proc/meminfo -> total/available/used ratio +- battery /sys/class/power_supply/*/capacity -> per-battery percent +- thermal /sys/class/thermal/*/temp -> per-zone millidegrees C + +Missing files are reported as {"available": False} — honestly unavailable, +never guessed, never defaulted to a fake number. Import policy clean: +pathlib, glob, json — no executor, no network. + +The drain-rate helper exists for Phase 3.2: a battery-aware secondary +reward term needs a rate (%/hour) from two capacity samples, not just a +level. The mapping to the bandit's [0, 1] secondary reward lives next to +it (reward_from_drain) so the measurement→signal contract is stated once. +""" + +from __future__ import annotations + +import glob +import json +from pathlib import Path +from typing import Any, Dict, List, Optional, Union + +PathLike = Union[str, Path] + +# Battery drain-rate mapping (Phase 3.2 contract). +# A drain-rate DELTA of +/-DRAIN_FULL_DELTA_PCT_PER_H (%/hour faster or +# slower than before the preset was active) maps to the full [0, 1] +# secondary reward swing; beyond that it clamps. +DRAIN_FULL_DELTA_PCT_PER_H = 5.0 +# The secondary term can never outweigh one real approve/reject decision. +SECONDARY_REWARD_WEIGHT = 0.25 + + +def _read_text(path: PathLike) -> Optional[str]: + try: + return Path(path).read_text(encoding="utf-8", errors="replace") + except (OSError, ValueError): + return None + + +def read_loadavg(path: PathLike = "/proc/loadavg") -> Dict[str, Any]: + text = _read_text(path) + if text is None: + return {"available": False, "source": str(path)} + parts = text.split() + if len(parts) < 3: + return {"available": False, "source": str(path)} + try: + return {"available": True, "source": str(path), + "load1": float(parts[0]), "load5": float(parts[1]), + "load15": float(parts[2])} + except ValueError: + return {"available": False, "source": str(path)} + + +def read_meminfo(path: PathLike = "/proc/meminfo") -> Dict[str, Any]: + text = _read_text(path) + if text is None: + return {"available": False, "source": str(path)} + fields: Dict[str, int] = {} + for line in text.splitlines(): + key, _, rest = line.partition(":") + value = rest.strip().split() + if value and value[0].isdigit(): + fields[key.strip()] = int(value[0]) + total = fields.get("MemTotal") + if total is None: + return {"available": False, "source": str(path)} + available = fields.get("MemAvailable", fields.get("MemFree")) + result: Dict[str, Any] = {"available": True, "source": str(path), + "total_kb": total} + if available is not None: + result["available_kb"] = available + result["used_ratio"] = round(1.0 - available / total, 4) if total else None + return result + + +def read_battery(pattern: str = "/sys/class/power_supply/*/capacity") -> Dict[str, Any]: + rows: List[Dict[str, Any]] = [] + for path in sorted(glob.glob(pattern)): + text = _read_text(path) + if text is None: + continue + try: + pct = int(text.strip()) + except ValueError: + continue + if 0 <= pct <= 100: + rows.append({"path": path, "capacity_pct": pct}) + return {"available": bool(rows), "batteries": rows} + + +def read_thermal(pattern: str = "/sys/class/thermal/*/temp") -> Dict[str, Any]: + rows: List[Dict[str, Any]] = [] + for path in sorted(glob.glob(pattern)): + text = _read_text(path) + if text is None: + continue + try: + milli = int(text.strip()) + except ValueError: + continue + rows.append({"path": path, "temp_c": round(milli / 1000.0, 1)}) + return {"available": bool(rows), "zones": rows} + + +def snapshot(proc_dir: str = "/proc", sys_dir: str = "/sys") -> Dict[str, Any]: + """One on-demand snapshot of every probe that is available. + + Never raises for missing interfaces: each probe reports its own + availability, so a container or a desktop without a battery yields an + honest partial snapshot. + """ + return { + "loadavg": read_loadavg(Path(proc_dir) / "loadavg"), + "meminfo": read_meminfo(Path(proc_dir) / "meminfo"), + "battery": read_battery(str(Path(sys_dir) / "class/power_supply/*/capacity")), + "thermal": read_thermal(str(Path(sys_dir) / "class/thermal/*/temp")), + } + + +# --------------------------------------------------------------------------- +# Phase 3.2 helpers: battery drain rate -> the bandit's secondary reward. +# --------------------------------------------------------------------------- + +def drain_rate_percent_per_hour(capacity_before: float, capacity_after: float, + hours: float) -> float: + """Positive = the battery DRAINED at that rate (%/hour). + + Raises ValueError for a non-positive window or capacities outside + [0, 100] — measurement garbage is refused, not averaged in. + """ + if hours <= 0: + raise ValueError("hours must be > 0") + for value in (capacity_before, capacity_after): + if not 0 <= value <= 100: + raise ValueError("capacities must be percentages in [0, 100]") + return (capacity_before - capacity_after) / hours + + +def reward_from_drain_delta(delta_pct_per_hour: float, + full_delta: float = DRAIN_FULL_DELTA_PCT_PER_H, + ) -> float: + """A drain-rate DELTA (%/hour; negative = battery drains SLOWER than + before, i.e. the preset helped) -> secondary reward in [0, 1]. + + 0.5 is the neutral midpoint. Mapping: 0.5 - 0.5 * clamp(delta / + full_delta) — a 5%/h improvement with the default full_delta gives 1.0, + a 5%/h regression gives 0.0. The bandit weights this by + SECONDARY_REWARD_WEIGHT, so it can never outweigh one real + approve/reject decision. + """ + if full_delta <= 0: + raise ValueError("full_delta must be > 0") + clamped = max(-full_delta, min(full_delta, delta_pct_per_hour)) + return round(0.5 - 0.5 * (clamped / full_delta), 4) + + +def main(argv: Optional[List[str]] = None) -> int: + import argparse + + parser = argparse.ArgumentParser( + prog="telemetry", + description="Read-only /proc and /sys snapshot (on-demand; runs " + "once, prints, exits — never a daemon).") + parser.add_argument("--proc", default="/proc", help="proc base dir override") + parser.add_argument("--sys", default="/sys", help="sys base dir override") + parser.add_argument("--json", action="store_true", help="machine-readable output") + args = parser.parse_args(argv) + snap = snapshot(proc_dir=args.proc, sys_dir=args.sys) + if args.json: + print(json.dumps(snap, indent=2)) + return 0 + load = snap["loadavg"] + if load["available"]: + print(f"load: {load['load1']:.2f} {load['load5']:.2f} {load['load15']:.2f}") + mem = snap["meminfo"] + if mem["available"]: + used = mem.get("used_ratio") + print(f"memory: {mem.get('available_kb', '?')} kB available of " + f"{mem['total_kb']} kB" + (f" (used {used:.0%})" if used is not None else "")) + bat = snap["battery"] + for row in bat["batteries"]: + print(f"battery: {row['capacity_pct']}% ({row['path']})") + for row in snap["thermal"]["zones"]: + print(f"thermal: {row['temp_c']}C ({row['path']})") + missing = [name for name, probe in snap.items() if not probe["available"]] + if missing: + print("unavailable: " + ", ".join(missing)) + return 0 + + +# --------------------------------------------------------------------------- +# Time-series accumulation (exponential-build-4 E) — the bridge between +# the one-shot snapshot above and diagnostics/forecast.py's Kalman trend. +# The series lives in the caller's learned-state JSON (the enumerated +# write path); this module still performs no writes itself. +# --------------------------------------------------------------------------- + +SERIES_STATE_KEY = "telemetry_series" +SERIES_MAX_POINTS = 240 + + +def _flatten(snapshot: Dict[str, Any]) -> Dict[str, float]: + """The numeric leaves of one snapshot as a flat {metric: value} — + the same flattening convention robust_baseline.flatten_snapshot + uses, so both consumers agree on metric names.""" + from . import robust_baseline + return robust_baseline.flatten_snapshot(snapshot) + + +def record_series(state: Dict[str, Any], snapshot: Dict[str, Any], + when: str, key: str = SERIES_STATE_KEY) -> Dict[str, Any]: + """Append one flattened snapshot to the persisted series. ``when`` + is the caller-supplied ISO timestamp (determinism: nothing here + reads the clock). Bounded at SERIES_MAX_POINTS (oldest dropped — + a series that grows without bound is a leak, not a feature).""" + flat = _flatten(snapshot) + series = state.setdefault(key, []) + series.append({"when": when, "metrics": flat}) + if len(series) > SERIES_MAX_POINTS: + del series[:len(series) - SERIES_MAX_POINTS] + return series + + +def series_for(state: Dict[str, Any], metric: str, + key: str = SERIES_STATE_KEY) -> List[Tuple[str, float]]: + """One metric's [(when, value)] series in arrival order — the input + shape diagnostics.forecast.steady_state_kalman consumes (values + only) with the dates carried for the human report. Missing + readings are SKIPPED, not interpolated (a gap is honest; a + fabricated point is not).""" + out: List[Tuple[str, float]] = [] + for row in state.get(key, []): + metrics = row.get("metrics") or {} + if metric in metrics and isinstance(metrics[metric], (int, float)): + out.append((row.get("when", ""), float(metrics[metric]))) + return out From 71f26e6516f374907f4318fb5b306417a317b654 Mon Sep 17 00:00:00 2001 From: 0x0nYx <0x0nYx@users.noreply.github.com> Date: Fri, 9 Oct 2026 12:19:16 +0000 Subject: [PATCH 08/10] feat(assistant): natural-language settings capability (issue #120): registry, planner, applier (migration chunk 7/12) The natural-language settings capability (issue #120): the frozen tool registry over the shell's settings schema, parser, planner, applier with bounded undo, presets, profiles, wizard, lint and the D-Bus surface. Chunk contents (33 files): - assistant/capabilities/settings/__init__.py - assistant/capabilities/settings/__main__.py - assistant/capabilities/settings/accessibility.py - assistant/capabilities/settings/applier.py - assistant/capabilities/settings/build_registry.py - assistant/capabilities/settings/catalog.py - assistant/capabilities/settings/causal.py - assistant/capabilities/settings/cli.py - assistant/capabilities/settings/consequences.py - assistant/capabilities/settings/curations.py - assistant/capabilities/settings/dbus_surface.py - assistant/capabilities/settings/enumerate.py - ... and 21 more Source: 0x0nYx/caelestia-assistant@2c193e7 (main, v0.1) Faithfulness: byte-identical copy (sha256-verified in the migration audit; only metadata.json / README.md are plugin-store scaffolding, and .caelestia-audit-ignore documents scanner false positives). Safety audit: 0 errors; 36 line-level findings documented in .caelestia-audit-ignore (string vocabularies / rulepack prose / test assertion targets / opt-in provider calls - nothing executes). Store CI: validate.py OK - check_safety.py OK - check_scope.py OK. Next chunk: plugin/caelestia-assistant/08-brain --- .../capabilities/settings/__init__.py | 65 + .../capabilities/settings/__main__.py | 11 + .../capabilities/settings/accessibility.py | 155 ++ .../capabilities/settings/applier.py | 299 +++ .../capabilities/settings/build_registry.py | 361 +++ .../capabilities/settings/catalog.py | 183 ++ .../assistant/capabilities/settings/causal.py | 307 +++ .../assistant/capabilities/settings/cli.py | 2079 +++++++++++++++++ .../capabilities/settings/consequences.py | 322 +++ .../capabilities/settings/curations.py | 675 ++++++ .../capabilities/settings/dbus_surface.py | 506 ++++ .../capabilities/settings/enumerate.py | 584 +++++ .../capabilities/settings/envaudit.py | 196 ++ .../capabilities/settings/environments.py | 354 +++ .../capabilities/settings/explain.py | 511 ++++ .../capabilities/settings/gen_adapter.py | 228 ++ .../capabilities/settings/history.py | 292 +++ .../assistant/capabilities/settings/lint.py | 256 ++ .../assistant/capabilities/settings/macros.py | 210 ++ .../capabilities/settings/manifest.py | 10 + .../capabilities/settings/monitors.py | 137 ++ .../capabilities/settings/optimize.py | 569 +++++ .../assistant/capabilities/settings/parser.py | 674 ++++++ .../assistant/capabilities/settings/plain.py | 139 ++ .../capabilities/settings/planner.py | 336 +++ .../capabilities/settings/presets.py | 111 + .../capabilities/settings/profile_preview.py | 180 ++ .../capabilities/settings/profiles.py | 304 +++ .../capabilities/settings/recommend.py | 212 ++ .../assistant/capabilities/settings/sanity.py | 184 ++ .../assistant/capabilities/settings/slots.py | 391 ++++ .../capabilities/settings/ui_ranges_data.py | 328 +++ .../assistant/capabilities/settings/wizard.py | 193 ++ 33 files changed, 11362 insertions(+) create mode 100755 plugins/caelestia-assistant/assistant/capabilities/settings/__init__.py create mode 100755 plugins/caelestia-assistant/assistant/capabilities/settings/__main__.py create mode 100644 plugins/caelestia-assistant/assistant/capabilities/settings/accessibility.py create mode 100755 plugins/caelestia-assistant/assistant/capabilities/settings/applier.py create mode 100755 plugins/caelestia-assistant/assistant/capabilities/settings/build_registry.py create mode 100644 plugins/caelestia-assistant/assistant/capabilities/settings/catalog.py create mode 100644 plugins/caelestia-assistant/assistant/capabilities/settings/causal.py create mode 100755 plugins/caelestia-assistant/assistant/capabilities/settings/cli.py create mode 100644 plugins/caelestia-assistant/assistant/capabilities/settings/consequences.py create mode 100755 plugins/caelestia-assistant/assistant/capabilities/settings/curations.py create mode 100644 plugins/caelestia-assistant/assistant/capabilities/settings/dbus_surface.py create mode 100755 plugins/caelestia-assistant/assistant/capabilities/settings/enumerate.py create mode 100644 plugins/caelestia-assistant/assistant/capabilities/settings/envaudit.py create mode 100644 plugins/caelestia-assistant/assistant/capabilities/settings/environments.py create mode 100755 plugins/caelestia-assistant/assistant/capabilities/settings/explain.py create mode 100644 plugins/caelestia-assistant/assistant/capabilities/settings/gen_adapter.py create mode 100755 plugins/caelestia-assistant/assistant/capabilities/settings/history.py create mode 100644 plugins/caelestia-assistant/assistant/capabilities/settings/lint.py create mode 100644 plugins/caelestia-assistant/assistant/capabilities/settings/macros.py create mode 100644 plugins/caelestia-assistant/assistant/capabilities/settings/manifest.py create mode 100644 plugins/caelestia-assistant/assistant/capabilities/settings/monitors.py create mode 100644 plugins/caelestia-assistant/assistant/capabilities/settings/optimize.py create mode 100755 plugins/caelestia-assistant/assistant/capabilities/settings/parser.py create mode 100644 plugins/caelestia-assistant/assistant/capabilities/settings/plain.py create mode 100755 plugins/caelestia-assistant/assistant/capabilities/settings/planner.py create mode 100755 plugins/caelestia-assistant/assistant/capabilities/settings/presets.py create mode 100644 plugins/caelestia-assistant/assistant/capabilities/settings/profile_preview.py create mode 100644 plugins/caelestia-assistant/assistant/capabilities/settings/profiles.py create mode 100644 plugins/caelestia-assistant/assistant/capabilities/settings/recommend.py create mode 100644 plugins/caelestia-assistant/assistant/capabilities/settings/sanity.py create mode 100644 plugins/caelestia-assistant/assistant/capabilities/settings/slots.py create mode 100755 plugins/caelestia-assistant/assistant/capabilities/settings/ui_ranges_data.py create mode 100644 plugins/caelestia-assistant/assistant/capabilities/settings/wizard.py diff --git a/plugins/caelestia-assistant/assistant/capabilities/settings/__init__.py b/plugins/caelestia-assistant/assistant/capabilities/settings/__init__.py new file mode 100755 index 0000000..e97c9a1 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/capabilities/settings/__init__.py @@ -0,0 +1,65 @@ +"""Layer 5 of the caelestia assistant: natural-language settings editing +(#120) — the module that a 18-tool natural-language core answers, generated +generated registry (272 tools at the 2026-09-28 resync), explain, bounded undo, presets — the module that +answers "change this setting" while the four troubleshooting layers answer +"what is broken". + +Pipeline: text -> parser.parse (pure) -> planner.plan (validated plan +against the target file) -> applier.apply (the only writer, gated). + +Guarantees shared by every module in this package: + +- Dry-run by default: nothing is ever written unless the caller passes the + explicit --apply gate — and any plan touching more than one setting + additionally needs --confirm (second consent) or an interactive yes, + implementing #120's "confirmation for larger changes". A dry run writes + no file at all (no target, no backup, no tmp). +- One writer, four paths: applier.py is the ONLY module that writes + anything, and only behind --apply. It writes exactly the explicit target + file (via a transient .assistant-tmp + atomic os.replace), its + .assistant-backup sibling (single-slot, one-level undo via --restore), + its .assistant-history.json sibling (the bounded 12-entry undo history + that --history lists and --undo/--undo-id consume), and removes the tmp + after the rename. No other path is ever opened for writing; parent + directories are never created. The planner reads the target file and, + best-effort and read-only, per-monitor override files (to warn that a + global change would be shadowed) — never writes them. +- Additional surfaces: --explain answers "why does it look like this" against + effective values (file value else registry default) and never writes; + --history lists the bounded undo history (read-only); --undo/--undo-id + consume history entries and write only the reverted values; + --preset/--list-presets apply named bundles of already-validated tool + calls through the ordinary planner path (build-time validated; a preset + is never a bespoke code path). +- Validated before written: every value is checked against the frozen + generated registry (types, ranges, enums; 19 feature-area groups — see + --list-tools, tools.json for the generated table and the not_exposed + reasons). Absolute out-of-range values + are REJECTED entries — never silently clamped or dropped — and any + rejected entry blocks the whole apply (all-or-nothing). Relative results + are clamped with a visible notice. A target file that is invalid JSON + or not an object aborts the run untouched. +- NEVER executes anything: no subprocess/os.system anywhere in this + package; suggested commands (scheme/wallpaper, which live outside + shell.json) are inert strings prefixed SUGGESTED_NOT_EXECUTED. +- No network at all in this module — not even loopback (unlike Layer 3). +- The parser is a pure function: no file I/O, no environment, no clock, no + randomness; identical input always yields an identical result. +""" + +from .applier import apply, restore +from .parser import parse +from .planner import PlannerError, plan +from assistant.adapters.caelestia.registry import TOOL_SPECS, ToolSpec, tool_by_name, tool_by_path + +__all__ = [ + "PlannerError", + "TOOL_SPECS", + "ToolSpec", + "apply", + "parse", + "plan", + "restore", + "tool_by_name", + "tool_by_path", +] diff --git a/plugins/caelestia-assistant/assistant/capabilities/settings/__main__.py b/plugins/caelestia-assistant/assistant/capabilities/settings/__main__.py new file mode 100755 index 0000000..1e85d78 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/capabilities/settings/__main__.py @@ -0,0 +1,11 @@ +"""CLI shim: python3 -m assistant.capabilities.settings "" [--apply] [--file PATH] + +Delegates to cli.main so the command surface stays in one place. Dry-run is +the default: without --apply this prints the validated plan and writes +nothing at all. +""" + +from .cli import main + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/plugins/caelestia-assistant/assistant/capabilities/settings/accessibility.py b/plugins/caelestia-assistant/assistant/capabilities/settings/accessibility.py new file mode 100644 index 0000000..f4a6bfb --- /dev/null +++ b/plugins/caelestia-assistant/assistant/capabilities/settings/accessibility.py @@ -0,0 +1,155 @@ +"""Accessibility checks (exp-build-5 F22): WCAG 2.x contrast auditing and +color-vision-deficiency simulation, for the what-if/preset surfaces. + +Honesty notes, up front: +- WCAG 2.x relative luminance and contrast ratio are the published W3C + formulas (WCAG 2.1 section 1.4.3/1.4.6/1.4.11 math); thresholds are the + SC levels (AA 4.5 normal / 3.0 large & UI, AAA 7.0 normal). +- The CVD matrices are the published Machado, Oliveira & Fernandes (2009) + full-severity matrices (IEEE TVCG 15(6), DOI 10.1109/TVCG.2009.113), + cross-checked from the authors' project page + (inf.ufrgs.br/~oliveira/pubs_files/CVD_Simulation/). Intermediate + severities are LINEAR BLENDS between identity (severity 0) and the + published full-severity matrix — an explicit approximation, NOT the + paper's per-severity series; it is used because every shipped number + must be traceable to a published source we can cite. The blend + preserves the paper matrices' neutral-gray axis (row sums are 1). +- Matrices apply in LINEAR RGB; the sRGB transfer function is applied + around them (IEC 61966-2-1). +- APCA is deliberately NOT implemented: its license terms were not + verified for this repository (the F22 spec says skip unless verified). + +Pure math over stdlib; no I/O; deterministic. +""" + +from __future__ import annotations + +import math +from typing import Dict, List, Sequence, Tuple + +__all__ = ["hex_to_rgb", "rgb_to_hex", "relative_luminance", + "contrast_ratio", "wcag_findings", "simulate_cvd", + "CVD_TYPES", "SIMULATE_CITATION", "WCAG_CITATION"] + +WCAG_CITATION = "W3C WCAG 2.1, SC 1.4.3/1.4.6/1.4.11 (published contrast math)" +SIMULATE_CITATION = ("Machado, Oliveira & Fernandes 2009, IEEE TVCG 15(6), " + "DOI 10.1109/TVCG.2009.113 (full-severity matrices; " + "partial severity is our documented linear blend)") + +CVD_TYPES = ("protanopia", "deuteranopia", "tritanopia") + +# Machado et al. 2009, full severity (1.0), row-major, linear RGB. +_MACHADO: Dict[str, Tuple[Tuple[float, float, float], ...]] = { + "protanopia": ( + (0.152286, 1.052583, -0.204868), + (0.114503, 0.786281, 0.099216), + (-0.003882, -0.048116, 1.051998), + ), + "deuteranopia": ( + (0.367322, 0.860646, -0.227968), + (0.280085, 0.672501, 0.047413), + (-0.011820, 0.042940, 0.968881), + ), + "tritanopia": ( + (1.255528, -0.076749, -0.178779), + (-0.078411, 0.930809, 0.147602), + (0.004733, 0.691367, 0.303900), + ), +} + + +# --------------------------------------------------------------------------- +# color spaces +# --------------------------------------------------------------------------- + +def _linearize(v: float) -> float: + """sRGB EOTF (IEC 61966-2-1).""" + return v / 12.92 if v <= 0.04045 else ((v + 0.055) / 1.055) ** 2.4 + + +def _delinearize(v: float) -> float: + return 12.92 * v if v <= 0.0031308 else 1.055 * (v ** (1.0 / 2.4)) - 0.055 + + +def _clamp01(v: float) -> float: + return 0.0 if v < 0.0 else (1.0 if v > 1.0 else v) + + +def hex_to_rgb(text: str) -> Tuple[float, float, float]: + """'#rrggbb' -> (r, g, b) in 0..1 (sRGB non-linear). Raises on garbage.""" + t = (text or "").strip().lstrip("#") + if len(t) == 3: + t = "".join(ch * 2 for ch in t) + if len(t) != 6 or any(ch not in "0123456789abcdefABCDEF" for ch in t): + raise ValueError(f"not a #rrggbb color: {text!r}") + return tuple(int(t[i:i + 2], 16) / 255.0 for i in (0, 2, 4)) # type: ignore + + +def rgb_to_hex(rgb: Sequence[float]) -> str: + return "#" + "".join( + f"{round(_clamp01(c) * 255):02x}" for c in rgb) + + +# --------------------------------------------------------------------------- +# WCAG 2.x contrast +# --------------------------------------------------------------------------- + +def relative_luminance(rgb: Sequence[float]) -> float: + r, g, b = (_linearize(_clamp01(c)) for c in rgb) + return 0.2126 * r + 0.7152 * g + 0.0722 * b + + +def contrast_ratio(fg: Sequence[float], bg: Sequence[float]) -> float: + l1, l2 = relative_luminance(fg), relative_luminance(bg) + hi, lo = max(l1, l2), min(l1, l2) + return (hi + 0.05) / (lo + 0.05) + + +def wcag_findings(fg: Sequence[float], bg: Sequence[float]) -> List[Dict[str, object]]: + """The WCAG verdicts for one fg/bg pair, with the SC citation.""" + ratio = contrast_ratio(fg, bg) + out: List[Dict[str, object]] = [] + for level, threshold, scope in ( + ("AA normal text", 4.5, "SC 1.4.3"), + ("AA large text & UI components", 3.0, "SC 1.4.3 / 1.4.11"), + ("AAA normal text", 7.0, "SC 1.4.6"), + ): + out.append({ + "level": level, "threshold": threshold, "ratio": round(ratio, 2), + "pass": ratio >= threshold, "cite": f"{WCAG_CITATION} ({scope})", + }) + return out + + +# --------------------------------------------------------------------------- +# CVD simulation (Machado 2009 endpoints, linear blend between) +# --------------------------------------------------------------------------- + +def _blend_matrix(kind: str, severity: float) -> Tuple[Tuple[float, float, float], ...]: + if kind not in _MACHADO: + raise ValueError(f"unknown CVD type {kind!r}; have {list(_MACHADO)}") + if not 0.0 <= severity <= 1.0: + raise ValueError(f"severity must be in [0, 1], got {severity}") + full = _MACHADO[kind] + if severity >= 1.0: + return full + if severity <= 0.0: + return ((1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, 1.0)) + # documented linear blend: identity -> full severity + return tuple(tuple((1.0 - severity) * i + severity * m + for i, m in zip(identity_row, machado_row)) + for identity_row, machado_row in zip( + ((1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, 1.0)), + full)) + + +def simulate_cvd(rgb: Sequence[float], kind: str = "deuteranopia", + severity: float = 1.0) -> Tuple[float, float, float]: + """Simulate one color under a color-vision deficiency. Linear RGB in + the middle, sRGB on both ends; severity 0 is the identity (property- + tested), severity 1 is exactly the published matrix.""" + m = _blend_matrix(kind, severity) + lin = [_linearize(_clamp01(c)) for c in rgb] + out = tuple(_clamp01(sum(m[i][j] * lin[j] for j in range(3))) + for i in range(3)) + return (_delinearize(out[0]), _delinearize(out[1]), _delinearize(out[2])) diff --git a/plugins/caelestia-assistant/assistant/capabilities/settings/applier.py b/plugins/caelestia-assistant/assistant/capabilities/settings/applier.py new file mode 100755 index 0000000..08ae2d8 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/capabilities/settings/applier.py @@ -0,0 +1,299 @@ +"""Applier for the settings layer (the settings design notes (see module docstrings) §5): plan -> written file. + +This is the ONLY module in the whole assistant that writes anything, and it +writes ONLY when the caller passes ``write=True`` (the CLI's ``--apply`` +gate — the equivalent of #120's confirmation step). Its write scope is +exactly four paths, all siblings of the explicit target file: + +- the target file itself (via a transient ``.assistant-tmp`` + atomic + ``os.replace``, i.e. POSIX rename(2)); +- ``.assistant-backup`` — the single-slot one-level undo (a + zero-byte backup means "the target did not exist before the apply"); +- ``.assistant-tmp`` — removed after the rename; best-effort + unlinked on any failure; +- ``.assistant-history.json`` — the bounded undo history + (history.py owns the schema; the applier appends after each successful + write; oldest entries are evicted beyond history.MAX_ENTRIES). + +NEVER: any other path, any parent-directory creation (a missing config +directory is an error, not a mkdir), any command execution (suggested +commands are inert ``SUGGESTED_NOT_EXECUTED:`` strings), any network, any +monitor-override file. Dry-run (the default) writes nothing at all. +""" + +from __future__ import annotations + +import json +import os +from pathlib import Path +from typing import Any, Dict, List, Optional, Union + +from assistant.adapters.caelestia.registry import tool_by_path + +BACKUP_SUFFIX = ".assistant-backup" +TMP_SUFFIX = ".assistant-tmp" + + +class ApplierError(RuntimeError): + """Raised when a write or restore cannot be completed safely.""" + + +def _resolved(file_path: Union[str, Path]) -> Path: + """§5.3: resolve symlinks so the rename replaces the real file and the + backup/tmp siblings sit next to the *resolved* file.""" + return Path(os.path.realpath(str(file_path))) + + +def _sibling(target: Path, suffix: str) -> Path: + return target.with_name(target.name + suffix) + + +def _parse_current(target: Path) -> Dict[str, Any]: + """Parse the current target file for merging. Missing -> {} (the file + will be created on apply). Invalid JSON / non-object -> ApplierError, + with nothing written.""" + if not target.exists(): + return {} + try: + raw = target.read_bytes() + current = json.loads(raw.decode("utf-8")) + except (OSError, UnicodeDecodeError, ValueError) as exc: + raise ApplierError( + f"target file {target} cannot be parsed for merging ({exc}); nothing was written" + ) from exc + if not isinstance(current, dict): + raise ApplierError( + f"target file {target} is valid JSON but not an object; nothing was written" + ) + return current + + +def _deep_set(data: Dict[str, Any], dotted: str, value: Any) -> None: + """Set one whitelisted registry leaf, creating intermediate dicts along + the registry path only (§5.3 step 3). Every other key is preserved.""" + segments = dotted.split(".") + node: Dict[str, Any] = data + for segment in segments[:-1]: + nxt = node.get(segment) + if nxt is None: + child: Dict[str, Any] = {} + node[segment] = child + node = child + elif isinstance(nxt, dict): + node = nxt + else: + raise ApplierError( + f"cannot merge into {dotted}: '{segment}' exists but is not an object; " + "nothing was written" + ) + node[segments[-1]] = value + + +def _deep_unset(data: Dict[str, Any], dotted: str) -> None: + """Remove one leaf and prune now-empty parents along its path (the + inverse of _deep_set: an apply that CREATED a key is undone by making + the key absent again, so ConfigObject falls back to the default).""" + segments = dotted.split(".") + chain: List[Dict[str, Any]] = [data] + for segment in segments[:-1]: + nxt = chain[-1].get(segment) + if not isinstance(nxt, dict): + return # absent already — nothing to remove + chain.append(nxt) + chain[-1].pop(segments[-1], None) + for depth in range(len(chain) - 1, 0, -1): + parent = chain[depth - 1] + child = chain[depth] + if child: + break + parent.pop(segments[depth - 1], None) + + +def apply(plan: Dict[str, Any], file_path: Union[str, Path], write: bool = False, + label: Optional[str] = None, record_history: bool = True, + scheme: Optional[Dict[str, str]] = None) -> Dict[str, Any]: + """Apply a validated plan to the target file (§5.3). + + Dry-run (default): writes NOTHING — no target, no backup, no tmp — and + returns what would happen. ``write=True`` performs the gated write: + backup first, merge only whitelisted registry leaf paths into the + parsed current JSON, serialize with 4-space indent + trailing newline, + write ``.assistant-tmp`` then atomic ``os.replace`` onto the target. + + Before any byte is written, the POST-apply state runs through the + sanity simulator (sanity.check): a projected WCAG-contrast refusal + (only with scheme context) raises ApplierError with nothing written — + target, backup and history stay byte-identical — and tap-target + warnings ride the result. This runs for single-setting applies too + (they skip the multi-change preview, so this is their only invariant + gate). The write=True gate semantics are unchanged. + + A successful write also appends to the bounded undo history + at ``.assistant-history.json`` (history.MAX_ENTRIES entries, + oldest evicted first) unless ``record_history=False`` (used by + history.undo so an undo is not itself recorded). ``label`` is the + human-readable request the entry stores. ``scheme`` optionally supplies + {"role": "#hex"} colors for the projected-contrast check; without it + the contrast check honestly reports itself skipped. + """ + target = _resolved(file_path) + entries: List[Dict[str, Any]] = plan.get("entries", []) + applicable = [e for e in entries if not e.get("error") and not e.get("no_op")] + + if plan.get("apply_blocked") and write: + # §4.5: all-or-nothing — a blocked plan is never written. + raise ApplierError( + "apply refused: the plan contains rejected or type-mismatched entries; " + "nothing was written" + ) + + if not applicable: + # §5.3 step 1: every entry is a no-op -> no pointless backup churn. + return { + "written": False, + "no_changes": True, + "message": "no changes needed; nothing written", + } + + if not write: + return { + "written": False, + "message": ( + f"dry-run: {len(applicable)} change(s) would be written to {target} " + "with --apply; nothing is written now" + ), + } + + # The merge target: the parsed CURRENT JSON (fresh read at write time), + # so every other key survives the merge untouched. + current = _parse_current(target) + + # Pre-write sanity simulator (issue #120 Phase 1.2): check the POST-apply + # state BEFORE the backup slot is touched, so a refusal leaves the + # target, its backup and the undo history byte-identical. + from . import sanity as _sanity + projected = _sanity.project(current, applicable) + verdict = _sanity.check(projected, scheme=scheme) + if verdict["refusals"]: + detail = "; ".join(r["message"] for r in verdict["refusals"]) + raise ApplierError( + f"sanity check refused the apply: {detail}; nothing was written" + ) + + if not target.parent.is_dir(): + # §5: never create parent directories — a missing config directory + # is an error, not a mkdir. + raise ApplierError( + f"target directory {target.parent} does not exist; not creating it" + ) + + # Capture the OLD values for the undo history entry before + # the merge overwrites them (absent key -> None -> "(unset)"). + olds: List[Dict[str, Any]] = [] + for entry in applicable: + node: Any = current + for segment in str(entry.get("path", "")).split("."): + if not isinstance(node, dict) or segment not in node: + node = None + break + node = node[segment] + olds.append({"path": entry.get("path"), "old": node, + "new": entry.get("new")}) + + # §5.3 step 2 — backup (single slot; an existing backup is overwritten). + backup = _sibling(target, BACKUP_SUFFIX) + if target.exists(): + backup.write_bytes(target.read_bytes()) + else: + # Zero-byte marker: the target did not exist before this apply, so + # --restore returns to the no-file state (sound because the planner + # aborts on any existing-but-invalid file). + backup.write_bytes(b"") + + # §5.3 step 3 — merge + serialize. + try: + for entry in applicable: + spec = tool_by_path(str(entry.get("path", ""))) + if spec is None: + raise ApplierError( + f"refusing to write non-registry path {entry.get('path')!r}; " + "nothing was written" + ) + if entry.get("unset"): + # Undo of a key the apply CREATED: restore absence. + _deep_unset(current, spec.path) + else: + _deep_set(current, spec.path, entry["new"]) + serialized = json.dumps(current, indent=4) + "\n" + except ApplierError: + raise + except (TypeError, ValueError) as exc: + raise ApplierError(f"serialization failed: {exc}; nothing was written") from exc + + # §5.3 step 4 — atomic replace via the tmp sibling. + tmp = _sibling(target, TMP_SUFFIX) + try: + tmp.write_text(serialized, encoding="utf-8") + os.replace(tmp, target) + except OSError as exc: + try: + tmp.unlink() + except OSError: + pass + raise ApplierError( + f"write to {target} failed: {exc}; target and backup left untouched" + ) from exc + + # Bounded undo history (after the write succeeded, so a + # failed write leaves no phantom entry). + history_note = "" + if record_history: + from . import history as _history + entry = _history.record(file_path, label or "", olds) + history_note = f"; undo entry #{entry['id']}" + + return { + "written": True, + "message": f"wrote {len(applicable)} change(s) to {target}; backup at {backup}{history_note}", + "backup": str(backup), + "changes": len(applicable), + "sanity": {"warnings": verdict["warnings"], "notes": verdict["notes"]}, + } + + +def restore(file_path: Union[str, Path]) -> Dict[str, Any]: + """§5.4: one-level undo. Requires ``.assistant-backup``; a + zero-byte backup deletes the target (restores the no-file state); + otherwise the backup atomically replaces the target and the single + slot is consumed.""" + target = _resolved(file_path) + backup = _sibling(target, BACKUP_SUFFIX) + if not backup.exists(): + raise ApplierError(f"no backup to restore ({backup} does not exist)") + + if backup.stat().st_size == 0: + removed = target.exists() + if removed: + try: + os.remove(target) + except OSError as exc: + raise ApplierError(f"cannot delete {target}: {exc}") from exc + try: + backup.unlink() + except OSError as exc: + raise ApplierError(f"cannot consume the backup slot {backup}: {exc}") from exc + message = ( + f"deleted {target} (restored the no-file state); backup slot consumed" + if removed + else f"{target} was already absent; backup slot consumed" + ) + return {"restored": True, "message": message} + + try: + os.replace(backup, target) + except OSError as exc: + raise ApplierError(f"cannot restore {target} from {backup}: {exc}") from exc + return { + "restored": True, + "message": f"restored {target} from its backup; the single backup slot is consumed", + } diff --git a/plugins/caelestia-assistant/assistant/capabilities/settings/build_registry.py b/plugins/caelestia-assistant/assistant/capabilities/settings/build_registry.py new file mode 100755 index 0000000..1c184e1 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/capabilities/settings/build_registry.py @@ -0,0 +1,361 @@ +#!/usr/bin/env python3 +"""Build assistant/settings/tools.json from the repo's real headers. + +The generated-registry pipeline. The ONLY settings-layer piece that reads the +caelestia checkout: runs the stdlib header walker (enumerate.py), applies +the safety classification (curations.py) plus the transcribed shipped +control table (ui_ranges_data.py), and emits the frozen tool table that +registry.py loads at runtime. Deterministic; regenerating against a moved +upstream and diffing is the drift guard (a unittest does that). +""" +from __future__ import annotations + +import argparse +import json +import os +import re +import sys +from pathlib import Path +from typing import Any, Dict, List, Optional, Tuple + +from . import curations +from .enumerate import enumerate_leaves +from .ui_ranges_data import UI_RANGES + +REPO_COMMIT = "70ee7da115fde9012e28e393c73d274f55bd2dd7" +_ENUM_NOTE = re.compile(r"enum ([A-Za-z0-9_]+)\s*:\s*([A-Za-z0-9_|]+)") + + +def parse_default(raw: str, cpp_type: str) -> Tuple[Optional[Any], Optional[str]]: + """C++ default literal -> JSON value, or (None, reason).""" + raw = raw.strip() + if raw == "{}": + if cpp_type == "QString": + return "", None + return None, f"untyped brace default {raw!r}" + m = re.fullmatch(r'u"([^"]*)"_s', raw) + if m: + return m.group(1), None + m = re.fullmatch(r'QStringLiteral\("([^"]*)"\)', raw) + if m: + return m.group(1), None + if raw == "QString()": + return "", None + if raw == "true": + return True, None + if raw == "false": + return False, None + if re.fullmatch(r"-?\d+", raw): + return (float(raw) if cpp_type in ("qreal", "double", "float") else int(raw)), None + if re.fullmatch(r"-?\d+\.\d*", raw) or re.fullmatch(r"\.\d+", raw): + return float(raw), None + # Enum-typed default: ClockFormat::Auto -> "Auto" (the metaenum key IS + # the serialized form; EnumCodec::encode writes the key, codecs.cpp:238-240) + m = re.fullmatch(r"([A-Za-z0-9_]+)::([A-Za-z0-9_]+)", raw) + if m and "::" in cpp_type: + return m.group(2), None + return None, f"non-representable C++ default literal {raw!r}" + + +def enum_members_from_note(note: str) -> Optional[List[str]]: + """'enum ClockFormat: Auto|TwelveHour|TwentyFourHour' -> members.""" + if not note: + return None + m = _ENUM_NOTE.search(note) + return m.group(2).split("|") if m else None + + +def _preset_value_ok(t: Dict[str, Any], value: Any) -> Tuple[bool, str]: + """Validate one preset call against its tool spec (build-time gate).""" + kind = t["kind"] + if kind == "bool": + return (True, "") if isinstance(value, bool) else (False, "bool tool needs true/false") + if kind == "enum": + return (True, "") if value in (t["enum"] or []) else (False, f"not one of {t['enum']}") + if kind == "string": + ok = isinstance(value, str) and 0 < len(value) <= int(t.get("string_max_len") or 64) + return (True, "") if ok else (False, "non-empty string within max length required") + if not isinstance(value, (int, float)) or isinstance(value, bool): + return False, "numeric tool needs a number" + if t["minimum"] is not None and value < t["minimum"]: + return False, f"below minimum {t['minimum']}" + if t["maximum"] is not None and value > t["maximum"]: + return False, f"above maximum {t['maximum']}" + if kind == "int" and int(value) != value: + return False, "int tool needs an integer" + return True, "" + + +def build(repo_root: str) -> Dict[str, Any]: + leaves = enumerate_leaves(repo_root) + by_path = {r["path"]: r for r in leaves} + tools: List[Dict[str, Any]] = [] + not_exposed: List[Dict[str, Any]] = [] + stats: Dict[str, Any] = {"ui_rows_not_leaves": [], "excluded_by_rule": {}} + + def exclude(path: str, tag: str, reason: str) -> None: + not_exposed.append({"path": path, "reason": f"[{tag}] {reason}"}) + stats["excluded_by_rule"][tag] = stats["excluded_by_rule"].get(tag, 0) + 1 + + scalar_rows = [r for r in leaves if r["kind"] == "scalar"] + for row in sorted(scalar_rows, key=lambda r: r["path"]): + path = row["path"] + excl = curations.exclusion_for(row) + if excl is not None: + name, reason = excl + exclude(path, name, reason) + continue + ui = UI_RANGES.get(path) + if ui is None: + exclude(path, "no-shipped-control", + "no Nexus control touches this leaf; not exposed without " + "a UI-grounded citation") + continue + control = str(ui.get("control", "")) + if not curations.control_is_scalar(control): + exclude(path, "complex-control", + f"the shipped control is {control!r}, not a scalar setter") + continue + cpp_type = row["type"] + default, bad = parse_default(row["default"], cpp_type) + if bad is not None: + exclude(path, "default", bad) + continue + + enum_vals: Optional[List[str]] = None + int_enum: Optional[List[int]] = None + int_range = None + extra_fixup_cite: List[List[str]] = [] + cpp_members = enum_members_from_note(row.get("notes", "")) + is_enum_typed = cpp_type != "QString" and cpp_members is not None + + if path in curations.ENUM_FIXUPS: + vals, cite = curations.ENUM_FIXUPS[path] + enum_vals = vals + kind = "enum" + extra_fixup_cite = [list(cite)] + elif is_enum_typed: + # C++ enum declaration wins over any UI annotation: the + # metaenum keys ARE the serialized form (codecs.cpp:238-240). + enum_vals = cpp_members + kind = "enum" + extra_fixup_cite = [] + elif control.startswith("SelectRow"): + ui_list = ui.get("enum") + vals = [str(v) for v in ui_list] if isinstance(ui_list, list) else [] + # strip parenthetical annotations: "Stretch (Image...)" -> "Stretch" + vals = [v.split(" (")[0].strip() for v in vals] + # numeric-coded rows: "0=KDE Grid" / "-1 Random" / "5 attempts" + num_prefix = [re.match(r"^(-?\d+)", v) for v in vals] + if all(m is not None for m in num_prefix) and vals: + ints = [int(m.group(1)) for m in num_prefix] # type: ignore[union-attr] + if ints == list(range(min(ints), max(ints) + 1)): + kind = "int" + int_range = (min(ints), max(ints)) + enum_vals = None + else: + kind = "enum" + int_enum = sorted(set(ints)) + enum_vals = [str(i) for i in int_enum] + extra_fixup_cite = [] + elif vals and all(v and " " not in v and "+" not in v for v in vals): + enum_vals = vals + kind = "enum" + extra_fixup_cite = [] + else: + exclude(path, "dynamic-enum", + "the SelectRow's value list is dynamic, numeric-coded " + "without per-value ids, or not a frozen enumeration") + continue + elif control.startswith("FontCard"): + kind = "string" + extra_fixup_cite = [] + else: + kind = {"bool": "bool", "int": "int", "qreal": "float", + "double": "float", "float": "float"}.get(cpp_type) + if cpp_type == "QString" and kind is None: + kind = "string" + extra_fixup_cite = [] + if kind is None: + exclude(path, "type", f"unhandled C++ type {cpp_type!r}") + continue + if cpp_type == "QString" and control.startswith(("StepperRow", "DoubleStepperRow")): + exclude(path, "string-stepper", + "the shipped stepper stores a transformed string " + "(e.g. HH:MM); not a passthrough scalar") + continue + if cpp_type == "QString" and kind == "string" and not control.startswith("FontCard"): + exclude(path, "free-string", + "free-form string with no frozen enumeration") + continue + + spec: Dict[str, Any] = { + "name": curations.tool_name_for(path), + "path": path, + "group": curations.group_for(path), + "kind": kind, + "default": default, + "minimum": None, "maximum": None, "step": None, "enum": None, + "string_max_len": None, + # enumerate_leaves returns a bool; the TSV form spelled it + # "yes"/"no" — accept both so neither shape can silently + # flatten the flag again (2-a-2 audit: it did, for every tool then shipped). + "global_only": row["global_only"] is True or row["global_only"] == "yes", + "nouns": [], + "citations": [], + } + if kind == "enum": + if int_enum is not None: + spec["enum"] = int_enum # enum of ints (numeric-coded select) + else: + spec["enum"] = enum_vals + elif kind == "string": + spec["string_max_len"] = 64 + else: + ov = curations.CORE_OVERRIDES.get(path) + if ov is not None: + spec["minimum"] = ov.get("minimum") + spec["maximum"] = ov.get("maximum") + spec["step"] = ov.get("step") + elif path in curations.RANGE_FIXUPS: + # Transformed stepper: adopt the range in the STORED unit + # (see curations.RANGE_FIXUPS for the per-row evidence). + fix = curations.RANGE_FIXUPS[path] + spec["minimum"] = fix.get("minimum") + spec["maximum"] = fix.get("maximum") + spec["step"] = fix.get("step") + if "cite" in fix: + extra_fixup_cite.append(list(fix["cite"])) # type: ignore[arg-type] + elif kind == "int" and int_range is not None: + spec["minimum"], spec["maximum"] = int_range + spec["step"] = 1 + else: + spec["minimum"] = ui.get("min") + spec["maximum"] = ui.get("max") + spec["step"] = ui.get("step") + if kind == "int": + for k in ("minimum", "maximum", "step"): + if spec[k] is not None: + spec[k] = int(spec[k]) + core = curations.CORE_TOOLS.get(path) + if core is not None: + spec["name"] = core["name"] + spec["nouns"] = list(core.get("nouns", [])) + for k in ("minimum", "maximum", "step", "enum"): + if k in core: + spec[k] = list(core[k]) if k == "enum" else core[k] + + header_rel = f"shell/plugin/src/Caelestia/Config/{row['header']}" + cites = [ + [f"{header_rel}:{row['line']}", + f"CONFIG declaration: {cpp_type} {path.rsplit('.', 1)[-1]} = {row['default']}"], + [f"{ui['file']}:{ui['line']}", + f"shipped Nexus control ({control.split('(')[0].strip()})"], + ] + cites.extend([list(c) for c in curations.extra_citations_for(path)]) + cites.extend(extra_fixup_cite) + spec["citations"] = cites + tools.append(spec) + + leaf_paths = set(by_path) + stats["ui_rows_not_leaves"] = sorted(k for k in UI_RANGES if k not in leaf_paths) + # Two-pass naming: short names first; colliding basenames get the full + # dotted path camel-cased (area prefix included), e.g. setSessionVimKeybinds. + names = [t["name"] for t in tools] + dupes = {n for n in names if names.count(n) > 1} + if dupes: + for t in tools: + if t["name"] in dupes and t["path"] not in curations.CORE_TOOLS: + parts = [p for p in t["path"].split(".") if p] + t["name"] = "set" + "".join(p[:1].upper() + p[1:] for p in parts) + names = [t["name"] for t in tools] + dupes = {n for n in names if names.count(n) > 1} + if dupes: + raise SystemExit(f"tool name collisions: {sorted(dupes)}") + group_order = {g: i for i, g in enumerate(curations.GROUPS)} + tools.sort(key=lambda t: (group_order.get(t["group"], 99), t["name"])) + counts: Dict[str, int] = {} + for t in tools: + counts[t["group"]] = counts.get(t["group"], 0) + 1 + + # ---- presets: bundles of validated calls (fail the build if invalid) -- + by_name = {t["name"]: t for t in tools} + presets_out: List[Dict[str, Any]] = [] + for p in curations.PRESETS: + calls_out = [] + for tool_name, value in p["calls"]: # type: ignore[index] + t = by_name.get(str(tool_name)) + if t is None: + raise SystemExit(f"preset {p['name']!r} references unknown tool {tool_name!r}") + ok, why = _preset_value_ok(t, value) + if not ok: + raise SystemExit(f"preset {p['name']!r} value {value!r} for {tool_name}: {why}") + calls_out.append({"tool": str(tool_name), "value": value}) + presets_out.append({ + "name": p["name"], "label": p["label"], + "description": p["description"], "calls": calls_out, + }) + + explain_out = [ + { + "path": r["path"], "when": r["when"], "answer": r["answer"], + "cites": list(r["cites"]), # type: ignore[arg-type] + } + for r in curations.EXPLAIN_RULES + ] + + return { + "meta": { + "generator": "assistant.capabilities.settings.build_registry", + "repo_commit": REPO_COMMIT, + "notes": ( + "Validation ranges/enums adopted exactly from the shipped " + "Nexus controls (ui_ranges_data.py) and the C++ enum " + "declarations; upstream declares no numeric bounds in the " + "settings schema (type-only hook). not_exposed records every " + "scalar leaf without a tool, with its reason." + ), + "tool_count": len(tools), + "group_counts": dict(sorted(counts.items(), + key=lambda kv: group_order.get(kv[0], 99))), + "not_exposed_count": len(not_exposed), + "excluded_by_rule": stats["excluded_by_rule"], + }, + "tools": tools, + "not_exposed": sorted(not_exposed, key=lambda e: e["path"]), + "presets": presets_out, + "explain_rules": explain_out, + } + + +def find_repo_root(start: Path) -> Optional[Path]: + for cand in [start, *start.parents]: + if (cand / "shell" / "plugin" / "src" / "Caelestia" / "Config").is_dir(): + return cand + return None + + +def main(argv: Optional[List[str]] = None) -> int: + ap = argparse.ArgumentParser(description="build tools.json from a caelestia checkout") + ap.add_argument("--repo-root", default=None, help="caelestia checkout root") + ap.add_argument("--output", default=None, help="output path (default: tools.json beside this module)") + args = ap.parse_args(argv) + root = Path(args.repo_root) if args.repo_root else find_repo_root(Path(__file__).resolve().parent) + if root is None or not root.exists(): + print("error: cannot locate a caelestia checkout " + "(need shell/plugin/src/Caelestia/Config under the repo root)", file=sys.stderr) + return 2 + data = build(str(root)) + out = Path(args.output) if args.output else Path(__file__).resolve().parent / "tools.json" + tmp = out.with_name(out.name + ".tmp") + tmp.write_text(json.dumps(data, indent=2, ensure_ascii=False) + "\n", encoding="utf-8") + os.replace(tmp, out) + m = data["meta"] + print(f"wrote {out}") + print(f" tools: {m['tool_count']} by group: {m['group_counts']}") + print(f" not exposed: {m['not_exposed_count']} ({m['excluded_by_rule']})") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/plugins/caelestia-assistant/assistant/capabilities/settings/catalog.py b/plugins/caelestia-assistant/assistant/capabilities/settings/catalog.py new file mode 100644 index 0000000..a13277f --- /dev/null +++ b/plugins/caelestia-assistant/assistant/capabilities/settings/catalog.py @@ -0,0 +1,183 @@ +"""assistant.capabilities.settings.catalog — generated community docs (F23, +exponential-build-5). + +The registry is generated from the upstream checkout (gen_adapter), and +anything HAND-written about 272 tools drifts the moment upstream moves +(the A0 recon found exactly that: five tools removed upstream while +prose still described them). This module extends the gen_adapter +pattern — GENERATE, never hand-write, verify byte-identity — to the two +community-facing artifacts that list the tool surface: + +- the tool catalog (every registry tool — name, config path, kind, + range/enum/default, which presets set it — with the registry's own + counts pinned), generated on demand by ``settings --gen-catalog``; +- ``scripts/completions/caelestia-assist.bash``: a bash completion for + the settings layer's flags, preset names, and tool names (committed; + ``--verify`` re-checks byte-identity so a registry change that + outdates it FAILS THE BUILD instead of silently drifting). + +Pure generation: no I/O in the pure functions; the CLI writes only the +declared path (or verifies). +""" + +from __future__ import annotations + +from pathlib import Path +from typing import Any, Dict, List, Optional, Tuple + +from . import presets as presets_mod +from assistant.adapters.caelestia.registry import TOOL_COUNT, TOOL_SPECS + +__all__ = ["catalog_markdown", "completions_bash", "ARTIFACTS", + "generate", "verify"] + +# The committed artifacts, relative to the repo root (the CLI resolves +# the root as the parent of the assistant package directory). +ARTIFACTS: Tuple[Tuple[str, str], ...] = ( + ("scripts/completions/caelestia-assist.bash", "completions_bash"), +) + +_SETTINGS_FLAGS = [ + "--apply", "--restore", "--file", "--json", "--list-tools", "--group", + "--tool", "--call", "--explain", "--history", "--prefer", "--threeway", + "--what-if", "--why-chain", "--counterfactual", "--accessibility-check", + "--cvd", "--severity", "--recommend", "--rank", "--undo", "--undo-id", + "--preset", "--list-presets", "--confirm", "--lint", "--audit-env", + "--wallpaper-palette", "--wizard", "--answers", "--macro", "--macro-save", + "--macro-list", "--macro-delete", "--from-id", "--profile", + "--profile-save", "--also", "--profile-list", "--profile-show", + "--profile-diff", "--profile-delete", "--profile-whatif", "--env-save", + "--env-list", "--env-show", "--env-diff", "--env-restore", + "--env-delete", "--env-export", "--env-import", "--to", "--as", + "--monitor", "--monitors", +] + + +def _range_text(spec) -> str: + if spec.enum: + return "`" + " | ".join(str(v) for v in spec.enum) + "`" + parts = [] + if spec.minimum is not None: + parts.append(f"min {spec.minimum}") + if spec.maximum is not None: + parts.append(f"max {spec.maximum}") + return ", ".join(parts) if parts else "—" + + +def _default_text(spec) -> str: + if spec.default is not None: + return f"`{spec.default}`" + return "—" + + +def catalog_markdown() -> str: + """The full tool catalog as markdown (pure; deterministic).""" + preset_touch: Dict[str, List[str]] = {} + for preset in presets_mod.presets(): + for call in preset["calls"]: + preset_touch.setdefault(call[0], []).append(preset["name"]) + group_tools: Dict[str, List[Any]] = {} + for spec in TOOL_SPECS: + group_tools.setdefault(spec.group, []).append(spec) + + lines: List[str] = [ + "# Tool catalog", + "", + "", + "", + f"Registry version: generated from the caelestia-kde checkout this", + f"assistant pins; **{TOOL_COUNT} tools** in {len(group_tools)} " + f"groups, {len(presets_mod.presets())} presets.", + "", + "A tool is a validated setter for one shell.json path. Every value", + "passes the tool's own validation before any plan exists; nothing", + "here is ever executed by the assistant itself — suggested changes", + "ride the preview -> consent -> applier gate.", + "", + ] + for group in sorted(group_tools): + lines.append(f"## {group} ({len(group_tools[group])})") + lines.append("") + lines.append("| tool | path | kind | range/enum | default | presets |") + lines.append("|---|---|---|---|---|---|") + for spec in sorted(group_tools[group], key=lambda s: s.name): + presets = ", ".join(sorted(preset_touch.get(spec.name, []))) + lines.append( + f"| `{spec.name}` | `{spec.path}` | {spec.kind} | " + f"{_range_text(spec)} | {_default_text(spec)} | " + f"{presets or '—'} |") + lines.append("") + return "\n".join(lines) + "\n" + + +def completions_bash() -> str: + """bash completion for the settings layer (pure; deterministic).""" + words = " ".join(sorted(_SETTINGS_FLAGS)) + preset_words = " ".join(sorted(p["name"] for p in presets_mod.presets())) + tool_words = " ".join(sorted(spec.name for spec in TOOL_SPECS)) + return ( + "# caelestia-assist settings — bash completion (GENERATED by\n" + "# assistant.capabilities.settings.catalog; verify with --gen-catalog --verify)\n" + "# shellcheck shell=bash\n" + "_caelestia_assist_settings() {\n" + " local cur prev\n" + " cur=\"${COMP_WORDS[COMP_CWORD]}\"\n" + " case \"$cur\" in\n" + " -*)\n" + f" COMPREPLY=( $(compgen -W \"{words}\" -- \"$cur\") ) ;;\n" + " *)\n" + " local prev2=\"${COMP_WORDS[COMP_CWORD-1]}\"\n" + " case \"$prev2\" in\n" + " --preset|--recommend|--tool|--explain)\n" + f" COMPREPLY=( $(compgen -W \"{tool_words}\" -- \"$cur\") ) ;;\n" + " --profile|--macro)\n" + " COMPREPLY=( ) ;; # user-defined names: not enumerable\n" + " *)\n" + f" COMPREPLY=( $(compgen -W \"{preset_words}\" -- \"$cur\") ) ;;\n" + " esac ;;\n" + " esac\n" + "}\n" + "complete -F _caelestia_assist_settings -o default " + "caelestia-assist\n" + "complete -F _caelestia_assist_settings -o default " + "python3-m-assistant.capabilities.settings 2>/dev/null || true\n" + ) + + +def generate(root: Optional[Path] = None) -> Dict[str, str]: + """Write the committed artifacts. Returns {path: bytes-written}.""" + root = root or _default_root() + written: Dict[str, str] = {} + for rel, fn_name in ARTIFACTS: + content = globals()[fn_name]() + path = root / rel + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(content, encoding="utf-8") + written[rel] = str(path) + return written + + +def verify(root: Optional[Path] = None) -> List[str]: + """Byte-identity check of the committed artifacts against a fresh + generation. Returns the list of mismatching paths (empty = all + current).""" + root = root or _default_root() + problems: List[str] = [] + for rel, fn_name in ARTIFACTS: + expected = globals()[fn_name]() + path = root / rel + try: + actual = path.read_text(encoding="utf-8") + except OSError: + problems.append(f"{rel}: MISSING (run --gen-catalog)") + continue + if actual != expected: + problems.append(f"{rel}: STALE (registry moved past the " + f"committed artifact; run --gen-catalog)") + return problems + + +def _default_root() -> Path: + return Path(__file__).resolve().parents[3] diff --git a/plugins/caelestia-assistant/assistant/capabilities/settings/causal.py b/plugins/caelestia-assistant/assistant/capabilities/settings/causal.py new file mode 100644 index 0000000..6c1d641 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/capabilities/settings/causal.py @@ -0,0 +1,307 @@ +"""assistant.capabilities.settings.causal — causal attribution over the curated DAG +(exponential-build-5 F14). + +Two questions, both answered ONLY from the shipped, citation-backed +consequences table plus the live state the caller supplies read-only: + + * ``why_chain(path, current)`` — BACKWARD: which armed interactions + explain the current value of ``path``? Multi-hop (bounded, cycle- + safe), every hop carrying the edge's citation, confidence and + arming condition. A trigger value no curated edge explains + terminates the chain as DIRECT ("set directly — see undo history"), + never as a guess. An edge whose ``requires`` live value is missing + is reported UNEVALUATED — the abstention the design demands. + + * ``counterfactual(tool, value, current)`` — FORWARD: "if I set X, + what happens?" — the existing ``consequences.project`` projection + (reuse, not re-implementation) EXTENDED with the honesty the what-if + view never had: every curated edge that COULD have fired but could + not be evaluated (its ``requires`` path missing from the live + state) is listed as UNEVALUATED instead of silently staying quiet. + +The honesty rules are the table's own: the causal universe is EXACTLY +the curated edges (bounded, growable by reviewed diffs); chains are +explanations OF CITED CODE, not causes in nature; and every unknown +needed value is an abstention, never a default. +""" + +from __future__ import annotations + +from typing import Any, Dict, List, Optional + +from . import consequences as _cons +from assistant.adapters.caelestia.registry import tool_by_name, tool_by_path + +__all__ = ["why_chain", "counterfactual", "unevaluated_edges", + "render_chain", "render_counterfactual", "MAX_CHAIN_DEPTH"] + +MAX_CHAIN_DEPTH = 4 # bounded walk; deeper chains are refused, not faked + + +def _live(current: Optional[Dict[str, Any]], path: str) -> Any: + """Read a dotted path from the NESTED live dict (None = unknown).""" + if not isinstance(current, dict): + return None + node: Any = current + for piece in path.split("."): + if isinstance(node, dict): + node = node.get(piece) + else: + return None + return node + + +def _is_number(v: Any) -> bool: + return isinstance(v, (int, float)) and not isinstance(v, bool) + + +def _edge_state(edge: Dict[str, Any], current: Optional[Dict[str, Any]] + ) -> Dict[str, Any]: + """Classify one edge against live state for BACKWARD explanation. + + Returns {"status": ARMED | NOT_ARMED | UNEVALUATED, ...}: + ARMED — the trigger's live value satisfies the when-condition + AND any requires precondition holds AND (when the + edge sets a value) the effect's live value matches + what the edge induces — this edge genuinely explains + the effect's current value. + NOT_ARMED — a known value contradicts the condition. + UNEVALUATED — a needed live value is missing (the abstention). + """ + when = edge.get("when") or {} + trigger = edge["trigger_path"] + live_trigger = _live(current, trigger) + reason_unknown: Optional[str] = None + if "op_is" in when: + if live_trigger is None: + reason_unknown = f"live value of {trigger} unknown" + elif live_trigger is not when["op_is"]: + return {"status": "NOT_ARMED"} + if "op_below" in when and reason_unknown is None: + if live_trigger is None: + reason_unknown = f"live value of {trigger} unknown" + elif not (_is_number(live_trigger) and live_trigger < when["op_below"]): + return {"status": "NOT_ARMED"} + requires = when.get("requires") + if requires: + live_req = _live(current, requires["path"]) + if live_req is None: + reason_unknown = (reason_unknown or + f"live value of {requires['path']} unknown") + elif live_req != requires.get("equals"): + return {"status": "NOT_ARMED"} + if reason_unknown is not None: + return {"status": "UNEVALUATED", "reason": reason_unknown} + # the edge's induced value must match the effect's live value, else + # it explains a PAST state, not the current one + effect_value = edge.get("effect_value") + if effect_value is not None: + live_effect = _live(current, edge["effect_path"]) + if live_effect is None: + return {"status": "UNEVALUATED", + "reason": f"live value of {edge['effect_path']} unknown"} + if live_effect != effect_value: + return {"status": "NOT_ARMED"} + return {"status": "ARMED"} + + +def _hop(edge: Dict[str, Any]) -> Dict[str, Any]: + return { + "from": edge["trigger_path"], + "edge": edge.get("id"), + "effect_path": edge["effect_path"], + "effect": edge.get("effect"), + "confidence": edge.get("confidence"), + "citation": edge.get("citation"), + "claimed_content": edge.get("claimed_content"), + "when": _describe(edge), + } + + +def _describe(edge: Dict[str, Any]) -> str: + when = edge.get("when") or {} + parts: List[str] = [] + if "op_is" in when: + parts.append(f"{edge['trigger_path']} is {when['op_is']!r}") + if "op_below" in when: + parts.append(f"{edge['trigger_path']} < {when['op_below']!r}") + if "requires" in when: + r = when["requires"] + parts.append(f"{r['path']} == {r.get('equals')!r}") + return " and ".join(parts) if parts else "unconditional" + + +def why_chain(path: str, current: Optional[Dict[str, Any]] = None, + max_depth: int = MAX_CHAIN_DEPTH) -> Dict[str, Any]: + """Backward causal chain for the current value of ``path``. + + ``current`` is the NESTED live state (planner._read_current's shape). + Verdicts: OK (>= 1 chain) / NO_CURATED_CAUSE (the value is what it + is without any armed curated interaction — set directly) / + UNKNOWN_PATH / DEPTH_EXCEEDED refuses rather than truncating a live + chain silently.""" + spec = tool_by_path(path) or tool_by_name(path) + if spec is not None: + path = spec.path + if not any(e["effect_path"] == path or e["trigger_path"] == path + for e in _cons.EDGES): + if spec is None: + return {"verdict": "UNKNOWN_PATH", "path": path} + return {"verdict": "NO_CURATED_CAUSE", "path": path, + "note": "the key is in the registry but no curated " + "interaction touches it — its value is set " + "directly (see undo history)"} + + chains: List[Dict[str, Any]] = [] + unevaluated: List[Dict[str, Any]] = [] + _walk(path, current, [], chains, unevaluated, set(), max_depth) + if not chains: + return {"verdict": "NO_CURATED_CAUSE", "path": path, + "unevaluated": unevaluated, + "note": "no armed curated interaction explains this " + "value; it was set directly (see undo history " + "for who set it and when)"} + return {"verdict": "OK", "path": path, "chains": chains, + "unevaluated": unevaluated, + "note": "chains are explanations OF CITED CODE in the " + "curated table (bounded, growable by reviewed " + "diffs), not causes in nature"} + + +def _walk(path: str, current: Optional[Dict[str, Any]], + hops: List[Dict[str, Any]], chains: List[Dict[str, Any]], + unevaluated: List[Dict[str, Any]], visited: set, + depth: int) -> None: + if depth == 0: + if hops: + chains.append({"hops": list(hops), + "terminal": "DEPTH_LIMIT", + "note": "chain stopped at the bounded depth " + f"({MAX_CHAIN_DEPTH}); refusing to " + "guess further"}) + return + progressed = False + for edge in _cons.EDGES: + if edge["effect_path"] != path: + continue + if edge["trigger_path"] == path: + continue # self-annotation edges explain nothing backward + state = _edge_state(edge, current) + if state["status"] == "UNEVALUATED": + entry = dict(_hop(edge)) + entry["status"] = "UNEVALUATED" + entry["reason"] = state["reason"] + if entry not in unevaluated: + unevaluated.append(entry) + continue + if state["status"] != "ARMED": + continue + key = (edge["trigger_path"], edge.get("id")) + if key in visited: + continue # cycle in the curated table itself: stop, no loop + progressed = True + hop = _hop(edge) + _walk(edge["trigger_path"], current, hops + [hop], chains, + unevaluated, visited | {key}, depth - 1) + if not progressed and hops: + live = _live(current, path) + detail = (f"{path} is currently {live!r} — no curated " + "interaction explains it (set directly; see undo " + "history)" if live is not None else + f"live value of {path} unknown — cannot attribute " + "further (abstaining)") + chains.append({"hops": list(hops), "terminal": "DIRECT", + "terminal_detail": detail}) + + +def unevaluated_edges(current: Optional[Dict[str, Any]] = None + ) -> List[Dict[str, Any]]: + """Curated edges whose ``requires`` live value is unknown — the ones + a projection against this state could not evaluate. Public so the + what-if CLI view lists them instead of silently dropping them.""" + out: List[Dict[str, Any]] = [] + for edge in _cons.EDGES: + when = edge.get("when") or {} + requires = when.get("requires") + if not requires: + continue + if _live(current, requires["path"]) is None: + out.append({ + "edge": edge.get("id"), + "requires": requires["path"], + "reason": f"live value of {requires['path']} unknown — " + "this edge could fire or not; abstaining", + }) + return out + + +def counterfactual(tool: str, value: Any, + current: Optional[Dict[str, Any]] = None + ) -> Dict[str, Any]: + """Forward counterfactual: "if I set ``tool`` to ``value``…". + + Reuses ``consequences.project`` verbatim for the fired effects and + ADDS the honesty layer: curated edges that could not be evaluated + because their ``requires`` live value is unknown are listed as + UNEVALUATED — silence about an unevaluable edge is a silent drop, + and this module's contract is the opposite.""" + spec = tool_by_name(str(tool)) or tool_by_path(str(tool)) + if spec is None: + return {"verdict": "UNKNOWN_TOOL", "tool": str(tool)} + ops = [{"tool": spec.name, "value": value}] + projection = _cons.project(ops, current=current) + out = {"verdict": "OK", "tool": spec.name, "value": value, + "derived": projection.get("derived", []), + "conflicts": projection.get("conflicts", []), + "unevaluated": unevaluated_edges(current), + "note": "single pass over the curated table; the transitive " + "view is `graph breaks ` (F12), this is the " + "cited immediate projection"} + return out + + +def render_chain(result: Dict[str, Any]) -> List[str]: + """Human lines for why_chain (the CLI and the why engine reuse).""" + lines: List[str] = [] + if result.get("verdict") == "UNKNOWN_PATH": + lines.append(f"causal: {result['path']} is not in the registry — " + "no causal answer exists") + return lines + if result.get("verdict") == "NO_CURATED_CAUSE": + lines.append(f"causal: no armed curated interaction explains " + f"{result['path']}") + note = result.get("note") + if note: + lines.append(f" ({note})") + else: + for i, chain in enumerate(result.get("chains", ()), 1): + for hop in chain.get("hops", ()): + lines.append( + f"causal: {hop['effect_path']} <- {hop['from']} " + f"({hop['confidence']}, {hop['citation']})") + lines.append(f" because {hop['when']}: {hop['effect']}") + term = chain.get("terminal_detail") or chain.get("terminal") + if term: + lines.append(f" terminal: {term}") + for u in result.get("unevaluated", ()): + lines.append(f"causal: unevaluated edge {u.get('edge')}: " + f"{u.get('reason')}") + return lines + + +def render_counterfactual(result: Dict[str, Any]) -> List[str]: + """Human lines for counterfactual.""" + if result.get("verdict") == "UNKNOWN_TOOL": + return [f"counterfactual: unknown tool {result['tool']!r}"] + lines = [f"counterfactual: if {result['tool']} were " + f"{result['value']!r}…"] + for d in result.get("derived", ()): + lines.append(f" derived: {d.get('effect')} " + f"[{d.get('effect_path')}] ({d.get('confidence')}, " + f"{d.get('citation')})") + if not result.get("derived"): + lines.append(" derived: nothing in the curated table fires " + "(absence is not a guarantee)") + for u in result.get("unevaluated", ()): + lines.append(f" unevaluated: edge {u.get('edge')}: {u.get('reason')}") + return lines diff --git a/plugins/caelestia-assistant/assistant/capabilities/settings/cli.py b/plugins/caelestia-assistant/assistant/capabilities/settings/cli.py new file mode 100755 index 0000000..f48c439 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/capabilities/settings/cli.py @@ -0,0 +1,2079 @@ +"""CLI for the settings layer (the settings design notes (see module docstrings) §5): + + python3 -m assistant.capabilities.settings "" [--apply] [--file PATH] [--json] + python3 -m assistant.capabilities.settings --call NAME=VALUE [--call ...] [--apply] [--file PATH] [--json] + python3 -m assistant.capabilities.settings --list-tools [--group SLUG] + python3 -m assistant.capabilities.settings --tool NAME + python3 -m assistant.capabilities.settings --threeway "REQUEST|PRESET" [--file PATH] + # read-only: current value vs proposal vs undo-restore value + python3 -m assistant.capabilities.settings --restore [--file PATH] + +Guarantees: + +- Dry-run by default: without --apply nothing is written — not the target, + not a backup, not a tmp file — and the printed plan ends with the exact + re-run command including --apply, so the confirmation step is a + copy-paste (§5.2). This is the CLI equivalent of #120's "confirmation + for larger changes". +- Exit codes (§5.1): 0 for every honest verdict (INTENT / AMBIGUOUS / + NO_INTENT / SUGGESTED, including dry-run plans containing REJECTED + entries) and for a successful apply/restore/list; 1 for operational + failures (target file invalid JSON or non-object, unreadable file, + --apply on a blocked plan, write failure, --restore with no backup); + 2 for usage errors (argparse's default). +- --call (direct tool addressing): NAME is a registry tool name, + VALUE is parsed as JSON (true/false, numbers, quoted strings; a bare + unquoted token that fails JSON parsing is treated as a plain string). + Each --call becomes one {"tool", "action": "set", "value", "raw"} op + and is routed through the SAME planner/render/--apply path as NL + requests — this is how presets and model-driven callers address tools + without the NL parser. A --call run whose plan contains any error entry + (unknown tool, out-of-range value, bad enum, string-valued tool) exits 1 + even in dry-run: a direct invocation with a bad name or value is a + caller error, not an honest NL verdict. --call and the positional + request sentence are mutually exclusive (usage error, exit 2). +- Default target: $XDG_CONFIG_HOME/caelestia/shell.json falling back to + $HOME/.config/caelestia/shell.json (the same two env vars Layer 1 + already allowlists); never any other path unless --file says so. +- No execution, no network: suggested commands are inert + SUGGESTED_NOT_EXECUTED strings; the only writes are the ones the + applier performs behind --apply. +""" + +from __future__ import annotations + +import argparse +import json +import math +import os +import re +import sys +from pathlib import Path +from typing import Any, Dict, List, Optional, Tuple + +from . import applier, parser, planner + +from assistant.adapters.caelestia import registry +from assistant.adapters.caelestia.registry import ToolSpec, format_value, list_tools_lines, tool_by_name + +PROG = "python3 -m assistant.capabilities.settings" + +# The string-kind pre-check message: the planner validates +# bool/enum/number values only, so string-valued tools are rejected here, +# before the planner is asked to resolve the op. +CALL_STRING_TOOLS_MESSAGE = ( + "string-valued tools are not settable through --call yet " + "(registry-only until the planner gains string support)" +) + + +def default_target() -> Path: + """§5.1: $XDG_CONFIG_HOME/caelestia/shell.json, falling back to + $HOME/.config/caelestia/shell.json (QStandardPaths' GenericConfigLocation + resolves exactly these two; [C7][C29]).""" + xdg = os.environ.get("XDG_CONFIG_HOME") + base = Path(xdg) if xdg else Path.home() / ".config" + return base / "caelestia" / "shell.json" + + +def _shell_quote(text: str) -> str: + """Minimal double-quoting for the re-run command line (stdlib-only).""" + escaped = text.replace("\\", "\\\\").replace('"', '\\"') + return f'"{escaped}"' + + +# --------------------------------------------------------------------------- +# Rendering (§5.5). --json emits the same structure, machine-readable. +# --------------------------------------------------------------------------- + + +def _header(apply_mode: bool) -> List[str]: + return [ + "caelestia assistant — settings layer (NL -> validated tool calls; dry-run by default)", + "Nothing is written without --apply; this run writes nothing.", + ] if not apply_mode else [ + "caelestia assistant — settings layer (NL -> validated tool calls; dry-run by default)", + "Writes are gated: this run writes only the target file and its .assistant-backup sibling.", + ] + + +def _rerun(text: str, file_arg: Optional[str], extra: str, + call_args: Optional[List[str]] = None) -> str: + """The exact re-run command (§5.2): confirmation as a copy-paste.""" + parts = [PROG] + if call_args: + for call in call_args: + parts.append(f"--call {_shell_quote(call)}") + if text: + parts.append(_shell_quote(text)) + if file_arg: + parts.append(f"--file {file_arg}") + parts.append(extra) + return " ".join(parts) + + +def _render_entry(index: int, entry: Dict[str, Any]) -> List[str]: + lines: List[str] = [] + arrow = f"{entry['path']}: {format_value(entry['old'])} -> {format_value(entry['new'])}" + action = entry.get("action") or "" + raw = entry.get("raw") + paren = f"({entry['tool']}, {action} {raw})" if raw else f"({entry['tool']}, {action})" + if entry.get("error"): + lines.append(f" {index}. {arrow} {paren} — REJECTED: {entry['error']}") + elif entry.get("no_op"): + lines.append(f" {index}. {arrow} {paren} [no change needed]") + else: + lines.append(f" {index}. {arrow} {paren}") + if entry.get("note"): + lines.append(f" note: {entry['note']}") + return lines + + +def render_plan(plan: Dict[str, Any], parse_notes: List[str], text: str, + file_arg: Optional[str], apply_mode: bool, + apply_result: Optional[Dict[str, Any]], + call_args: Optional[List[str]] = None) -> List[str]: + lines = ["caelestia assistant — settings layer (NL -> validated tool calls; dry-run by default)"] + if apply_result is not None and apply_result.get("written"): + lines.append(f"Writes are gated: this run wrote {plan['file']} and its .assistant-backup sibling.") + elif apply_result is not None and apply_result.get("no_changes"): + lines.append("Nothing is written without --apply; this run wrote nothing (no changes were needed).") + elif apply_mode: + lines.append("Writes are gated: this run writes only the target file and its .assistant-backup sibling.") + else: + lines.append("Nothing is written without --apply; this run writes nothing.") + lines.append("") + + entries = plan.get("entries", []) + notes = list(parse_notes) + list(plan.get("notes", [])) + if apply_result is not None and apply_result.get("written"): + lines.append(f"Verdict: INTENT — {len(entries)} change(s) applied on {plan['file']}") + else: + lines.append(f"Verdict: INTENT — {len(entries)} change(s) planned on {plan['file']}") + for idx, entry in enumerate(entries, start=1): + lines.extend(_render_entry(idx, entry)) + if plan.get("apply_blocked"): + lines.append( + "apply_blocked: this plan contains rejected or type-mismatched entries; " + "--apply will refuse to write anything" + ) + if notes: + lines.append("notes:") + lines.extend(f" - {note}" for note in notes) + if apply_result is not None: + lines.append(apply_result["message"]) + if apply_result.get("written"): + lines.append(f"undo with: {_rerun('', file_arg, '--restore')}") + else: + # §5.2: the printed plan ends with the exact re-run command. + lines.append(f"Apply with: {_rerun(text, file_arg, '--apply', call_args)}") + return lines + + +def render_verdict(result: Dict[str, Any]) -> List[str]: + """Render AMBIGUOUS / NO_INTENT / SUGGESTED verdicts (§5.5).""" + lines = _header(False) + lines.append("") + verdict = result["verdict"] + if verdict == "AMBIGUOUS": + if result.get("candidates"): + lines.append("Verdict: AMBIGUOUS — several settings fit; name one:") + for idx, cand in enumerate(result["candidates"], start=1): + lines.append(f" {idx}. {cand['description']}") + else: + lines.append("Verdict: AMBIGUOUS — the request is not specific enough to act on safely.") + if result.get("notes"): + for note in result["notes"]: + lines.append(f" note: {note}") + if result.get("question"): + lines.append(f"Clarify: {result['question']}") + elif verdict == "NO_INTENT": + lines.append("Verdict: NO supported setting matched.") + for note in result.get("notes", []): + lines.append(f" {note}") + if result.get("question"): + lines.append(f"Clarify: {result['question']}") + elif verdict == "SUGGESTED": + lines.append( + "Verdict: SUGGESTED — this request is real, but it lives outside shell.json " + "(the scheme/wallpaper system); nothing was executed and nothing was written." + ) + for suggestion in result.get("suggestions", []): + lines.append(f" {suggestion}") + for note in result.get("notes", []): + lines.append(f" note: {note}") + return lines + + +# --------------------------------------------------------------------------- +# --list-tools / --tool (registry inspection; these never write anything). +# --------------------------------------------------------------------------- + + +def _list_tools_lines(group: Optional[str]) -> List[str]: + """The --list-tools table: group-filtered when --group is given (the + registry itself renders per-group subtotal lines when unfiltered).""" + return list_tools_lines(group) + + +def _tool_card(spec: ToolSpec) -> List[str]: + """The --tool NAME detail card: every registry fact we hold about one + tool, including every citation line ("file:line — what it evidences"). + Fields the current registry build does not carry (group, citations on + the 18-tool core) are rendered as explicit absences, never guessed.""" + if spec.kind == "enum": + enum_values = "|".join(spec.enum or ()) or "(none)" + validation = f"enum {enum_values}" + elif spec.kind == "bool": + validation = "on/off" + elif spec.kind == "string": + validation = "string" + else: + low = "(unbounded)" if spec.minimum is None else spec.minimum + high = "(unbounded)" if spec.maximum is None else spec.maximum + validation = f"range {low}-{high}" + group = getattr(spec, "group", None) + citations = getattr(spec, "citations", None) or () + lines = [ + "caelestia assistant — settings layer: tool detail", + "", + f" name: {spec.name}", + f" path: {spec.path}", + f" group: {group if group else '(no group metadata in this registry build)'}", + f" kind: {spec.kind}", + f" validation: {validation}", + f" default: {format_value(spec.default)}", + f" global-only: {'yes' if spec.global_only else 'no'}", + f" step: {spec.step if spec.step else '(not steppable)'}", + f" nouns: {'; '.join(spec.nouns) if spec.nouns else '(none)'}", + " citations:", + ] + if not citations: + lines.append(" (none recorded in this registry build)") + return lines + for citation in citations: + if isinstance(citation, (tuple, list)) and len(citation) >= 2: + lines.append(f" {citation[0]} — {citation[1]}") + else: + lines.append(f" {citation}") + return lines + + +# --------------------------------------------------------------------------- +# --call NAME=VALUE (direct tool addressing): parse into planner +# ops, with two CLI-side pre-checks that produce error entries WITHOUT +# calling the planner for that op (the planner only knows bool/enum/number). +# --------------------------------------------------------------------------- + + +def _parse_call_value(value_text: str) -> Any: + """VALUE is parsed as JSON (true/false, numbers, quoted strings); a + bare unquoted token that fails JSON parsing is a plain string.""" + try: + return json.loads(value_text) + except ValueError: + return value_text + + +def _call_error_entry(spec: Optional[ToolSpec], name: str, raw: str, + error: str) -> Dict[str, Any]: + """A planner-shaped error entry synthesized by the CLI (same keys as + planner._error_entry) for ops the planner must not be asked to resolve.""" + return { + "tool": spec.name if spec is not None else name, + "path": spec.path if spec is not None else "", + "action": "set", + "raw": raw, + "old": None, + "new": None, # an errored entry is never applied + "clamped": False, + "no_op": False, + "note": None, + "error": error, + } + + +def _compose_call_ops(calls: List[str]) -> Tuple[List[Dict[str, Any]], Dict[int, Dict[str, Any]]]: + """Turn --call NAME=VALUE flags into planner ops. + + Returns (ops, cli_errors): ``ops`` holds the ops the planner should + resolve (in flag order); ``cli_errors`` maps each rejected flag's + position to a ready-made error entry. Raises ValueError for malformed + flags (no '=' / empty name) — a usage error, exit 2. + """ + ops: List[Dict[str, Any]] = [] + cli_errors: Dict[int, Dict[str, Any]] = {} + for position, call in enumerate(calls): + name, sep, value_text = call.partition("=") + if not sep or not name: + raise ValueError(f"--call expects NAME=VALUE (got {call!r})") + value = _parse_call_value(value_text) + op = {"tool": name, "action": "set", "value": value, "raw": call} + spec = tool_by_name(name) + if spec is None: + # Unknown tool: the planner's existing unknown-tool error entry + # (it renders through the same REJECTED path). + ops.append(op) + continue + if getattr(spec, "kind", "") == "string": + # The planner validates bool/enum/number values only; string + # tools are rejected here, before the planner sees the op. + cli_errors[position] = _call_error_entry( + spec, name, call, CALL_STRING_TOOLS_MESSAGE) + continue + if isinstance(value, float) and not math.isfinite(value): + # json.loads accepts NaN/Infinity; the planner's range checks + # cannot reject them (all comparisons with NaN are False), so + # they are stopped here — they can never be written as JSON. + cli_errors[position] = _call_error_entry( + spec, name, call, + f"value {value_text!r} is not a finite number; " + "NaN/Infinity are not valid JSON values", + ) + continue + ops.append(op) + return ops, cli_errors + + +def _splice_call_errors(plan: Dict[str, Any], + cli_errors: Dict[int, Dict[str, Any]], total: int) -> None: + """Merge the CLI-synthesized error entries back into the plan at their + original --call positions, extend the plan's error list and mark it + apply_blocked (all-or-nothing, §4.5).""" + if not cli_errors: + return + merged: List[Dict[str, Any]] = [] + planner_entries = plan.get("entries", []) + planner_index = 0 + for position in range(total): + if position in cli_errors: + merged.append(cli_errors[position]) + else: + merged.append(planner_entries[planner_index]) + planner_index += 1 + plan["entries"] = merged + errors = plan.setdefault("errors", []) + for entry in cli_errors.values(): + errors.append( + {"tool": entry["tool"], "path": entry["path"], "error": entry["error"]} + ) + plan["apply_blocked"] = True + + +# --------------------------------------------------------------------------- +# Argument parsing and dispatch. +# --------------------------------------------------------------------------- + + +def _build_arg_parser() -> argparse.ArgumentParser: + arg_parser = argparse.ArgumentParser( + prog=PROG, + description=( + "caelestia assistant settings layer (#120): natural-language request " + "-> validated tool calls on the shell's shell.json. Dry-run by default; the only " + "writes are the target file behind --apply plus its .assistant-backup sibling." + ), + epilog="Nothing is ever executed; suggested commands are inert strings.", + ) + arg_parser.add_argument( + "text", nargs="?", default=None, + help='the request, e.g. "make the bar thinner" (required unless ' + "--list-tools/--tool/--restore/--call)", + ) + gate = arg_parser.add_mutually_exclusive_group() + gate.add_argument( + "--apply", action="store_true", + help="actually write the planned changes (default: dry-run, nothing written)", + ) + gate.add_argument( + "--restore", action="store_true", + help="undo: put the single .assistant-backup slot back (one level of undo)", + ) + arg_parser.add_argument( + "--file", metavar="PATH", default=None, + help=f"target shell.json override (default: {default_target()})", + ) + arg_parser.add_argument( + "--json", action="store_true", help="emit the machine-readable plan/verdict as JSON" + ) + arg_parser.add_argument( + "--list-tools", action="store_true", + help="print the tool registry table (every tool with path, type, range) and exit", + ) + arg_parser.add_argument( + "--group", metavar="SLUG", default=None, + help="feature-area filter for --list-tools (default: all groups)", + ) + arg_parser.add_argument( + "--tool", metavar="NAME", default=None, + help="print a detail card for one tool (path, validation, citations) and exit", + ) + arg_parser.add_argument( + "--call", action="append", dest="calls", metavar="NAME=VALUE", + help="direct tool call: NAME is a registry tool name, VALUE is JSON " + "(true/false, number, quoted string; a bare token that fails JSON " + "parsing is a plain string); repeatable — multiple --call flags " + "compose one multi-op plan", + ) + arg_parser.add_argument( + "--explain", metavar="QUERY", default=None, + help="read-only: explain a setting's current state (a dotted path, a " + "tool name, or a plain-words question like 'why is my dock " + "blurry'); never writes", + ) + arg_parser.add_argument( + "--history", action="store_true", + help="read-only: list the bounded undo history (newest first) and exit", + ) + arg_parser.add_argument( + "--prefer", nargs=2, metavar=("PRESET_A", "PRESET_B"), default=None, + help="opt-in pairwise comparison: dry-run previews of both presets " + "side by side, then record which you pick (feeds the Elo/" + "Bradley-Terry ladder; writes one comparison row to the " + "assistant state, never to shell.json)", + ) + arg_parser.add_argument( + "--threeway", metavar="TEXT", default=None, + help="read-only three-way diff view: for each setting the " + "request (or preset) would touch — the file's current " + "value, the proposal's value, and the value the undo " + "history would restore — so 'apply then undo' is never a " + "surprise; never writes", + ) + arg_parser.add_argument( + "--what-if", metavar="TEXT", default=None, + help="read-only consequence view: plan the request (or a preset " + "name) as a DRY RUN, then project it through the cited " + "interaction table (derived effects, conflicts, " + "reversibility); never writes, never applies", + ) + arg_parser.add_argument( + "--why-chain", metavar="KEY", default=None, + help="read-only causal attribution (F14): the backward chain " + "of ARMED, cited interactions explaining the current " + "value of a registry path or tool — with the live state " + "read from the target file; unevaluable edges are listed, " + "never guessed", + ) + arg_parser.add_argument( + "--counterfactual", nargs=2, metavar=("TOOL", "VALUE"), + default=None, + help="read-only forward counterfactual (F14): 'if TOOL were " + "VALUE' — the cited immediate projection plus every " + "curated edge that could not be evaluated against the " + "live state (abstained, not dropped)", + ) + arg_parser.add_argument( + "--accessibility-check", nargs=2, metavar=("FG", "BG"), + default=None, + help="read-only WCAG 2.x contrast verdicts (F22) for an " + "fg/bg pair of #rrggbb colors, with the Machado (2009) " + "CVD simulation of each color under --cvd/--severity; " + "pure math, never writes", + ) + arg_parser.add_argument( + "--cvd", default=None, + choices=["protanopia", "deuteranopia", "tritanopia"], + help="accessibility-check: simulate this color-vision deficiency", + ) + arg_parser.add_argument( + "--severity", type=float, default=1.0, + help="accessibility-check: CVD severity in [0, 1] (default 1.0; " + "partial severities are the documented linear blend)", + ) + arg_parser.add_argument( + "--recommend", metavar="TOOL", default=None, + help="read-only value recommendation (F29) for a numeric tool: " + "hierarchical partial pooling over the registry default, " + "the preset pool and your approved history, with a " + "95-percent " + "credible interval and the Pareto position against the " + "optimization profiles; a proposal, never applied", + ) + arg_parser.add_argument( + "--rank", action="store_true", + help="read-only: print the learned pairwise preference ladder for " + "presets (Elo + Bradley-Terry, with comparison counts)", + ) + arg_parser.add_argument( + "--undo", nargs="?", const=1, default=None, type=int, metavar="STEPS", + help="undo the newest STEPS applies (default 1) from the bounded " + "history; writes only the reverted values", + ) + arg_parser.add_argument( + "--undo-id", type=int, default=None, metavar="ID", + help="revert one specific history entry (see --history) — the " + "'restore the theme I had yesterday' operation", + ) + arg_parser.add_argument( + "--preset", metavar="NAME", default=None, + help="apply a named preset (compact, minimal, gaming, battery-saver, " + "macos-like) — a bundle of validated tool calls; multi-change, " + "so it always shows the preview and needs --confirm/--apply", + ) + arg_parser.add_argument( + "--list-presets", action="store_true", + help="print the preset table (name, description, bundled calls) and exit", + ) + arg_parser.add_argument( + "--confirm", action="store_true", + help="second consent for multi-change applies: without it (and without " + "an interactive yes), a plan touching more than one setting is " + "previewed but NOT written", + ) + arg_parser.add_argument( + "--lint", action="store_true", + help="read-only config health lint of the target shell.json (unknown " + "keys, out-of-range or mistyped values, silent no-ops, inert " + "customizations); never writes", + ) + arg_parser.add_argument( + "--audit-env", action="store_true", + help="read-only environment audit (F21): config lint, cited " + "interaction INERT states, snapshot freshness (F17), " + "per-screen overrides (F20) and backup coverage in one " + "report; exit 1 on CRITICAL findings", + ) + arg_parser.add_argument( + "--wallpaper-palette", metavar="PATH", default=None, + help="read-only: derive a WCAG-checked accent candidate from a " + "wallpaper PNG (k-means in OKLab) and surface it through the " + "same inert scheme-suggestion path as accent-color requests", + ) + arg_parser.add_argument( + "--wizard", action="store_true", + help="first-run setup wizard: pairwise tradeoff questions -> AHP " + "weights -> TOPSIS over the shipped presets -> a starting-preset " + "recommendation (writes nothing; apply via --preset yourself)", + ) + arg_parser.add_argument( + "--answers", metavar="N,N,N,N,N,N", default=None, + help="non-interactive wizard answers, one 1-5 intensity per " + "question, in the order --wizard prints them", + ) + gate2 = arg_parser.add_mutually_exclusive_group() + gate2.add_argument( + "--macro", metavar="NAME", default=None, + help="replay a saved macro (an APPROVED proposal sequence " + "captured earlier): dry-run plan by default; with --apply " + "it STILL needs --confirm or the interactive prompt — " + "every replay is re-approved, single-change macros " + "included", + ) + gate2.add_argument( + "--macro-save", metavar="NAME", default=None, + help="capture the newest applied change (or --from-id ID, see " + "--history) as a named macro — a record of something you " + "already approved, stored in the history file's bounded " + "macro list (never the target file)", + ) + gate2.add_argument( + "--macro-list", action="store_true", + help="read-only: list the saved macros and exit", + ) + gate2.add_argument( + "--macro-delete", metavar="NAME", default=None, + help="delete one saved macro by name (an explicit command; " + "never a silent overwrite)", + ) + gate3 = arg_parser.add_mutually_exclusive_group() + gate3.add_argument( + "--profile", metavar="NAME", default=None, + help="apply a saved profile (F9: a named composition of " + "presets, macros and direct calls, later source wins per " + "tool with conflicts reported): dry-run plan by default; " + "with --apply it needs --confirm like any multi-change " + "bundle", + ) + gate3.add_argument( + "--profile-save", nargs=2, metavar=("NAME", "SRC"), default=None, + help="save a profile: NAME plus the first source; repeat " + "--also SRC for more. A source is preset:NAME, macro:NAME, " + "or TOOL=VALUE; sources compose in order, later wins per " + "tool (conflicts reported, never dropped)", + ) + gate3.add_argument( + "--profile-list", action="store_true", + help="read-only: list the saved profiles and exit", + ) + gate3.add_argument( + "--profile-show", metavar="NAME", default=None, + help="read-only: one profile's sources, composed ops and the " + "conflicts their order resolved; never writes", + ) + gate3.add_argument( + "--profile-diff", nargs=2, metavar=("A", "B"), default=None, + help="read-only: effective-value diff of two saved profiles " + "(only A / only B / changed per tool)", + ) + gate3.add_argument( + "--profile-delete", metavar="NAME", default=None, + help="delete one saved profile by name (an explicit command)", + ) + gate3.add_argument( + "--profile-whatif", metavar="NAME", default=None, + help="read-only composite preview (F11): per-source consequences, " + "the conflicts the source order resolved, the blast radius by " + "feature area, and the projected-state sanity verdicts the " + "applier itself would enforce — before any consent", + ) + arg_parser.add_argument( + "--also", action="append", dest="also_sources", + metavar="SRC", default=None, + help="with --profile-save: an additional source (see " + "--profile-save); repeatable, order matters", + ) + gate4 = arg_parser.add_mutually_exclusive_group() + gate4.add_argument( + "--env-save", metavar="NAME", default=None, + help="snapshot the current environment (shell.json content, " + "hash-pinned; macros/profiles as metadata) into the " + "history file's bounded environment list", + ) + gate4.add_argument( + "--env-list", action="store_true", + help="read-only: list the saved environments and exit", + ) + gate4.add_argument( + "--env-show", metavar="NAME", default=None, + help="read-only: one environment's metadata + integrity " + "verification (with --env-verify, default on) and per-area " + "summary", + ) + gate4.add_argument( + "--env-diff", metavar="NAME", default=None, + help="read-only: what RESTORING NAME would change — registry " + "paths set back to snapshot values / reset to defaults, " + "unknown keys REPORTED and never touched", + ) + gate4.add_argument( + "--env-restore", metavar="NAME", default=None, + help="restore environment NAME: the diff becomes a normal " + "planned multi-change apply (dry-run by default; --apply " + "still needs --confirm)", + ) + gate4.add_argument( + "--env-delete", metavar="NAME", default=None, + help="delete one saved environment by name (an explicit command)", + ) + gate4.add_argument( + "--env-export", metavar="NAME", default=None, + help="export a verified environment as a portable bundle (with " + "--to PATH); nothing else is written", + ) + gate4.add_argument( + "--env-import", metavar="FROM_JSON", default=None, + help="import a bundle as a NEW snapshot, REVIEW-ONLY (with --as " + "NAME): schema/hash validated, drift measured, nothing " + "applied — restore stays the explicit F17 path", + ) + arg_parser.add_argument( + "--monitor", metavar="SCREEN", default=None, + help="F20: target ONE screen's override file " + "(monitors/SCREEN/shell.json, the upstream forScreen layer — " + "same schema, same validation, same gates) instead of the " + "global config; combine with a request or --call; cannot be " + "combined with --file", + ) + arg_parser.add_argument( + "--monitors", action="store_true", + help="read-only monitor report (F20): the discovered per-screen " + "override files and the global tools that select monitor " + "behavior, with citations; never writes", + ) + gate5 = arg_parser.add_mutually_exclusive_group() + gate5.add_argument( + "--gen-catalog", action="store_true", + help="community docs generator (F23): (re)write the generated " + "the generated tool catalog (`settings --gen-catalog`) and bash completion from the frozen " + "registry; with --verify it only CHECKS byte-identity (CI " + "safe)", + ) + arg_parser.add_argument( + "--verify", dest="gen_verify", action="store_true", + help="with --gen-catalog: verify the committed artifacts match a " + "fresh generation instead of rewriting them", + ) + arg_parser.add_argument( + "--plain", action="store_true", + help="accessible output (F24): one fact per line, no tables or " + "decorations — also CAELESTIA_ASSISTANT_PLAIN=1; the " + "contract is test-enforced (no ANSI, no box-drawing, " + "stable order)", + ) + arg_parser.add_argument( + "--a11y-recipe", action="store_true", + help="read-only reduced-motion recipe (F24): registry-validated " + "knobs composed into an inert one-line --profile-save " + "command; nothing is saved or applied by printing it", + ) + arg_parser.add_argument( + "--to", metavar="PATH", default=None, + help="with --env-export: the bundle output path", + ) + arg_parser.add_argument( + "--as", dest="as_name", metavar="NAME", default=None, + help="with --env-import: the local name for the imported " + "environment", + ) + arg_parser.add_argument( + "--from-id", type=int, default=None, metavar="ID", + help="with --macro-save: capture this history entry id instead " + "of the newest (see --history)", + ) + return arg_parser + + +def _preview_block(plan: Dict[str, Any], label: str) -> List[str]: + """The issue #120 preview, verbatim in shape: + "I found several changes that match your request:" + one line per + change + "Apply these changes?".""" + lines = ["I found several changes that match your request" + + (f" ({label})" if label else "") + ":"] + for entry in plan.get("entries", []): + if entry.get("error") or entry.get("no_op"): + continue + lines.append(f"- {entry.get('path')}: " + f"{entry.get('old', '(unset)')} -> {entry.get('new')}") + lines.append("Apply these changes?") + return lines + + +def _confirm_multi(plan: Dict[str, Any], args: Any) -> Tuple[bool, str]: + """The multi-change confirmation gate (issue #120). + + --confirm: explicit second consent. Interactive tty: the preview plus a + y/N prompt. Otherwise: refusal with the re-run hint. Never guesses.""" + label = getattr(args, "text", None) or "" + if getattr(args, "confirm", False): + return True, "" + if sys.stdin is not None and sys.stdin.isatty(): + print("\n".join(_preview_block(plan, label))) + try: + answer = input("Apply these changes? [y/N] ").strip().lower() + except EOFError: + answer = "" + if answer in ("y", "yes"): + return True, "" + return False, "not confirmed; nothing was written" + return False, ( + "multi-change plans need confirmation: re-run with --confirm " + "(or answer the prompt interactively); nothing was written" + ) + + +def main(argv: Optional[List[str]] = None) -> int: + arg_parser = _build_arg_parser() + args = arg_parser.parse_args(argv) + + if args.calls is not None and args.text is not None: + arg_parser.error( + "--call and a request sentence are mutually exclusive: address tools " + "directly with --call, or describe the change in plain words" + ) + if args.group is not None and not args.list_tools: + arg_parser.error("--group is only valid together with --list-tools") + if args.undo is not None and args.undo_id is not None: + arg_parser.error("--undo and --undo-id are mutually exclusive") + if args.from_id is not None and args.macro_save is None: + arg_parser.error("--from-id is only valid together with --macro-save") + + if args.list_presets: + from . import presets as presets_mod + print("\n".join(presets_mod.describe_lines())) + return 0 + + if args.preset is not None: + # A preset is a bundle of validated tool calls riding the ordinary + # plan path — never a bespoke writer. + from . import presets as presets_mod + try: + ops = presets_mod.preset_ops(args.preset) + except presets_mod.PresetError as exc: + print(f"error: {exc}", file=sys.stderr) + return 1 + target = Path(args.file) if args.file else default_target() + try: + plan = planner.plan(ops, target) + except planner.PlannerError as exc: + print(f"error: {exc}", file=sys.stderr) + return 1 + if not args.apply: + print("\n".join(render_plan(plan, [], f"preset: {args.preset}", + args.file, False, None, None))) + return 0 + confirmed, why = _confirm_multi(plan, args) + if not confirmed: + print(why, file=sys.stderr) + return 1 + try: + apply_result = applier.apply( + plan, target, write=True, label=f"preset: {args.preset}") + except applier.ApplierError as exc: + print(f"error: {exc}", file=sys.stderr) + return 1 + print("\n".join(render_plan(plan, [], f"preset: {args.preset}", + args.file, True, apply_result, None))) + return 0 + + if args.threeway is not None: + # exponential-build-3 G1: the three-way diff view — current + # file value vs the current proposal vs the undo-log restore + # value, per touched key. Read-only: the parser/planner spine + # runs dry (plan only) and the history is only READ. + from . import history as history_mod + + request = args.threeway + try: + parse = parser.parse(request) + ops = parse.get("ops") or [] + except Exception: + ops = [] + if not ops: + from . import presets as presets_mod + try: + ops = presets_mod.preset_ops(request) + except Exception: + ops = [] + if not ops: + print(f"error: threeway could not plan {request!r} (use a " + "request or a preset name)", file=sys.stderr) + return 1 + target = Path(args.file) if args.file else default_target() + try: + plan = planner.plan(ops, target) + except planner.PlannerError as exc: + print(f"error: {exc}", file=sys.stderr) + return 1 + entries = history_mod.entries(target) # newest first + print("\n".join(_header(False))) + print("") + print(f"three-way view for {request!r} (read-only; nothing " + "is written):") + shown = 0 + for entry in plan.get("entries", []): + if entry.get("error") or entry.get("no_op"): + continue + path = str(entry.get("path")) + current = entry.get("old", "(unset)") + proposed = entry.get("new") + record = next((e for e in entries + if any(op.get("path") == path + for op in e.get("ops", []))), None) + print(f" {path}:") + print(f" now (file): {current!r}") + print(f" proposal: {proposed!r}") + if record is not None: + op = next(op for op in record.get("ops", []) + if op.get("path") == path) + restore = op.get("old") + label = record.get("label") or "(unlabelled)" + print(f" undo would restore: {restore!r} " + f"(history #{record.get('id')} {label!r}, " + f"{record.get('at', '?')})") + if restore != current: + print(" note: apply-then-undo lands on the " + "restored value, NOT back on the current " + "one") + else: + print(" note: apply-then-undo returns exactly " + "to the current value") + else: + print(" undo record: none for this key " + "(first change would create one)") + shown += 1 + if not shown: + print(" the request resolves to no applicable changes") + return 0 + + if args.why_chain is not None: + # F14: backward causal attribution — read-only, cited, live-state + from . import causal as causal_mod + from . import planner as chain_planner + + target = Path(args.file) if args.file else default_target() + current: Dict[str, Any] = {} + if target.exists(): + try: + current, _notes = chain_planner._read_current(target) + except Exception: + current = {} + result = causal_mod.why_chain(args.why_chain, current) + print("\n".join(_header(False))) + print("") + print("\n".join(causal_mod.render_chain(result))) + if args.json: + print(json.dumps(result, sort_keys=True, indent=1)) + return 0 if result.get("verdict") == "OK" else 1 + + if args.counterfactual is not None: + # F14: forward counterfactual — the what-if projection for one + # explicit tool/value pair, with the unevaluated-edge honesty + from . import causal as causal_mod + from . import planner as cf_planner + + tool_name, raw_value = args.counterfactual + parsed_value: Any + if raw_value == "true": + parsed_value = True + elif raw_value == "false": + parsed_value = False + elif re.fullmatch(r"-?\d+", raw_value): + parsed_value = int(raw_value) + elif re.fullmatch(r"-?\d+\.\d+", raw_value): + parsed_value = float(raw_value) + else: + parsed_value = raw_value + target = Path(args.file) if args.file else default_target() + current: Dict[str, Any] = {} + if target.exists(): + try: + current, _notes = cf_planner._read_current(target) + except Exception: + current = {} + result = causal_mod.counterfactual(tool_name, parsed_value, current) + print("\n".join(_header(False))) + print("") + print("\n".join(causal_mod.render_counterfactual(result))) + if args.json: + print(json.dumps(result, sort_keys=True, indent=1)) + return 0 if result.get("verdict") == "OK" else 1 + + if args.recommend is not None: + # F29: the value recommender — read-only, pooled, honest + from . import recommend as recommend_mod + + ledger = None + target = Path(args.file) if args.file else default_target() + hist = target.parent / (target.name + ".assistant-history.json") + if hist.exists(): + ledger = str(hist) + result = recommend_mod.recommend(args.recommend, ledger_path=ledger) + print("\n".join(_header(False))) + print("") + print("\n".join(recommend_mod.render_recommendation(result))) + if args.json: + print(json.dumps(result, sort_keys=True, indent=1)) + return 0 if result.get("verdict") == "OK" else 1 + + if args.accessibility_check is not None: + # F22: WCAG 2.x contrast verdicts + optional Machado CVD + # simulation — pure published math, read-only. + from . import accessibility as ax + + fg_hex, bg_hex = args.accessibility_check + try: + fg, bg = ax.hex_to_rgb(fg_hex), ax.hex_to_rgb(bg_hex) + except ValueError as exc: + print(f"error: {exc}", file=sys.stderr) + return 2 + print("\n".join(_header(False))) + print("") + print(f"contrast {fg_hex} on {bg_hex}: " + f"{ax.contrast_ratio(fg, bg):.2f}:1") + for f in ax.wcag_findings(fg, bg): + mark = "pass" if f["pass"] else "FAIL" + print(f" [{mark}] {f['level']}: {f['ratio']}:1 " + f"(threshold {f['threshold']})") + if args.cvd: + sev = args.severity + if not 0.0 <= sev <= 1.0: + print("error: --severity must be in [0, 1]", + file=sys.stderr) + return 2 + sim_fg = ax.rgb_to_hex(ax.simulate_cvd(fg, args.cvd, sev)) + sim_bg = ax.rgb_to_hex(ax.simulate_cvd(bg, args.cvd, sev)) + ratio = ax.contrast_ratio( + ax.simulate_cvd(fg, args.cvd, sev), + ax.simulate_cvd(bg, args.cvd, sev)) + print(f" under {args.cvd} (severity {sev}): {sim_fg} on " + f"{sim_bg}, contrast {ratio:.2f}:1") + print(f" cite: {ax.WCAG_CITATION}") + if args.cvd: + print(f" cite: {ax.SIMULATE_CITATION}") + if args.json: + import json as _json + print(_json.dumps({ + "fg": fg_hex, "bg": bg_hex, + "ratio": round(ax.contrast_ratio(fg, bg), 4), + "findings": ax.wcag_findings(fg, bg), + "cvd": ({"kind": args.cvd, "severity": args.severity, + "fg": ax.rgb_to_hex(ax.simulate_cvd(fg, args.cvd, args.severity)), + "bg": ax.rgb_to_hex(ax.simulate_cvd(bg, args.cvd, args.severity))} + if args.cvd else None), + }, sort_keys=True, indent=1)) + return 0 + + if args.what_if is not None: + # Phase 2.7: the what-if consequence view — a DRY-RUN plan plus + # the projection through the cited interaction table. Read-only: + # the parser/planner/applier spine is untouched and this surface + # can never apply anything. + from . import consequences as consequences_mod + from . import parser as whatif_parser + + request = args.what_if + try: + parse = whatif_parser.parse(request) + ops = parse.get("ops") or [] + except Exception: + ops = [] + if not ops: + # preset name? plan its bundle as the candidate list + from . import presets as presets_mod + + try: + ops = presets_mod.preset_ops(request) + except Exception: + ops = [] + if not ops: + print(f"error: what-if could not plan {request!r} (use a " + "request or a preset name)", file=sys.stderr) + return 1 + target = Path(args.file) if args.file else default_target() + current: Dict[str, Any] = {} + if target.exists(): + try: + current, _notes = planner._read_current(target) + except Exception: + current = {} + # Resolve the ops through the standard planner ONCE: step and + # multiply ops become the absolute values they produce. The + # projection runs over the RESOLVED entries — projecting a raw + # step delta (-1) as an absolute value fires false edges. + resolved_ops: List[Dict[str, Any]] = [] + try: + plan = planner.plan(ops, target) + resolved_ops = [{"tool": e.get("tool"), "value": e.get("new")} + for e in plan.get("entries", []) + if not e.get("error")] + except planner.PlannerError as exc: + plan = None + print(f"note: planner refused: {exc} (projection below is " + "the honest view of the requested ops)") + projection = consequences_mod.project( + resolved_ops or ops, current=current) + print("\n".join(_header(False))) + print("") + print("\n".join(consequences_mod.render(projection))) + # F14 honesty extension: curated edges that could not be + # evaluated against the live state are listed, not dropped + from . import causal as whatif_causal + + for u in whatif_causal.unevaluated_edges(current): + print(f" unevaluated: edge {u['edge']}: {u['reason']}") + print("") + if plan is not None: + print("\n".join(render_plan(plan, [], + f"what-if: {request}", args.file, + False, None, None))) + return 0 + + if args.rank: + # Phase 2.4: the learned pairwise ladder — read-only, over the + # comparison rows --prefer records. The shared ranking primitive + # (brain/ranking.py) is the same one agent plan comparisons use. + from assistant.capabilities.brain import ranking as ranking_mod + from assistant.capabilities.brain import state as brain_state + + state = brain_state.load() + rows = state.get("preset_comparisons") or [] + # exponential-build-3 G2: surface a pending idle-time invitation + # BEFORE the empty-log early return — a fresh install's first + # invitation must be visible even with zero comparisons + from assistant.capabilities.brain import preference_prompts + invite = preference_prompts.pending(state) + if not rows: + if invite: + print("no pairwise comparisons recorded yet — but an " + "idle-time invitation is waiting:") + print(f" settings --prefer {invite.get('a')} " + f"{invite.get('b')} ({invite.get('reason')}; " + f"invited {invite.get('at')})") + return 0 + print("no pairwise comparisons recorded yet; record one with " + "settings --prefer PRESET_A PRESET_B") + return 0 + pairs = [(row.get("winner"), row.get("loser")) for row in rows + if row.get("winner") and row.get("loser")] + report = ranking_mod.ladder_report(pairs) + print("preset preference ladder (pairwise, learned from your " + "explicit comparisons):") + for row in report["ladder"]: + conf = (f"{row['comparisons']} comparisons" + if row["enough_data"] else "not enough data") + print(f" {row['rating']:8.1f} {row['item']:<16} ({conf})") + tau = report["agreement_kendall_tau"] + if tau is not None: + print(f"elo/bradley-terry order agreement (kendall tau): {tau}") + # exponential-build-3 G2: surface a pending idle-time invitation + if invite: + print(f"idle-time invitation pending: settings --prefer " + f"{invite.get('a')} {invite.get('b')} " + f"({invite.get('reason')}; invited {invite.get('at')})") + print("proposals only — nothing is applied; the planner/applier " + "gates are untouched") + return 0 + + if args.prefer: + # Phase 2.4: ONE explicit pairwise comparison (the proposal's + # opt-in design — each pair is a deliberate choice, no batch). + from assistant.capabilities.brain import state as brain_state + from . import presets as presets_mod + + name_a, name_b = args.prefer + known = [str(p["name"]) for p in presets_mod.presets()] + target = Path(args.file) if args.file else default_target() + for name in (name_a, name_b): + if name not in known: + print(f"error: unknown preset {name!r}; known: " + f"{', '.join(known)}", file=sys.stderr) + return 1 + print("\n".join(_header(False))) + print("") + for index, name in enumerate((name_a, name_b), 1): + print(f"[{index}] preset {name} (dry-run, nothing written):") + try: + plan = planner.plan(presets_mod.preset_ops(name), target) + except planner.PlannerError as exc: + print(f" planner refused: {exc}") + continue + print("\n".join(" " + line for line in render_plan( + plan, [], f"prefer: {name}", args.file, False, None, None))) + try: + pick = input(f"which do you prefer? [1={name_a} / 2={name_b} " + "/ s=skip] ").strip().lower() + except EOFError: + pick = "" + if pick not in ("1", "2"): + print("no comparison recorded (skip)") + return 0 + winner = name_a if pick == "1" else name_b + loser = name_b if pick == "1" else name_a + state = brain_state.load() + rows = state.setdefault("preset_comparisons", []) + if not isinstance(rows, list): + rows = [] + from datetime import datetime + rows.append({"winner": winner, "loser": loser, + "at": datetime.now().isoformat(timespec="seconds")}) + state["preset_comparisons"] = rows[-200:] + # exponential-build-3 G2: if this comparison answers a pending + # idle-time invitation, consume it (either order counts) + from assistant.capabilities.brain import preference_prompts + consumed = preference_prompts.answer(state, name_a, name_b) + brain_state.save(state) + suffix = " (this answers the pending idle-time prompt)" \ + if consumed else "" + print(f"recorded: {winner} > {loser} (see settings --rank){suffix}") + return 0 + + if args.lint: + # Read-only config health lint (issue #120 Phase 1.1). Never writes; + # findings are advisory — the applier/planner remain the only gate. + from . import lint as lint_mod + target = Path(args.file) if args.file else default_target() + try: + findings = lint_mod.lint_file(target) + except (OSError, ValueError) as exc: + print(f"error: {exc}", file=sys.stderr) + return 1 + print("\n".join(_header(False))) + print("") + print("\n".join(lint_mod.render_findings(findings))) + return 0 + + if args.wallpaper_palette is not None: + # Issue #120 Phase 2.4: wallpaper -> candidate accent, surfaced + # through the EXISTING inert scheme-suggestion mechanism (same + # constants, same renderer, same SUGGESTED_NOT_EXECUTED prefix). + from . import parser as parser_mod + from assistant.capabilities.genius import palette_extract as palette_mod + try: + data = Path(args.wallpaper_palette).read_bytes() + result = palette_mod.accent_from_png(data) + except (OSError, ValueError) as exc: + print(f"error: {exc}", file=sys.stderr) + return 1 + suggestions = list(parser_mod.SCHEME_SUGGESTIONS) + \ + list(parser_mod.WALLPAPER_SUGGESTIONS) + notes = [ + (f"derived from {args.wallpaper_palette}: dominant accent-like " + f"color {result['accent']} (k-means quantization in OKLab over " + f"{result['n_pixels']} sampled pixels; {result['selection']})"), + (f"WCAG contrast of the derived accent: on white " + f"{result['contrast']['on_white']['ratio']}:1, on black " + f"{result['contrast']['on_black']['ratio']}:1 — the scheme " + "system owns the actual change"), + parser_mod.SCHEME_NOTE, + "nothing was executed and nothing was written; these are inert suggestions only", + ] + print("\n".join(render_verdict( + {"verdict": "SUGGESTED", "suggestions": suggestions, "notes": notes}))) + return 0 + + if args.wizard: + # Issue #120 Phase 3 "setup wizards": pure AHP+TOPSIS over the + # shipped presets; renders a recommendation and writes nothing. + from . import wizard as wizard_mod + answers = None + if args.answers: + try: + answers = [int(x) for x in args.answers.split(",")] + except ValueError: + print("error: --answers must be comma-separated integers", + file=sys.stderr) + return 2 + elif args.text: + answers = [int(x) for x in args.text.split(",")] + if answers is not None: + try: + result = wizard_mod.run(answers) + except ValueError as exc: + print(f"error: {exc}", file=sys.stderr) + return 1 + print("\n".join(wizard_mod.render(result))) + return 0 + return wizard_mod.mainish() + + if args.explain is not None: + # Read-only explainability: never writes, never plans. + from . import explain as explain_mod + target = Path(args.file) if args.file else default_target() + try: + result = explain_mod.explain(args.explain, target) + except explain_mod.ExplainError as exc: + print(f"error: {exc}", file=sys.stderr) + return 1 + print("\n".join(_header(False))) + print("") + print(result["answer"]) + if result["cites"]: + print("grounded in: " + "; ".join(result["cites"])) + if not result["rule"]: + print( + "(value readback — no causal rule fired for this key; rules " + "needing live session state do not fire from the CLI)" + ) + # Multi-hop provenance (Phase 1.3): best-effort and read-only — + # missing/unreadable ledger or state files simply shorten the chain. + try: + from assistant.capabilities.brain.cli import DEFAULT_LEDGER + from assistant.capabilities.brain import state as brain_state + ledger_path = DEFAULT_LEDGER if Path(DEFAULT_LEDGER).exists() else None + bandit_state = None + state_file = Path(brain_state.DEFAULT_STATE) + if state_file.exists(): + try: + bandit_state = brain_state.load().get("preset_bandit") + except (OSError, ValueError): + bandit_state = None + if ledger_path is not None or bandit_state is not None: + prov = explain_mod.provenance( + args.explain, target, ledger_path=ledger_path, + bandit_state=bandit_state) + if prov["chain"]: + print("") + print("\n".join(explain_mod.render_provenance(prov))) + except ImportError: + pass # brain layer unavailable: value readback alone still answers + return 0 + + if args.history: + from . import history as history_mod + target = Path(args.file) if args.file else default_target() + try: + entries = history_mod.entries(target) + except history_mod.HistoryError as exc: + print(f"error: {exc}", file=sys.stderr) + return 1 + print("\n".join(_header(False))) + print("") + if not entries: + print("the undo history is empty (nothing has been applied yet)") + else: + print(f"undo history (newest first, {len(entries)} of " + f"{history_mod.MAX_ENTRIES} slots):") + for e in entries: + label = e.get("label") or "(unlabelled)" + print(f" #{e['id']} {e['at']} {label} " + f"({len(e.get('ops', []))} change(s))") + print("") + print("undo with --undo (newest N) or --undo-id ID; capture " + "one as a replayable macro with --macro-save NAME " + "(newest) or --from-id ID") + return 0 + + if args.undo is not None or args.undo_id is not None: + from . import history as history_mod + target = Path(args.file) if args.file else default_target() + try: + if args.undo_id is not None: + result = history_mod.undo_by_id(target, args.undo_id) + else: + result = history_mod.undo(target, args.undo) + except (history_mod.HistoryError, applier.ApplierError) as exc: + print(f"error: {exc}", file=sys.stderr) + return 1 + print("\n".join(_header(False))) + print("") + print(result.get("message", "")) + return 0 if result.get("restored", True) else 1 + + if args.macro is not None: + # C3: replay a captured APPROVED proposal sequence. The ops are + # plain planner ops (presets.preset_ops shape), so the replay + # rides the ordinary plan/render path; the ONLY bespoke rule is + # STRONGER consent — every macro apply needs the second consent + # (--confirm or interactive y/N), single-change macros included, + # because a replay's contents may no longer be in the user's head. + from . import history as _history + from . import macros as macros_mod + target = Path(args.file) if args.file else default_target() + try: + ops = macros_mod.macro_ops(target, args.macro) + except (macros_mod.MacroError, _history.HistoryError) as exc: + print(f"error: {exc}", file=sys.stderr) + return 1 + try: + plan = planner.plan(ops, target) + except planner.PlannerError as exc: + print(f"error: {exc}", file=sys.stderr) + return 1 + label = f"macro: {args.macro}" + if not args.apply: + print("\n".join(render_plan(plan, [], label, args.file, + False, None, None))) + return 0 + confirmed, _why = _confirm_multi(plan, args) + if not confirmed: + print( + "macro replays always need confirmation (re-run with " + "--confirm, or answer the interactive prompt); nothing " + "was written", + file=sys.stderr, + ) + return 1 + try: + apply_result = applier.apply(plan, target, write=True, + label=label) + except applier.ApplierError as exc: + print(f"error: {exc}", file=sys.stderr) + return 1 + print("\n".join(render_plan(plan, [], label, args.file, True, + apply_result, None))) + return 0 + + if args.macro_save is not None: + # C3: capture an APPROVED apply from the bounded history. Writes + # only the history file's macros key (the A3 undo_log precedent + # — same _save atomic path, no new write surface, the target + # file is not touched). + from . import history as _history + from . import macros as macros_mod + target = Path(args.file) if args.file else default_target() + try: + macro = macros_mod.save(target, args.macro_save, + args.from_id) + except (macros_mod.MacroError, _history.HistoryError) as exc: + print(f"error: {exc}", file=sys.stderr) + return 1 + print(f"captured macro {macro['name']!r}: {len(macro['ops'])} " + f"change(s) from history entry #{macro['from_id']} " + f"(label {macro['label']!r})") + print("replay with --macro NAME (dry-run preview; --apply still " + "needs --confirm)") + return 0 + + if args.macro_list: + from . import history as _history + from . import macros as macros_mod + target = Path(args.file) if args.file else default_target() + try: + saved = macros_mod.list_macros(target) + except (macros_mod.MacroError, _history.HistoryError) as exc: + print(f"error: {exc}", file=sys.stderr) + return 1 + print("\n".join(_header(False))) + print("") + if not saved: + print("no macros saved; capture an applied change with " + "--macro-save NAME") + else: + print(f"saved macros (oldest capture first, " + f"{len(saved)} of {macros_mod.MAX_MACROS} slots):") + for m in saved: + ops = ", ".join(f"{o['tool']}={o['value']!r}" + for o in m.get("ops", [])) + print(f" {m['name']:<24} {len(m.get('ops', []))} " + f"change(s) from #{m.get('from_id')}: {ops}") + print("") + print("replay with --macro NAME; every replay is re-approved " + "(--apply + --confirm)") + return 0 + + if args.macro_delete is not None: + from . import history as _history + from . import macros as macros_mod + target = Path(args.file) if args.file else default_target() + try: + result = macros_mod.delete(target, args.macro_delete) + except (macros_mod.MacroError, _history.HistoryError) as exc: + print(f"error: {exc}", file=sys.stderr) + return 1 + print(f"deleted macro {result['deleted']!r} " + f"({result['ops']} change(s), captured from history entry " + f"#{result['from_id']})") + return 0 + + if args.also_sources is not None and args.profile_save is None: + arg_parser.error("--also is only valid together with --profile-save") + + if args.profile is not None: + # F9: apply a saved profile. The composed ops are plain planner + # ops, so this rides the ordinary plan/render/confirm path — no + # bespoke writer. Conflicts the order resolved are listed on the + # preview so the consent is informed. + from . import history as _history + from . import profiles as profiles_mod + target = Path(args.file) if args.file else default_target() + try: + ops, conflicts = profiles_mod.profile_ops(target, args.profile) + except (profiles_mod.ProfileError, _history.HistoryError) as exc: + print(f"error: {exc}", file=sys.stderr) + return 1 + try: + plan = planner.plan(ops, target) + except planner.PlannerError as exc: + print(f"error: {exc}", file=sys.stderr) + return 1 + label = f"profile: {args.profile}" + if not args.apply: + print("\n".join(render_plan(plan, [], label, args.file, + False, None, None))) + for c in conflicts: + print(f"conflict (later source wins): {c['tool']}: " + f"{c['dropped']['value']!r} " + f"({c['dropped']['from']}) overridden by " + f"{c['kept']['value']!r} ({c['kept']['from']})") + return 0 + confirmed, _why = _confirm_multi(plan, args) + if not confirmed: + print( + "multi-change profiles need the second consent (re-run " + "with --confirm, or answer the interactive prompt); " + "nothing was written", + file=sys.stderr, + ) + return 1 + try: + apply_result = applier.apply(plan, target, write=True, + label=label) + except applier.ApplierError as exc: + print(f"error: {exc}", file=sys.stderr) + return 1 + print("\n".join(render_plan(plan, [], label, args.file, True, + apply_result, None))) + return 0 + + if args.profile_save is not None: + # F9: save a named composition. Sources resolve against the live + # registry and saved stores NOW; writes only the history file's + # profiles key (same bounded store as macros). Target untouched. + from . import history as _history + from . import profiles as profiles_mod + target = Path(args.file) if args.file else default_target() + name, first = args.profile_save + specs = [first] + list(args.also_sources or []) + try: + sources = [profiles_mod.parse_source(s) for s in specs] + entry = profiles_mod.save(target, name, sources) + except (profiles_mod.ProfileError, _history.HistoryError) as exc: + print(f"error: {exc}", file=sys.stderr) + return 1 + print(f"saved profile {entry['name']!r} " + f"({len(entry['sources'])} source(s))") + print("preview with --profile " + entry["name"] + + " (dry-run; --apply still needs --confirm)") + return 0 + + if args.profile_list: + from . import history as _history + from . import profiles as profiles_mod + target = Path(args.file) if args.file else default_target() + try: + saved = profiles_mod.list_profiles(target) + except (profiles_mod.ProfileError, _history.HistoryError) as exc: + print(f"error: {exc}", file=sys.stderr) + return 1 + print("\n".join(_header(False))) + print("") + if not saved: + print("no profiles saved; compose one with --profile-save " + "NAME SRC [--also SRC ...]") + else: + print(f"saved profiles (oldest first, {len(saved)} of " + f"{profiles_mod.MAX_PROFILES} slots):") + for p in saved: + srcs = ", ".join( + (f"{s.get('kind')}:{s.get('name')}" if s.get('kind') != 'call' + else f"{s.get('tool')}={s.get('value')!r}") + for s in p.get("sources", [])) + print(f" {p['name']:<24} {len(p.get('sources', []))} " + f"source(s): {srcs}") + print("") + print("preview with --profile NAME; apply with --profile NAME " + "--apply --confirm") + return 0 + + if args.profile_show is not None: + from . import history as _history + from . import profiles as profiles_mod + target = Path(args.file) if args.file else default_target() + try: + print("\n".join(profiles_mod.render_profile_lines( + target, args.profile_show))) + except (profiles_mod.ProfileError, _history.HistoryError) as exc: + print(f"error: {exc}", file=sys.stderr) + return 1 + return 0 + + if args.profile_diff is not None: + from . import history as _history + from . import profiles as profiles_mod + target = Path(args.file) if args.file else default_target() + name_a, name_b = args.profile_diff + try: + result = profiles_mod.diff(target, name_a, name_b) + except (profiles_mod.ProfileError, _history.HistoryError) as exc: + print(f"error: {exc}", file=sys.stderr) + return 1 + rows = result["rows"] + if not rows: + print(f"profiles {name_a!r} and {name_b!r} are effectively " + f"identical") + else: + print(f"diff {name_a!r} -> {name_b!r} " + f"({len(rows)} differing tool(s)):") + for row in rows: + if row["kind"] == "only_a": + print(f" only in {name_a!r}: {row['tool']} = " + f"{row['a']!r}") + elif row["kind"] == "only_b": + print(f" only in {name_b!r}: {row['tool']} = " + f"{row['b']!r}") + else: + print(f" changed: {row['tool']} {row['a']!r} -> " + f"{row['b']!r}") + return 0 + + if args.profile_delete is not None: + from . import history as _history + from . import profiles as profiles_mod + target = Path(args.file) if args.file else default_target() + try: + result = profiles_mod.delete(target, args.profile_delete) + except (profiles_mod.ProfileError, _history.HistoryError) as exc: + print(f"error: {exc}", file=sys.stderr) + return 1 + print(f"deleted profile {result['deleted']!r} " + f"({result['sources']} source(s))") + return 0 + + if args.profile_whatif is not None: + # F11: composite what-if for a saved profile. Read-only: plan, + # project through the cited interaction graph per source and for + # the composite, run the applier's own sanity checks against the + # projected state, and render. Nothing is applied or written. + from . import history as _history + from . import planner as _planner_mod + from . import profile_preview + from . import profiles as profiles_mod + target = Path(args.file) if args.file else default_target() + try: + view = profile_preview.build(target, args.profile_whatif) + except (profiles_mod.ProfileError, _history.HistoryError, + _planner_mod.PlannerError) as exc: + print(f"error: {exc}", file=sys.stderr) + return 1 + print("\n".join(profile_preview.render(view))) + return 0 + + if args.monitor is not None and args.file is not None: + arg_parser.error( + "--monitor and --file are mutually exclusive: --monitor " + "resolves the target to that screen's override file") + + if args.monitor is not None: + # F20: --monitor is a TARGET RESOLVER — the ordinary machinery + # (parser, planner, applier, backup sibling, history) then runs + # against the screen's override file unchanged. Naming a screen + # explicitly is the consent for its override directory to exist + # (upstream creates monitors// on the first per-screen + # write too); the applier's own no-directory-creation rule is + # untouched. + from . import monitors as monitors_mod + try: + resolved = monitors_mod.resolve_target( + default_target(), args.monitor) + except ValueError as exc: + arg_parser.error(str(exc)) + resolved.parent.mkdir(parents=True, exist_ok=True) + args.file = str(resolved) + + if args.monitors: + # F20 read-only report: discovered override files + the global + # monitor-behavior tools, cited. Never writes. + from . import monitors as monitors_mod + target = Path(args.file) if args.file else default_target() + discovered = monitors_mod.discover(target) + print("monitor-aware planning (F20) — read-only report") + print("") + print("per-screen override files (upstream forScreen layer, " + "shell/plugin/src/Caelestia/Config/rootnodes.cpp:87 + " + "common.cpp:15):") + if not discovered: + print(f" none yet under {monitors_mod.monitors_dir(target)} — " + "target one with --monitor SCREEN (the file is created " + "on the first --apply, like any config target)") + for d in discovered: + if d.get("error"): + print(f" {d['screen']}: {d['error']}") + continue + print(f" {d['screen']}: {d['managed_keys']} registry-managed " + f"key(s), {d['unknown_keys']} unknown") + print("") + print("global tools that select monitor behavior (same schema, " + "cited):") + for row in monitors_mod.monitor_behavior_tools(): + enum = (f" {'|'.join(row['enum'])}" if row.get("enum") else "") + cite = row["citations"][0][0] if row["citations"] else "-" + print(f" {row['name']:<28} {row['path']} " + f"(default {row['default']!r}{enum}) [{cite}]") + print("") + print("NOTE: connected-screen enumeration lives in " + "Quickshell/Wayland; this report only sees override files " + "that already exist. per-screen values use the SAME " + "planner/confirm/undo gates as the global config.") + return 0 + + if args.audit_env: + # F21: the environment audit — one read-only pass composing the + # existing engines. Exit 1 only on CRITICAL findings (states the + # applier itself would refuse); WARN/INFO never block. + from datetime import datetime as _dt + from . import envaudit + target = Path(args.file) if args.file else default_target() + result = envaudit.audit(target, now=_dt.now()) + print("\n".join(envaudit.render_lines(result))) + return 1 if result["critical"] else 0 + + if args.gen_catalog: + # F23: generated community docs. Byte-identity is the contract: + # the committed files are OUTPUT of this module, and a registry + # change that outdates them fails here instead of shipping + # stale docs (the gen_adapter --verify discipline). + from . import catalog + if args.gen_verify: + problems = catalog.verify() + if problems: + for problem in problems: + print(f"STALE: {problem}", file=sys.stderr) + print("catalog verify FAILED", file=sys.stderr) + return 1 + print("catalog verify OK: generated artifacts are " + "byte-identical") + return 0 + written = catalog.generate() + for rel, path in written.items(): + print(f"wrote {path} ({rel})") + print("verify with --gen-catalog --verify") + return 0 + + if args.a11y_recipe: + from . import plain as plain_mod + print("\n".join(plain_mod.render_recipe())) + return 0 + + if args.env_save is not None: + # F17: snapshot the current environment. Writes only the history + # file's bounded "environments" key; the target is untouched. + from . import environments as env_mod + target = Path(args.file) if args.file else default_target() + try: + entry = env_mod.save(target, args.env_save) + except env_mod.EnvironmentError as exc: + print(f"error: {exc}", file=sys.stderr) + return 1 + print(f"saved environment {entry['name']!r}: " + f"{entry['paths']} value(s), hash " + f"{entry['content_hash'][:12]}..., " + f"{len(entry.get('macros', []))} macro(s), " + f"{len(entry.get('profiles', []))} profile(s) metadata") + print("diff with --env-diff " + entry["name"] + + "; restore with --env-restore (dry-run first)") + return 0 + + if args.env_list: + from . import environments as env_mod + target = Path(args.file) if args.file else default_target() + saved = env_mod.list_environments(target) + print("\n".join(_header(False))) + print("") + if not saved: + print("no environments saved; snapshot one with " + "--env-save NAME") + else: + print(f"saved environments (oldest first, {len(saved)} of " + f"{env_mod.MAX_ENVIRONMENTS} slots):") + for e in saved: + print(f" {e['name']:<24} {e.get('created_at', '?')} " + f"hash {str(e.get('content_hash'))[:12]}..." + + (" [imported]" if e.get("imported") else "")) + print("") + print("restore with --env-restore NAME (dry-run first; " + "--apply --confirm to write)") + return 0 + + if args.env_show is not None: + from . import environments as env_mod + target = Path(args.file) if args.file else default_target() + try: + env = env_mod.get(target, args.env_show, verify=True) + except env_mod.EnvironmentError as exc: + print(f"error: {exc}", file=sys.stderr) + return 1 + print(f"environment {env['name']!r}: " + f"created {env.get('created_at', '?')}, hash " + f"{str(env.get('content_hash'))[:12]}... VERIFIED, " + f"captured against registryTools=" + f"{env.get('registry_tools')} " + f"(local now: {len(registry.TOOL_SPECS)})") + if env.get("imported"): + print(f" imported bundle; drift: {env.get('import_drift')}; " + f"unknown paths: " + f"{len(env.get('import_unknown_paths', []))}") + print(f" metadata: {len(env.get('macros', []))} macro(s), " + f"{len(env.get('profiles', []))} profile(s) " + "(restored separately through their own commands)") + return 0 + + if args.env_diff is not None: + from . import environments as env_mod + target = Path(args.file) if args.file else default_target() + try: + diff = env_mod.diff_to_ops(target, args.env_diff) + except env_mod.EnvironmentError as exc: + print(f"error: {exc}", file=sys.stderr) + return 1 + if diff["identical"]: + print(f"environment {args.env_diff!r} matches the live " + f"config on every registry-managed path") + else: + print(f"restoring {args.env_diff!r} would " + f"({len(diff['set_ops'])} set / " + f"{len(diff['reset_ops'])} reset-to-default op(s)):") + for op in diff["set_ops"] + diff["reset_ops"]: + print(f" {op['raw']}") + for label, keys in (("only in SNAPSHOT (untouched by the " + "restore — not registry-managed)", + diff["unknown_only_in_snapshot"]), + ("only in LIVE file (untouched)", + diff["unknown_only_in_live"])): + if keys: + print(f"{label}: {', '.join(keys)}") + return 0 + + if args.env_restore is not None: + # F17: restore = the diff becomes a PLAIN planned multi-change + # apply through the standard gates. No bespoke writer. + from . import environments as env_mod + target = Path(args.file) if args.file else default_target() + try: + diff = env_mod.diff_to_ops(target, args.env_restore) + ops = diff["set_ops"] + diff["reset_ops"] + if not ops: + print(f"environment {args.env_restore!r} already matches " + "the live config — no changes needed") + return 0 + plan = planner.plan(ops, target) + except env_mod.EnvironmentError as exc: + print(f"error: {exc}", file=sys.stderr) + return 1 + except planner.PlannerError as exc: + print(f"error: {exc}", file=sys.stderr) + return 1 + label = f"env restore: {args.env_restore}" + if not args.apply: + print("\n".join(render_plan(plan, [], label, args.file, + False, None, None))) + return 0 + confirmed, _why = _confirm_multi(plan, args) + if not confirmed: + print( + "multi-change restores need the second consent (re-run " + "with --confirm, or answer the interactive prompt); " + "nothing was written", + file=sys.stderr, + ) + return 1 + try: + apply_result = applier.apply(plan, target, write=True, + label=label) + except applier.ApplierError as exc: + print(f"error: {exc}", file=sys.stderr) + return 1 + print("\n".join(render_plan(plan, [], label, args.file, True, + apply_result, None))) + return 0 + + if args.env_delete is not None: + from . import environments as env_mod + target = Path(args.file) if args.file else default_target() + try: + result = env_mod.delete(target, args.env_delete) + except env_mod.EnvironmentError as exc: + print(f"error: {exc}", file=sys.stderr) + return 1 + print(f"deleted environment {result['deleted']!r}") + return 0 + + if args.env_export is not None: + # F18: export a verified environment as a portable bundle. The + # ONLY file written is the caller-chosen --to path. + from . import environments as env_mod + target = Path(args.file) if args.file else default_target() + if not args.to: + arg_parser.error("--env-export needs --to PATH") + try: + bundle = env_mod.export_bundle(target, args.env_export) + except env_mod.EnvironmentError as exc: + print(f"error: {exc}", file=sys.stderr) + return 1 + Path(args.to).write_text(json.dumps(bundle, indent=2, sort_keys=True) + + "\n", encoding="utf-8") + print(f"exported environment {args.env_export!r} to {args.to} " + f"(schema {bundle['schema']}, hash verified)") + return 0 + + if args.env_import is not None: + # F18: import is REVIEW-ONLY: the bundle lands as a new stored + # snapshot (marked imported, drift measured); nothing is applied. + from . import environments as env_mod + target = Path(args.file) if args.file else default_target() + if not args.as_name: + arg_parser.error("--env-import needs --as NAME") + try: + bundle = json.loads(Path(args.env_import).read_text( + encoding="utf-8")) + except (OSError, json.JSONDecodeError) as exc: + print(f"error: cannot read the bundle: {exc}", file=sys.stderr) + return 1 + try: + entry = env_mod.import_bundle(target, bundle, args.as_name) + except env_mod.EnvironmentError as exc: + print(f"error: {exc}", file=sys.stderr) + return 1 + print(f"imported environment {entry['name']!r} (review-only: " + f"NOTHING was applied): drift {entry['import_drift']}, " + f"unknown paths " + f"{len(entry['import_unknown_paths'])}") + print("preview with --env-diff " + entry["name"] + + "; restore with --env-restore if you want it") + return 0 + + if args.list_tools: + # §5.1: --list-tools ignores TEXT (and writes nothing, ever). + from . import plain as plain_mod + if args.group is not None: + groups = tuple(registry.GROUPS) + if args.group not in groups: + print( + f"error: unknown group {args.group!r}; available groups: " + + ", ".join(groups), + file=sys.stderr, + ) + return 1 + if plain_mod.plain_requested( + True if getattr(args, "plain", False) else None): + # F24 linear form: one record per tool, one fact per line. + from assistant.adapters.caelestia.registry import TOOL_SPECS, TOOL_COUNT + wanted = (lambda s: s.group == args.group + if args.group is not None else lambda s: True) + specs = [s for s in TOOL_SPECS if wanted(s)] + print(f"tool registry: {TOOL_COUNT} tools " + f"({len(specs)} shown)") + rows = ([ + ("tool", s.name), ("path", s.path), ("kind", s.kind), + ("range", s.minimum if s.minimum is not None else "-" if + not s.enum else " | ".join(map(str, s.enum))), + ("max", s.maximum if s.maximum is not None else "-"), + ("default", s.default if s.default is not None else "-"), + ] for s in specs) + for line in plain_mod.to_linear_rows( + ("tool", "path", "kind", "range", "max", "default"), + [tuple(r[1] for r in row) for row in rows]): + plain_mod.assert_plain_safe(line) + print(line) + return 0 + print("\n".join(_list_tools_lines(args.group))) + return 0 + + if args.tool is not None: + spec = tool_by_name(args.tool) + if spec is None: + print( + f"error: unknown tool {args.tool!r}; run --list-tools to see every tool", + file=sys.stderr, + ) + near = registry.suggest_tools(args.tool, max_distance=2) + if near: + shown = ", ".join(f"{name} (distance {dist})" + for name, dist in near[:3]) + print(f"did you mean: {shown}", file=sys.stderr) + return 1 + print("\n".join(_tool_card(spec))) + return 0 + + if args.restore: + target = Path(args.file) if args.file else default_target() + try: + result = applier.restore(target) + except applier.ApplierError as exc: + print(f"error: {exc}", file=sys.stderr) + return 1 + print("\n".join(_header(False))) + print("") + print(result["message"]) + return 0 + + if args.text is None and args.calls is None: + arg_parser.error( + "TEXT is required unless --list-tools, --tool, --restore, --call, " + "--explain, --history, --undo, --lint or a --macro* flag is given" + ) + + target = Path(args.file) if args.file else default_target() + file_arg = args.file + + call_args: Optional[List[str]] = None + cli_errors: Dict[int, Dict[str, Any]] = {} + + if args.calls is not None: + # Direct tool addressing: compose the ops here, then ride + # the exact same plan/render/--apply/--restore path as NL requests. + try: + ops, cli_errors = _compose_call_ops(args.calls) + except ValueError as exc: + arg_parser.error(str(exc)) + call_args = list(args.calls) + parse_notes: List[str] = [] + text = "" + else: + result = parser.parse(args.text) + verdict = result["verdict"] + + if verdict != "INTENT": + if args.json: + print(json.dumps(result, indent=2)) + else: + print("\n".join(render_verdict(result))) + return 0 + + ops = result["ops"] + parse_notes = list(result.get("notes", [])) + text = args.text + + try: + plan = planner.plan(ops, target) + except planner.PlannerError as exc: + print(f"error: {exc}", file=sys.stderr) + return 1 + + if cli_errors: + _splice_call_errors( + plan, cli_errors, total=len(args.calls) if args.calls else 0 + ) + + if not args.apply: + if args.json: + payload = dict(plan) + payload["notes"] = parse_notes + list(plan.get("notes", [])) + print(json.dumps(payload, indent=2)) + else: + print("\n".join( + render_plan(plan, parse_notes, text, file_arg, False, None, call_args) + )) + if args.calls is not None and plan.get("errors"): + # A direct invocation with a bad name/value is a caller error, + # not an honest NL verdict: exit 1 even in dry-run. + print( + f"error: {len(plan['errors'])} --call entry(s) rejected; " + "nothing was written", + file=sys.stderr, + ) + return 1 + return 0 + + # --apply: the gated write path. + if plan.get("apply_blocked"): + print( + "error: apply refused — the plan contains rejected or type-mismatched entries; " + "nothing was written", + file=sys.stderr, + ) + if args.json: + payload = dict(plan) + payload["notes"] = parse_notes + list(plan.get("notes", [])) + print(json.dumps(payload, indent=2)) + return 1 + + # Issue #120's confirmation rule: a request that resolves to MORE THAN + # ONE tool call is previewed and must be confirmed before anything is + # written; single-setting requests apply directly (exactly as the + # issue frames it). + applicable_count = sum( + 1 for e in plan.get("entries", []) + if not e.get("error") and not e.get("no_op") + ) + if applicable_count > 1: + confirmed, why = _confirm_multi(plan, args) + if not confirmed: + if args.json: + payload = dict(plan) + payload["notes"] = parse_notes + list(plan.get("notes", [])) + payload["confirmation"] = "required" + print(json.dumps(payload, indent=2)) + else: + print("\n".join( + render_plan(plan, parse_notes, text, file_arg, False, + None, call_args))) + print("") + print(why) + return 1 + + try: + label = text if text else "direct --call invocation" + apply_result = applier.apply(plan, target, write=True, label=label) + except applier.ApplierError as exc: + print(f"error: {exc}", file=sys.stderr) + return 1 + + if args.json: + payload = dict(plan) + payload["notes"] = parse_notes + list(plan.get("notes", [])) + payload["applied"] = { + "written": apply_result.get("written", False), + "changes": apply_result.get("changes", 0), + } + print(json.dumps(payload, indent=2)) + return 0 + + print("\n".join( + render_plan(plan, parse_notes, text, file_arg, True, apply_result, call_args) + )) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/plugins/caelestia-assistant/assistant/capabilities/settings/consequences.py b/plugins/caelestia-assistant/assistant/capabilities/settings/consequences.py new file mode 100644 index 0000000..4120028 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/capabilities/settings/consequences.py @@ -0,0 +1,322 @@ +"""settings.consequences — what-if consequence-graph mode (phase 2.7). + +Implements the former proposals/2026-09-26-c-whatif-consequences.md +(pruned in exponential-build-3 Phase 2 once implemented — this +docstring carries the design) as specified: +a HAND-CURATED, citation-backed table of KNOWN cross-key interactions in +the shell's own code; a bounded, cycle-safe projection over a candidate +op list; the existing AC-3 conflict check extended to see induced +values; and a read-only what-if surface that renders consequences and +reversibility BEFORE the user consents. + +The honesty rule (the proposal's own): a cited-edge list can be WRONG if +upstream changes — so every edge's cited file:line is re-verified +against the checkout by test (the registry's citation-guard pattern, +extended here). The consequence universe is EXACTLY this table: +bounded, auditable, growable by reviewed diffs — NOT a general model, +and NOT "fake open-endedness". + +Purely read-only: this module reads op lists and the edge table; it +never writes, never applies, and nothing here is reachable from an NL +request that would apply — the parser/planner/applier spine is +untouched. +""" + +from __future__ import annotations + +from typing import Any, Dict, List, Optional, Sequence, Tuple + +__all__ = ["EDGES", "project", "render"] + +# --------------------------------------------------------------------------- +# The interaction graph: every edge cites the shipped code that makes it +# true. Line numbers refer to the caelestia-kde checkout this registry is +# built from (verified by assistant/settings/tests/test_consequences.py — +# an edge whose cited line no longer matches its claimed content is a +# test failure, never a silent stale edge). +# +# Edge shape: {trigger_path, trigger_when, effect_path, effect, direction, +# citation, confidence, note, effect_value} +# trigger_when: the value/condition of the trigger that arms the edge +# effect: what the trigger does to the effect path (human words) +# effect_value: the concrete value the edge induces on effect_path, when +# the edge sets one (machine-readable — feeds the AC-3 +# induced-value check; edges that only annotate an INERT or +# CLAMP state carry no effect_value because they change no +# shell.json value) +# --------------------------------------------------------------------------- + +EDGES: Tuple[Dict[str, Any], ...] = ( + { + "id": "transparency-off-forces-blur-off", + "trigger_path": "appearance.transparency.enabled", + "when": {"op_is": False}, + "effect_path": "appearance.blur", + "effect": "Nexus toggles it off with you (the toggle handler " + "sets blur = false when transparency goes off)", + "effect_value": False, + "citation": "shell/modules/nexus/pages/wallandstyle/AppearancePage.qml:132-137", + "claimed_content": "onToggled: { GlobalConfig.appearance.transparency" + ".enabled = checked if (!checked) { " + "GlobalConfig.appearance.blur = false } }", + "confidence": "high", + }, + { + "id": "blur-inert-without-transparency", + "trigger_path": "appearance.blur", + "when": {"op_is": True, "requires": {"path": "appearance.transparency.enabled", + "equals": False}}, + "effect_path": "appearance.blur", + "effect": "INERT: the blur regions gate on transparency.enabled " + "&& blur together, so blur does nothing until " + "transparency is re-enabled", + "citation": "shell/modules/drawers/blur/BlurOffsets.qml:17", + "claimed_content": "isActive: target && target.visible && target." + "opacity > 0 && GlobalConfig.appearance." + "transparency.enabled && GlobalConfig." + "appearance.blur", + "confidence": "high", + }, + { + "id": "bar-scale-floor", + "trigger_path": "bar.scale", + "when": {"op_below": 0.6}, + "effect_path": "bar.scale (effective)", + "effect": "CLAMPED at 0.6 at render time: the bar wrapper floors " + "the scale with Math.max(0.6, ...) — the shell.json " + "value you asked for is not what renders", + "citation": "shell/modules/bar/BarWrapper.qml:24", + "claimed_content": "readonly property real barScale: Math.max(0.6, " + "!isNaN(Config.bar.scale) ? Config.bar.scale : " + "1.0)", + "confidence": "high", + }, + { + "id": "dodge-needs-persistent", + "trigger_path": "bar.dodgeWindows", + "when": {"op_is": True, "requires": {"path": "bar.persistent", + "equals": False}}, + "effect_path": "bar.dodgeWindows (effective)", + "effect": "INERT: dodge requires persistent windows " + "(dodgeEnabled = dodgeWindows && persistent && !disabled)", + "citation": "shell/modules/bar/BarWrapper.qml:27", + "claimed_content": "readonly property bool dodgeEnabled: Config.bar." + "dodgeWindows && Config.bar.persistent && " + "!disabled", + "confidence": "high", + }, + { + "id": "border-below-padding-floor", + "trigger_path": "border.thickness", + "when": {"op_below": 2.5, + "approximate": "the floor is Tokens.padding.small, a QML " + "singleton constant; ops at or below ~2 are " + "where the floor starts binding"}, + "effect_path": "bar padding (effective)", + "effect": "the bar's padding floors at Tokens.padding.small — a " + "thinner border does not shrink the bar's padding below " + "that floor", + "citation": "shell/modules/bar/BarWrapper.qml:25", + "claimed_content": "readonly property int padding: Math.max(Tokens." + "padding.small, Config.border.thickness)", + "confidence": "medium", + }, +) + + +# --------------------------------------------------------------------------- +# Projection. +# --------------------------------------------------------------------------- + + +def project(ops: Sequence[Dict[str, Any]], + current: Optional[Dict[str, Any]] = None, + max_derived: int = 24) -> Dict[str, Any]: + """Project a candidate op list through the interaction graph. + + ``current``: the live file's values (path -> value) for evaluating + cross-key conditions (the caller reads it read-only; None means + cross-key edges that need the live state stay silent — honest). + + Returns (read-only): + - ``derived``: effects the user did NOT ask for, each with its edge, + citation, and confidence — bounded at ``max_derived``; + - ``annotated_ops``: the ops with a ``downstream`` count; + - ``conflicts``: the EXISTING AC-3 conflict check + (optimize.check_conflicts) over the candidate list; + - ``reversibility``: every planned op goes through the journaled + applier (backup + undo history), stated plainly. + """ + ops = [dict(op) for op in ops] + derived: List[Dict[str, Any]] = [] + + from assistant.adapters.caelestia.registry import tool_by_name + + def path_of(tool_name: str) -> Optional[str]: + spec = tool_by_name(str(tool_name)) + return spec.path if spec else None + + def path_value(path: str) -> Any: + """The value a path will have after the ops: the LAST op touching + it wins, else the live value.""" + for op in reversed(ops): + if path_of(str(op.get("tool", ""))) == path: + return op.get("value") + if isinstance(current, dict): + node: Any = current + for piece in path.split("."): + if isinstance(node, dict): + node = node.get(piece) + else: + return None + return node + return None + + def edge_fires(edge: Dict[str, Any], op: Dict[str, Any]) -> bool: + trigger = edge.get("trigger_path") + if path_of(str(op.get("tool", ""))) != trigger: + return False + when = edge.get("when") or {} + value = op.get("value") + if "op_is" in when and value is not when["op_is"]: + return False + if "op_below" in when and not ( + isinstance(value, (int, float)) and not isinstance(value, bool) + and value < when["op_below"]): + return False + requires = when.get("requires") + if requires: + live = path_value(requires["path"]) + if live is None or live != requires["equals"]: + return False + return True + + for op in ops: + if len(derived) >= max_derived: + break # the projection is a VIEW, never a wall of effects + for edge in EDGES: + if any(row["edge"] == edge["id"] for row in derived): + continue + if edge_fires(edge, op): + derived.append({ + "from_op": str(op.get("tool", "")), + "edge": edge["id"], + "effect_path": edge["effect_path"], + "effect": edge["effect"], + "trigger_when": _describe_when(edge), + "citation": edge["citation"], + "confidence": edge["confidence"], + }) + + annotated: List[Dict[str, Any]] = [] + for op in ops: + tool = str(op.get("tool", "")) + count = sum(1 for row in derived if row["from_op"] == tool) + row = dict(op) + row["downstream"] = count + annotated.append(row) + + conflicts: List[Dict[str, Any]] = [] + # (1) The EXISTING AC-3 check (optimize.check_conflicts, already + # shipped) over the candidate list: constraint propagation over the + # registry domains — an out-of-domain request is refused with its + # surviving domain, exactly as the planner would refuse it. Zero user + # constraints still validates requested values against the legal + # domains (the check's own semantics). + try: + from . import optimize + + optimize.check_conflicts(ops, ()) + except optimize.ConstraintError as exc: + conflicts.append({"verdict": "UNSUPPORTED", + "reason": str(exc)}) + except Exception: + pass # the conflict check must never break the view + # (2) The proposal's extension: the AC-3 view must also see INDUCED + # values. An edge that fires sets effect_path := effect_value; if the + # user ALSO requested a different value for that same path in this + # very op list, the shell will flip their request off — that is a + # conflict the flat plan never shows. + for row in derived: + edge = next((e for e in EDGES if e["id"] == row["edge"]), None) + if not edge or "effect_value" not in edge: + continue + for op in ops: + if path_of(str(op.get("tool", ""))) == edge["effect_path"] \ + and op.get("value") != edge["effect_value"]: + conflicts.append({ + "verdict": "INDUCED-CONFLICT", + "reason": f"{op.get('tool')}={op.get('value')!r} is " + f"requested, but edge {edge['id']} induces " + f"{edge['effect_path']}=" + f"{edge['effect_value']!r} — the shell's own " + f"handler wins; the requested value will not " + f"hold", + "cited": edge["citation"], + }) + + return { + "n_ops": len(ops), + "derived": derived, + "annotated_ops": annotated, + "conflicts": conflicts, + "reversibility": { + "all_journaled": True, + "note": "every planned change applies through the applier's " + "backup + undo history (undo: caelestia-assist " + "settings --undo); the what-if view itself writes " + "nothing", + }, + "note": "the consequence universe is exactly the cited edge table " + f"({len(EDGES)} edges) — bounded, auditable, never a " + "general model", + } + + +def _describe_when(edge: Dict[str, Any]) -> str: + when = edge.get("when") or {} + parts = [] + if "op_is" in when: + parts.append(f"set to {when['op_is']!r}") + if "op_below" in when: + parts.append(f"below {when['op_below']}") + requires = when.get("requires") + if requires: + parts.append(f"while {requires['path']} is {requires['equals']!r}") + return "; ".join(parts) or "always for this path" + + +# --------------------------------------------------------------------------- +# Rendering. +# --------------------------------------------------------------------------- + + +def render(projection: Dict[str, Any], title: str = "what-if") -> List[str]: + """Text rendering of one projection (nodes, cited edges, conflicts, + reversibility) — the pre-consent artifact the user actually reads.""" + lines = [f"{title} — projected consequences (read-only view, nothing " + "is applied):", + f" candidate ops: {projection['n_ops']}"] + derived = projection.get("derived") or [] + if derived: + lines.append(f" derived effects you did NOT ask for ({len(derived)}):") + for row in derived: + lines.append(f" - {row['from_op']} ({row['trigger_when']}) " + f"-> {row['effect_path']}") + lines.append(f" {row['effect']}") + lines.append(f" cited: {row['citation']} " + f"[{row['confidence']}]") + else: + lines.append(" derived effects: none in the known interaction " + "table for these ops") + conflicts = projection.get("conflicts") or [] + if conflicts: + lines.append(f" constraint conflicts ({len(conflicts)}):") + for row in conflicts: + lines.append(f" - {row}") + else: + lines.append(" constraint check: no conflict in the candidate list") + reversibility = projection.get("reversibility") or {} + lines.append(f" reversibility: {reversibility.get('note', 'n/a')}") + lines.append(f" {projection.get('note', '')}") + return lines diff --git a/plugins/caelestia-assistant/assistant/capabilities/settings/curations.py b/plugins/caelestia-assistant/assistant/capabilities/settings/curations.py new file mode 100755 index 0000000..f1cff54 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/capabilities/settings/curations.py @@ -0,0 +1,675 @@ +"""Safety classification and grouping rules for the settings tool registry. + +The generated-registry pipeline's curated data. Pure data + pure functions: no I/O, no +environment, no execution, no network. Every rule carries the reason that +lands in tools.json's ``not_exposed`` table, so the archive's manifest can +cite exactly why each leaf is (or is not) a tool. + +THE MECHANICAL EXPOSURE RULE (build_registry.py implements it): +a leaf becomes a tool IFF ALL hold: + (a) it is a serialized scalar leaf of the ConfigRoot tree (kind=scalar; + type bool/int/qreal/QString/enum) — lists, maps, unions, subobjects + are never tools; + (b) a shipped Nexus control touches it (ui_ranges_data.UI_RANGES) — the + conservative line: no UI row, no tool. UI-less bools with + live QML consumers stay unexposed rather than guessed + (recorded in not_exposed with this reason); every core tool also has a + UI row, so nothing regresses; + (c) it fails none of the EXCLUSION rules below. + +VALIDATION DERIVATION (exactly as the shipped QML declares it): +- Stepper/DoubleStepper/Slider rows: adopt min/max(/step) verbatim + (sliders are normalized 0..1 by StyledSlider.qml:152,173); +- SelectRow rows: adopt the verbatim enum list; +- ToggleRow rows: bool; +- FontCard rows: kind "string" (font family), max 64 chars, non-empty; +- any other control type (list editors, chips, free-text fields, ...): + not a scalar tool — excluded with the control type in the reason. + +Upstream's C++ declares type + default only (type-only validation hook, +Settings/macros.hpp SETTINGS_PROPERTY_IMPL) — the ranges here are the +shipped UI's own, which is what issue #120 asks tools to enforce +("If a value falls outside the supported range, it simply isn't applied"). +""" + +from __future__ import annotations + +import re +from typing import Any, Callable, Dict, List, Optional, Tuple + +from .ui_ranges_data import UI_RANGES + +# --------------------------------------------------------------------------- +# Group slugs, in display order. A tool's group is derived from its dotted +# path by GROUP_RULES (first match wins). +# --------------------------------------------------------------------------- + +GROUPS: Tuple[str, ...] = ( + "bar", + "dock", + "appearance", + "effects", + "animations", + "notifications", + "launcher", + "lockscreen", + "wallpaper-scheme", + "overview", + "osd", + "dashboard", + "sidebar", + "nexus", + "border", + "general", + "services", + "utilities", + "audio", + "ai", +) + +_EFFECTS_PATHS = frozenset(( + "appearance.blur", + "appearance.blurMask", + "appearance.pitchBlack", + "appearance.islands", + "appearance.ambientColor", + "appearance.ambientOpacity", + "appearance.transparency.enabled", + "appearance.transparency.base", + "appearance.transparency.layers", +)) + +GROUP_RULES: Tuple[Tuple[str, str], ...] = ( + ("dock", "bar.dock."), + ("animations", "appearance.anim."), + ("effects", "\x00effects-exact\x00"), # marker resolved in group_for() + ("appearance", "appearance."), + ("notifications", "notifs."), + ("launcher", "launcher."), + ("lockscreen", "lock."), + ("wallpaper-scheme", "background."), + ("overview", "overview."), + ("osd", "osd."), + ("dashboard", "dashboard."), + ("sidebar", "sidebar."), + ("nexus", "nexus."), + ("border", "border."), + ("general", "general."), + ("services", "services."), + ("utilities", "utilities."), + ("audio", "audio."), + ("ai", "ai."), + ("bar", "bar."), +) + + +def group_for(path: str) -> str: + """Feature-area slug for a dotted config path (first rule wins).""" + if path in _EFFECTS_PATHS: + return "effects" + for slug, prefix in GROUP_RULES: + if path.startswith(prefix): + return slug + return "general" + + +GROUP_TITLES: Dict[str, str] = { + "bar": "Bar / taskbar", + "dock": "Dock", + "appearance": "Appearance (scales, fonts)", + "effects": "Blur, transparency & effects", + "animations": "Animations", + "notifications": "Notifications", + "launcher": "Launcher", + "lockscreen": "Lock screen", + "wallpaper-scheme": "Wallpaper & colour scheme", + "overview": "Overview", + "osd": "On-screen display", + "dashboard": "Dashboard", + "sidebar": "Sidebar", + "nexus": "Nexus (settings app)", + "border": "Shell border", + "general": "General", + "services": "Services", + "utilities": "Utilities", + "audio": "Audio", + "ai": "AI assistant", +} + +# --------------------------------------------------------------------------- +# Exclusion rules. Each: (name, predicate over the walker's leaf row, +# reason). Applied in order; the FIRST matching rule's reason is recorded. +# A leaf may match none (then it is a tool candidate) — the exposure rule +# (UI row + scalar) is applied by build_registry.py separately. +# --------------------------------------------------------------------------- + +LeafRow = Dict[str, str] + + +def _prefix(*prefixes: str) -> Callable[[LeafRow], bool]: + def check(row: LeafRow) -> bool: + return any(row["path"].startswith(p) for p in prefixes) + return check + + +def _exact(*paths: str) -> Callable[[LeafRow], bool]: + paths_ = frozenset(paths) + + def check(row: LeafRow) -> bool: + return row["path"] in paths_ + return check + + +EXCLUSION_RULES: Tuple[Tuple[str, Callable[[LeafRow], bool], str], ...] = ( + ( + "non-scalar", + lambda r: r["kind"] != "scalar", + "non-scalar structured key (list/map/union/subobject); the settings " + "tool surface is scalar leaves only", + ), + ( + "master-switch", + _exact("enabled"), + "ConfigRoot master switch — a bad write disables the entire shell", + ), + ( + "filesystem-paths", + _prefix("paths."), + "filesystem path redirection; the wallpaper/CLI surface owns this", + ), + ( + "session-commands", + _prefix("session.commands."), + "command lists the session menu executes — never a settings tool", + ), + ( + "session-icons", + _prefix("session.icons."), + "icon-name strings with no shipped range/format control", + ), + ( + "general-command-lists", + _exact( + "general.terminal", "general.audio", "general.playback", + "general.explorer", + ), + "command lists the shell executes to open apps — never a settings tool", + ), + ( + "variant-unions", + _exact("general.idleAction", "general.returnAction"), + "QVariant union key; the type checker allows two metatypes and the " + "value shape is not a scalar", + ), + ( + "ai-credentials", + _exact( + "ai.anthropicApiKey", "ai.openaiApiKey", "ai.geminiApiKey", + "ai.openrouterApiKey", "ai.opencodeApiKey", + ), + "plaintext credential — never exposed as a tool", + ), + ( + "ai-endpoints", + _exact( + "ai.ollamaUrl", "ai.anthropicUrl", "ai.openaiUrl", "ai.geminiUrl", + "ai.openrouterUrl", "ai.opencodeUrl", "ai.opencodeGoUrl", + ), + "network endpoint the shell sends data to — outside the settings " + "tool surface", + ), + ( + "ai-executables", + _exact("ai.claudeCodeBin", "ai.loginTerminal"), + "binary/path the shell executes — never a settings tool", + ), + ( + "ai-internal-state", + _exact("ai.ollamaHistoryJson", "ai.claudeAccountsJson"), + "internally-managed state blob", + ), + ( + "ai-provider-selfconfig", + _prefix("ai."), + "AI-provider self-configuration (models/providers/accounts): the " + "assistant must not reconfigure its own plumbing; the Nexus " + "AiSettingsPage owns these", + ), + ( + "kwinrc-companion-writes", + _exact( + "general.magicLampEnabled", "general.krohnkiteEnabled", + "general.krohnkiteLastLayout", + "tabSwitch.enabled", "tabSwitch.orderTree", + "tabSwitch.highlightWindows", "tabSwitch.minMode", + "tabSwitch.multiScreenMode", + ), + "the shipped Nexus control writes companion kwinrc keys (or " + "installs a kwin script) alongside this key; a shell.json-only " + "write would desync the two stores", + ), + ( + "deprecated", + lambda r: bool(r.get("notes") and "deprecat" in r["notes"].lower()), + "deprecated migration key kept only for ConfigMigrations", + ), +) + +# Survey-transcription fixups: keys whose UI-survey enum annotation +# was imprecise, re-verified at source. Path -> (values, citation). +# Values may be strs (serialized enum keys) or ints (numeric-coded selects). +ENUM_FIXUPS: Dict[str, Tuple[List[Any], Tuple[str, str]]] = { + # ServicesPage.qml:47 — the value list is a FIXED literal (only the + # labels vary); the survey's "(dynamic gpuValues list)" note was wrong. + "services.gpuType": ( + ["", "NVIDIA", "GENERIC", "None"], + ("shell/modules/nexus/pages/ServicesPage.qml:47", + 'gpuValues: ["", "NVIDIA", "GENERIC", "None"] (fixed literal)'), + ), + # WallpaperSettingsPage.qml:26/56-58 — the SelectRow's menu items are + # LABELS (Crop|Fit|Stretch); the values it writes are the scalingValues + # ints [Image.PreserveAspectCrop, PreserveAspectFit, Image.Stretch] = + # [2, 1, 0]. The survey recorded the labels; the C++ leaf is int + # (default 2), so the enum must be the ints the UI actually stores. + "background.wallpaperFillMode": ( + [0, 1, 2], + ("shell/modules/nexus/pages/wallandstyle/WallpaperSettingsPage.qml:26", + "scalingValues: [Image.PreserveAspectCrop, Image.PreserveAspectFit, " + "Image.Stretch] = [2, 1, 0]; the SelectRow writes these ints"), + ), +} + +# Numeric leaves whose ONLY range source is not a stepper/slider row but a +# documented dynamic bound; the 18-tool core already handles bar.dock.iconSize +# with a conservative fixed cap (96) — preserved verbatim below. +CORE_OVERRIDES: Dict[str, Dict[str, object]] = { + "bar.dock.iconSize": { + "minimum": 16, "maximum": 96, "step": 4, + "reason": ( + "a conservative fixed cap; upstream's bound is dynamic " + "(Tokens.sizes.bar.innerWidth, tokens.hpp:115)" + ), + }, +} + +# Transformed steppers, re-verified at source (found by the +# 2-a-2 default-outside-range audit): the shipped StepperRow DISPLAYS a +# transformed value — seconds while the stored leaf is milliseconds, +# percent while the stored leaf is a fraction, minutes while the stored +# leaf is seconds — so the row's from/to/stepSize describe the DISPLAYED +# unit, not the stored one. tools.json must record the range in the STORED +# unit (the only unit a shell.json write can carry), so each entry carries +# the converted minimum/maximum/step plus a citation of the transforming +# row (the conversion arithmetic is on those very lines). +RANGE_FIXUPS: Dict[str, Dict[str, object]] = { + # NotificationPreferencesPage.qml:117-124 — UI 1-60 seconds. + "notifs.defaultExpireTimeout": { + "minimum": 1000, "maximum": 60000, "step": 1000, + "cite": ("shell/modules/nexus/pages/services/NotificationPreferencesPage.qml:120", + "stepper displays seconds (value: x/1000; onMoved: " + "Math.round(v*1000)); stored unit is ms — range converted x1000"), + }, + # NotificationPreferencesPage.qml:180-187 — UI 1-30 seconds. + "notifs.fullscreenExpireTimeout": { + "minimum": 1000, "maximum": 30000, "step": 1000, + "cite": ("shell/modules/nexus/pages/services/NotificationPreferencesPage.qml:183", + "stepper displays seconds (value: x/1000; onMoved: " + "Math.round(value*1000)); stored unit is ms — range converted x1000"), + }, + # utilities/OsdPage.qml:83-93 — UI 1-10 seconds. + "osd.hideDelay": { + "minimum": 1000, "maximum": 10000, "step": 1000, + "cite": ("shell/modules/nexus/pages/utilities/OsdPage.qml:88", + "stepper displays seconds (value: x/1000; onMoved: " + "Math.round(value*1000)); stored unit is ms — range converted x1000"), + }, + # ServicesPage.qml:110-118 — UI 5-120 seconds. + "nexus.networkRescanInterval": { + "minimum": 5000, "maximum": 120000, "step": 5000, + "cite": ("shell/modules/nexus/pages/ServicesPage.qml:114", + "stepper displays seconds (value: x/1000; onMoved: " + "Math.round(v*1000)); stored unit is ms — range converted x1000"), + }, + # ServicesPage.qml:100-108 — UI 0.5-10 seconds. + "dashboard.resourceUpdateInterval": { + "minimum": 500, "maximum": 10000, "step": 500, + "cite": ("shell/modules/nexus/pages/ServicesPage.qml:103", + "stepper displays seconds (value: x/1000; onMoved: " + "Math.round(v*1000)); stored unit is ms — range converted x1000"), + }, + # services/ArpcPage.qml:83-94 — UI 0-60 minutes (0 = never hide). + "services.arpcIdleTimeout": { + "minimum": 0, "maximum": 3600, "step": 60, + "cite": ("shell/modules/nexus/pages/services/ArpcPage.qml:89", + "stepper displays minutes (value: Math.round(x/60); onMoved: " + "Math.round(v*60)); stored unit is seconds — range converted x60"), + }, + # ServicesPage.qml:151-160 — UI 1-50 percent. + "services.audioIncrement": { + "minimum": 0.01, "maximum": 0.5, "step": 0.01, + "cite": ("shell/modules/nexus/pages/ServicesPage.qml:155", + "stepper displays percent (value: Math.round(x*100); onMoved: " + "v/100); stored unit is a fraction — range converted /100"), + }, + # ServicesPage.qml:162-170 — UI 1-50 percent. + "services.brightnessIncrement": { + "minimum": 0.01, "maximum": 0.5, "step": 0.01, + "cite": ("shell/modules/nexus/pages/ServicesPage.qml:165", + "stepper displays percent (value: Math.round(x*100); onMoved: " + "v/100); stored unit is a fraction — range converted /100"), + }, + # ServicesPage.qml:172-181 — UI 50-200 percent. + "services.maxVolume": { + "minimum": 0.5, "maximum": 2.0, "step": 0.05, + "cite": ("shell/modules/nexus/pages/ServicesPage.qml:176", + "stepper displays percent (value: Math.round(x*100); onMoved: " + "v/100); stored unit is a fraction — range converted /100"), + }, +} + +# The 18 core tools, preserved byte-for-byte (name/path/kind/default/min/max/ +# enum/global_only/step/nouns). Citations are re-derived from the walker + +# UI rows, plus these hand-carried citation notes for consumer evidence. +CORE_TOOLS: Dict[str, Dict[str, object]] = { + "bar.scale": {"name": "setBarScale", "minimum": 0.6, "maximum": 1.6, "step": 0.1, + "nouns": ["bar|taskbar|panel"], + "extra_citations": [ + ("shell/modules/bar/BarWrapper.qml:24", "contentWidth = innerWidth * barScale; floor 0.6"), + ]}, + "bar.position": {"name": "setBarPosition", "enum": ["top", "bottom", "left", "right"], + "nouns": ["bar|taskbar|panel"], + "extra_citations": [ + ("shell/modules/bar/BarWrapper.qml:23", "position-driven anchoring"), + ]}, + "bar.dock.iconSize": {"name": "setDockIconSize", "minimum": 16, "maximum": 96, "step": 4, + "nouns": ["dock icons|taskbar dock|dock"], + "extra_citations": [ + ("shell/modules/bar/components/Dock.qml:38", "QML floor 16"), + ]}, + "bar.persistent": {"name": "setBarPersistent", "nouns": ["bar|taskbar", "persistent|always visible|auto.?hide"], + "extra_citations": [ + ("shell/modules/bar/BarWrapper.qml:27", "persistent reader"), + ]}, + "bar.livePreviews": {"name": "setLivePreviews", "nouns": ["live previews|window previews|thumbnails|previews"], + "extra_citations": [ + # Path re-verified at 70ee7da: the file lives under + # shell/components/images/ (an earlier the settings design notes (see module docstrings) path + # shell/modules/bar/components/ no longer exists). + ("shell/components/images/WindowPreview.qml:42", "live reader"), + ]}, + "appearance.blur": {"name": "setBlurEnabled", "nouns": ["background blur|frosted glass|blur"], + "extra_citations": [ + ("shell/modules/drawers/blur/BlurOffsets.qml:17", "isActive = transparency.enabled && blur"), + ]}, + "appearance.transparency.base": {"name": "setTransparencyBase", "minimum": 0.0, "maximum": 1.0, "step": 0.05, + "nouns": ["base opacity|transparency|opacity"], + "extra_citations": [ + # Path re-verified at 70ee7da: ContentWindow.qml lives under + # shell/modules/drawers/ (an earlier the settings design notes (see module docstrings) path + # shell/modules/components/containers/ no longer exists). + ("shell/modules/drawers/ContentWindow.qml:383", "surface opacity reader"), + ]}, + "appearance.rounding.scale": {"name": "setRoundingScale", "minimum": 0.5, "maximum": 2.0, "step": 0.1, + "nouns": ["corner rounding|corner radius|rounding|corners"]}, + "appearance.spacing.scale": {"name": "setSpacingScale", "minimum": 0.5, "maximum": 2.0, "step": 0.1, + "nouns": ["gaps|spacing|gap"]}, + "appearance.padding.scale": {"name": "setPaddingScale", "minimum": 0.5, "maximum": 2.0, "step": 0.1, + "nouns": ["padding|insets"]}, + "appearance.font.scale": {"name": "setFontScale", "minimum": 0.5, "maximum": 2.0, "step": 0.1, + "nouns": ["font size|text size|fonts|font|text"]}, + "appearance.anim.durations.scale": {"name": "setAnimationSpeed", "minimum": 0.25, "maximum": 4.0, "step": 0.25, + "nouns": ["animation speed|animations?|transitions|motion|effects speed"], + "extra_citations": [ + ("shell/plugin/src/Caelestia/Config/appearanceconfig.cpp:207", "durations multiplied by scale"), + ]}, + "border.thickness": {"name": "setBorderThickness", "minimum": 0, "maximum": 50, "step": 2, + "nouns": ["shell border|border|outline"]}, + "launcher.maxShown": {"name": "setLauncherMaxShown", "minimum": 1, "maximum": 20, "step": 1, + "nouns": ["launcher results|search results|launcher"]}, + "appearance.pitchBlack": {"name": "setPitchBlack", "nouns": ["pitch black|bezel mode|bezel"], + "extra_citations": [ + # Path re-verified at 70ee7da (see setTransparencyBase above). + ("shell/modules/drawers/ContentWindow.qml:394", "#000000 surface when pitchBlack"), + ]}, + "notifs.maxPopups": {"name": "setNotifsMaxPopups", "minimum": 0, "maximum": 30, "step": 1, + "nouns": ["notification popups|popup notifications"]}, + "notifs.maxNotifs": {"name": "setNotifsMaxNotifs", "minimum": 20, "maximum": 2000, "step": 50, + "nouns": ["stored notifications|max stored notifications"]}, + "bar.dock.showBadges": {"name": "setDockBadges", "nouns": ["app badges|badges|badge"], + "extra_citations": [ + ("shell/modules/bar/components/Dock.qml:630", "badge over LauncherEntry.forApp, ?? true"), + ]}, +} + +# UI control types that are scalar-tool capable. Anything else on a UI row +# excludes the key (reason carries the control type). +_SCALAR_CONTROLS = re.compile( + r"^(ToggleRow|StepperRow|DoubleStepperRow|SliderRow|SelectRow|FontCard)" +) + +# ToggleRow variants annotated in parentheses remain ToggleRows (the note +# describes enabled/visible gating, not the control shape). + + +def control_is_scalar(control: str) -> bool: + """True when the shipped control is a scalar setter (toggle/stepper/ + slider/select/font card). Parenthesized annotations are ignored.""" + return bool(_SCALAR_CONTROLS.match(control)) + + +def exclusion_for(row: LeafRow) -> Optional[Tuple[str, str]]: + """First matching exclusion rule for a walker leaf row, if any.""" + for name, predicate, reason in EXCLUSION_RULES: + try: + if predicate(row): + return name, reason + except Exception: # noqa: BLE001 - defensive: rules are pure data + continue + return None + + +def tool_name_for(path: str) -> str: + """Derive the tool name from the dotted path (core names preserved via + CORE_TOOLS). 'appearance.transparency.base' -> 'setTransparencyBase'; + the leading area segment is dropped when the remainder is distinctive.""" + if path in CORE_TOOLS: + return str(CORE_TOOLS[path]["name"]) + parts = path.split(".") + # Drop a pure area prefix that matches the group's own root segment. + if len(parts) > 1: + parts = parts[1:] + camel = "".join(p[:1].upper() + p[1:] for p in parts if p) + return "set" + (camel if camel else "Value") + + +def extra_citations_for(path: str) -> List[Tuple[str, str]]: + core = CORE_TOOLS.get(path) + if not core: + return [] + return list(core.get("extra_citations", [])) # type: ignore[arg-type] + +# --------------------------------------------------------------------------- +# Explainability rules. Each rule is pure data the Python CLI and +# the QML service BOTH render; every citation below was re-verified by eye +# in this checkout. +# Fields: path (the key the question is about), when (a predicate over a +# state dict {path: value} — expressed as a small DSL string evaluated by +# both layers, see build_registry/explain.py for the evaluator), answer +# (a {fmt} template over state values), citations. +# --------------------------------------------------------------------------- + +EXPLAIN_RULES: List[Dict[str, object]] = [ + { + "path": "appearance.blur", + "when": "appearance.blur == true and appearance.transparency.enabled == true", + "answer": "Blur is enabled because transparency is currently active " + "and appearance.blur is on — the blur regions gate on both " + "({cite}).", + "cites": ["shell/modules/drawers/blur/BlurOffsets.qml:17"], + }, + { + "path": "appearance.blur", + "when": "appearance.blur == true and appearance.transparency.enabled == false", + "answer": "Blur is ON but has no effect, because transparency is " + "currently disabled — the blur regions gate on " + "transparency.enabled && blur together ({cite}).", + "cites": ["shell/modules/drawers/blur/BlurOffsets.qml:17"], + }, + { + "path": "appearance.transparency.enabled", + "when": "appearance.transparency.enabled == true and " + "utilities.gameMode.disableShellTransparency == true and " + "_gamemode == true", + "answer": "Transparency is configured ON but is currently suppressed, " + "because Game Mode is active with 'disable shell " + "transparency' set — the colour service gates on that pair " + "({cite}).", + "cites": ["shell/services/Colours.qml:418"], + }, + { + "path": "appearance.transparency.base", + "when": "appearance.transparency.base > 0 and _light == true", + "answer": "Surfaces look less transparent than the configured base " + "opacity {appearance.transparency.base}, because light mode " + "trims the base by 0.1 ({cite}).", + "cites": ["shell/services/Colours.qml:419"], + }, + { + "path": "appearance.pitchBlack", + "when": "appearance.pitchBlack == true", + "answer": "Surfaces are fully opaque and pure black because Pitch " + "Black (bezel mode) is active — it forces opacity 1 " + "({cite1}) and #000000 surfaces ({cite2}).", + "cites": ["shell/modules/drawers/ContentWindow.qml:383", + "shell/modules/drawers/ContentWindow.qml:394"], + }, + { + "path": "overview.enableOverviewBlur", + "when": "overview.enableOverviewBlur == true and appearance.blur == false", + "answer": "The overview blur setting is ON but has no effect, because " + "the global appearance blur is off — the overview effect " + "gates on both ({cite}).", + "cites": ["shell/modules/drawers/ContentWindow.qml:374"], + }, + { + "path": "appearance.anim.durations.scale", + "when": "appearance.anim.durations.scale != 1", + "answer": "Animations feel {slower|faster} because the animation " + "duration scale is currently set to " + "{appearance.anim.durations.scale} — every duration token " + "is multiplied by it, so lower means faster ({cite}).", + "cites": ["shell/plugin/src/Caelestia/Config/appearanceconfig.cpp:209"], + }, + { + "path": "appearance.ambientColor", + "when": "appearance.ambientColor == true and _light == true", + "answer": "The ambient glow is configured ON but is currently hidden, " + "because ambient glow only renders in dark mode — it gates " + "on ambientColor && !light ({cite}).", + "cites": ["shell/components/effects/AmbientGlow.qml:34"], + }, + { + "path": "bar.persistent", + "when": "bar.persistent == false", + "answer": "The bar hides because bar persistence is currently off — " + "a non-persistent bar dodges or auto-hides instead of " + "staying put ({cite}).", + "cites": ["shell/modules/bar/BarWrapper.qml:62"], + }, + { + "path": "bar.dodgeWindows", + "when": "bar.dodgeWindows == true and bar.persistent == false", + "answer": "Window dodging has no effect, because dodge mode requires " + "a persistent bar — the dodge gate is dodgeWindows && " + "persistent ({cite}).", + "cites": ["shell/modules/bar/BarWrapper.qml:27"], + }, + { + "path": "bar.scale", + "when": "bar.scale < 0.6", + "answer": "The bar is not as small as asked: the effective bar scale " + "is floored at 0.6 ({cite}); the configured value is " + "{bar.scale}.", + "cites": ["shell/modules/bar/BarWrapper.qml:24"], + }, +] + +# --------------------------------------------------------------------------- +# Named presets — bundles of validated tool calls ONLY, never +# bespoke code paths. Every (tool, value) must pass that tool's validation +# (a test asserts it). Values are in the STORED unit (see RANGE_FIXUPS). +# --------------------------------------------------------------------------- + +PRESETS: List[Dict[str, object]] = [ + { + "name": "compact", + "label": "Compact", + "description": "Smaller dock icons and tighter spacing/padding/rounding " + "— the same keys the Nexus steppers expose.", + "calls": [ + ["setDockIconSize", 24], + ["setSpacingScale", 0.8], + ["setPaddingScale", 0.8], + ["setRoundingScale", 0.8], + ], + }, + { + "name": "minimal", + "label": "Minimal", + "description": "Issue #120's own example direction: smaller bar and " + "dock, lower rounding, faster animations, badges and " + "previews off.", + "calls": [ + ["setBarScale", 0.7], + ["setDockIconSize", 20], + ["setRoundingScale", 0.5], + ["setAnimationSpeed", 0.5], + ["setSpacingScale", 0.7], + ["setDockBadges", False], + ["setLivePreviews", False], + ], + }, + { + "name": "gaming", + "label": "Gaming", + "description": "Snappier shell, no blur/transparency compositing, no " + "popup notifications. (Game Mode itself is a service " + "toggle, not a shell.json scalar — this bundle is the " + "config-side reduction only.)", + "calls": [ + ["setBlurEnabled", False], + ["setTransparencyEnabled", False], + ["setAnimationSpeed", 0.25], + ["setNotifsMaxPopups", 0], + ], + }, + { + "name": "battery-saver", + "label": "Battery saver", + "description": "Reduce compositing and background work: blur, ambient " + "glow and wallpaper recolour off, animations fast.", + "calls": [ + ["setBlurEnabled", False], + ["setAnimationSpeed", 0.25], + ["setAmbientColor", False], + ["setWallpaperRecolor", False], + ], + }, + { + "name": "macos-like", + "label": "More like macOS", + "description": "Always-visible bottom dock with larger icons, rounder " + "corners, roomier spacing and badges on — the keys the " + "shipped controls already expose.", + "calls": [ + ["setBarPosition", "bottom"], + ["setBarPersistent", True], + ["setDockIconSize", 48], + ["setRoundingScale", 1.3], + ["setSpacingScale", 1.1], + ["setPaddingScale", 1.1], + ["setAnimationSpeed", 1.0], + ["setDockBadges", True], + ], + }, +] diff --git a/plugins/caelestia-assistant/assistant/capabilities/settings/dbus_surface.py b/plugins/caelestia-assistant/assistant/capabilities/settings/dbus_surface.py new file mode 100644 index 0000000..632eafd --- /dev/null +++ b/plugins/caelestia-assistant/assistant/capabilities/settings/dbus_surface.py @@ -0,0 +1,506 @@ +"""settings.dbus_surface — the quarantined, opt-in DBus surface +(the former proposals/2026-09-26-c-dbus-surface.md, pruned in +exponential-build-3 Phase 2 once implemented — this docstring and +git history carry the design). + +THE QUARANTINE (the pkgprobe pattern, second module): this is one of +exactly TWO modules in ``assistant/`` permitted to import +``subprocess`` — the import-policy lint +(``diagnostics/schema_lint.py``) carries a per-module carve-out for +``dbus_surface.py`` alone, and a test pins the exemption set to +exactly {pkgprobe.py, dbus_surface.py}. Every other module stays +under the zero-tolerance rule. + +What it covers (the four surfaces the watched shell.json CANNOT +reach — the proposal's own table): + +- kwinrc companion writes (``kwriteconfig6``) — the target repo's own + precedent (lock-screen section, CONTRIBUTING.md); +- display topology (``kscreen-doctor``) — read via ``--outputs``, + write via a machine-derived ``--output --mode `` (the + values come FROM the tool's own observed output, never free text); +- power profiles (``powerprofilesctl``) — read the table, set one of + the OBSERVED profile names; +- KWin scripting (``dbus-send`` to org.kde.KWin) — the only scripting + entry point that survives across KDE releases; irreversible by + catalog declaration, never auto-run. + +The discipline, line by line (the proposal's safety contract): + +- FIXED ARGUMENT ARRAYS: every spawned command is + ``subprocess.run([binary, *fixed_args])`` — never ``shell=True``, + never free-text interpolation. Values fill typed slots + (bool/int/enum) or are machine-derived from a prior READ; +- OFF BY DEFAULT: nothing runs unless the capability manifest enables + ``dbus_surface`` (a file edit — never an NL request), the same + kill-switch posture as package_audit; +- RISK-CLASSIFIED BEFORE EXECUTION: every catalog command carries its + static risk class; DESTRUCTIVE classifications are withheld + entirely (none are cataloged — adding one is a reviewable diff that + must also change the pinning test); +- SHORT-LIVED: one bounded ``run`` per invocation, no resident + process, zero steady-state memory; +- UNDO WHERE THE TOOL SUPPORTS IT: kwriteconfig6 writes record the + previous value (read via the same fixed argv shape through + kreadconfig6) and undo writes it back; kscreen mode changes record + the observed prior mode; power profile sets record the prior active + profile; KWin script loads are declared irreversible and refuse to + run without an explicit ``confirm_irreversible=True`` — the second + confirmation the proposal demands; +- HONEST DEGRADATION: missing binaries, timeouts, the disabled + capability, and unknown commands return error dicts, never + exceptions. + +This is a LIBRARY surface, not a conversational one: no natural +language request reaches it, no CLI route applies a write. The caller +(a QML service or the agent layer) renders ``plan_write`` (the dry-run +artifact), obtains consent, then calls ``run_write``; the returned +undo record is the caller's to persist and later hand to +``apply_undo``. +""" + +from __future__ import annotations + +import subprocess +from datetime import datetime +from typing import Any, Dict, List, Optional, Tuple + +from assistant.core import features as capabilities + +__all__ = [ + "CATALOG", "catalog_lines", "plan_write", "run_write", "apply_undo", + "read_kscreen_outputs", "read_power_profiles", "run_read", +] + +_TIMEOUT_SECONDS = 10 + +# --------------------------------------------------------------------------- +# The command catalog: every entry is a complete fixed command shape. +# Adding an entry (or a risk class above STATE_CHANGING) is a reviewable +# diff: the pinning test asserts the exact ids and classes, and +# the package rationale (see module docstrings) §16 must grow with it. +# --------------------------------------------------------------------------- + +CATALOG: Tuple[Dict[str, Any], ...] = ( + { + "id": "kwinrc.nightcolor.active", + "binary": "kwriteconfig6", + "group": "NightColor", + "key": "Active", + "value_kind": "bool", + "risk": "STATE_CHANGING", + "reversible": True, + "note": "Night Color master switch (the kwinrc companion the " + "shell.json watched file cannot reach)", + }, + { + "id": "kwinrc.lockscreen.timeout", + "binary": "kwriteconfig6", + "group": "ScreenSaver", + "key": "Timeout", + "value_kind": "int", + "value_min": 0, + "value_max": 7200, + "risk": "STATE_CHANGING", + "reversible": True, + "note": "the lock-screen section precedent from the target " + "repo's own CONTRIBUTING.md", + }, + { + "id": "kscreen.mode.set", + "binary": "kscreen-doctor", + "argv": ("output", "{output}", "mode", "{mode}"), + "value_kind": "observed-pair", # {output, mode} from the read + "risk": "STATE_CHANGING", + "reversible": True, + "note": "display mode change; the output name and mode come from " + "the tool's own observed topology", + }, + { + "id": "powerprofiles.set", + "binary": "powerprofilesctl", + "argv": ("set", "{profile}"), + "value_kind": "observed", # from read_power_profiles + "risk": "STATE_CHANGING", + "reversible": True, + "note": "sets one of the OBSERVED profile names", + }, + { + "id": "kwin.script.unload", + "binary": "dbus-send", + "argv": ("--session", "--dest=org.kde.KWin", "/Scripting", + "org.kde.kwin.Scripting.unloadScript", "string:{name}"), + "value_kind": "name", + "risk": "STATE_CHANGING", + "reversible": False, + "note": "unloads a loaded KWin script by name; IRREVERSIBLE per " + "the proposal (no undo record exists) — requires " + "confirm_irreversible=True", + }, +) + +_CATALOG_IDS = frozenset(entry["id"] for entry in CATALOG) + + +# --------------------------------------------------------------------------- +# Spawning (the ONLY place subprocess appears). +# --------------------------------------------------------------------------- + + +def _spawn(argv: List[str]) -> Dict[str, Any]: + """One short-lived, bounded, fixed-array run. Returns the completed + result as a dict (stdout/stderr/rc) or an honest error dict.""" + try: + completed = subprocess.run( # noqa: S603 — fixed array, caller-built + argv, capture_output=True, text=True, + timeout=_TIMEOUT_SECONDS, check=False, + ) + except subprocess.TimeoutExpired: + return {"error": f"{argv[0]} timed out after {_TIMEOUT_SECONDS}s"} + except OSError as exc: + return {"error": f"{argv[0]} failed to start: " + f"{type(exc).__name__}: {exc}"} + return {"rc": completed.returncode, "stdout": completed.stdout, + "stderr": completed.stderr} + + +def _guard() -> Optional[Dict[str, Any]]: + """The kill-switch: the capability manifest must enable the surface + (a file edit, never an NL request).""" + if not capabilities.enabled("dbus_surface"): + return {"error": "dbus_surface is disabled in the capability " + "manifest (edit capabilities.json to enable; " + "it cannot be enabled by a request)", + "capability": "dbus_surface", + "enabled": False} + return None + + +def _spec(command_id: str) -> Optional[Dict[str, Any]]: + return next((e for e in CATALOG if e["id"] == command_id), None) + + +def _validate_value(spec: Dict[str, Any], value: Any) -> Optional[str]: + kind = spec.get("value_kind") + if kind == "bool": + if not isinstance(value, bool): + return "this command takes true or false" + elif kind == "int": + if not isinstance(value, int) or isinstance(value, bool): + return "this command takes an integer" + lo, hi = spec.get("value_min"), spec.get("value_max") + if lo is not None and value < lo: + return f"below the catalog minimum {lo}" + if hi is not None and value > hi: + return f"above the catalog maximum {hi}" + elif kind == "observed": + if not isinstance(value, str) or not value.strip() or len(value) > 80: + return ("this command takes a value observed from the " + "matching read probe (run the read first)") + elif kind == "observed-pair": + if not isinstance(value, dict) \ + or not isinstance(value.get("output"), str) \ + or not isinstance(value.get("mode"), str) \ + or not value["output"].strip() or not value["mode"].strip() \ + or len(value["output"]) > 40 or len(value["mode"]) > 40: + return ("this command takes {output, mode} from the observed " + "topology (run read_kscreen_outputs first)") + elif kind == "name": + if not isinstance(value, str) or not value.strip() or len(value) > 64: + return "this command takes a short script name" + return None + + +# --------------------------------------------------------------------------- +# kwriteconfig6 / kreadconfig6 helpers (the fixed argv shapes). +# --------------------------------------------------------------------------- + + +def _kwrite_argv(spec: Dict[str, Any], value: Any) -> List[str]: + return [spec["binary"], "--file", "kwinrc", "--group", + spec["group"], "--key", spec["key"], str(value).lower() + if isinstance(value, bool) else str(value)] + + +def _kread_argv(spec: Dict[str, Any]) -> List[str]: + return ["kreadconfig6", "--file", "kwinrc", "--group", + spec["group"], "--key", spec["key"]] + + +# --------------------------------------------------------------------------- +# The read probes (read-only, still behind the kill-switch). +# --------------------------------------------------------------------------- + + +def read_kscreen_outputs() -> Dict[str, Any]: + """``kscreen-doctor --outputs`` parsed into a topology dict: per + output, its name, modes and current mode. Read-only.""" + off = _guard() + if off: + return off + out = _spawn(["kscreen-doctor", "--outputs"]) + if "error" in out: + return out + if out["rc"] != 0: + return {"error": "kscreen-doctor exited " + f"{out['rc']}", "stderr": out["stderr"][:400]} + outputs: List[Dict[str, Any]] = [] + current: Dict[str, Any] = {} + for line in out["stdout"].splitlines(): + stripped = line.strip() + if stripped.startswith("Output:"): + current = {"raw": stripped, "modes": []} + outputs.append(current) + elif current is not None and "Modes:" in stripped: + continue + elif current is not None and stripped.startswith("Mode:"): + current.setdefault("modes", []).append(stripped) + if "*" in stripped: # the active mode is starred + # "Mode: 1920x1080@60*" -> "1920x1080@60" + fields = stripped.split() + if len(fields) >= 2: + current["current_mode"] = fields[1].rstrip("*") + current["current_mode_line"] = stripped + elif current is not None and stripped.startswith("Name:"): + fields = stripped.split(":", 1) + if len(fields) == 2: + current["name"] = fields[1].strip() + return {"outputs": outputs, "n": len(outputs), + "note": "machine-derived from kscreen-doctor's own output; " + "the write surface only accepts values seen here"} + + +def read_power_profiles() -> Dict[str, Any]: + """``powerprofilesctl`` parsed into the profile table (which are + available, which is active). Read-only.""" + off = _guard() + if off: + return off + out = _spawn(["powerprofilesctl"]) + if "error" in out: + return out + if out["rc"] != 0: + return {"error": f"powerprofilesctl exited {out['rc']}", + "stderr": out["stderr"][:400]} + profiles: List[Dict[str, Any]] = [] + for line in out["stdout"].splitlines(): + stripped = line.strip() + if not stripped: + continue + # rows look like " performance:", "* balanced:", or + # " power-saver:" (the starred one is active) + active = stripped.startswith("*") + if active: + stripped = stripped[1:].strip() + name = stripped.split(":")[0].strip() + if name: + profiles.append({"name": name, "active": active}) + return {"profiles": profiles, + "active": next((p["name"] for p in profiles if p["active"]), + None), + "note": "machine-derived from powerprofilesctl's own output"} + + +def run_read(command_id: str) -> Dict[str, Any]: + """The read probes by catalog intent (dispatch helper): 'kscreen' + reads the topology, 'power' reads the profile table. Read-only.""" + if command_id in ("kscreen", "kscreen.mode.set"): + return read_kscreen_outputs() + if command_id in ("power", "powerprofiles.set"): + return read_power_profiles() + return {"error": f"no read probe for {command_id!r} " + f"(have: kscreen, power)"} + + +# --------------------------------------------------------------------------- +# The write spine: plan (dry-run render) -> run (gated) -> undo. +# --------------------------------------------------------------------------- + + +def plan_write(command_id: str, value: Any) -> Dict[str, Any]: + """The DRY-RUN artifact: the exact argv that WOULD run, the static + risk class, the reversibility statement, and the undo strategy. + Spawns nothing, writes nothing, works even with the capability + disabled (you can always LOOK).""" + spec = _spec(command_id) + if spec is None: + return {"error": f"unknown command {command_id!r} " + f"(catalog: {sorted(_CATALOG_IDS)})"} + bad = _validate_value(spec, value) + if bad: + return {"error": f"invalid value for {command_id}: {bad}"} + argv = _render_argv(spec, value) + out: Dict[str, Any] = { + "command": command_id, + "argv": argv, + "risk": spec["risk"], + "reversible": spec["reversible"], + "note": spec["note"], + "dry_run": True, + } + if not spec["reversible"]: + out["requires"] = "run_write(..., confirm_irreversible=True) — " \ + "no undo record exists for this command" + elif spec["binary"] == "kwriteconfig6": + out["undo_strategy"] = "read the previous value (kreadconfig6, " \ + "same fixed shape) then write it back" + elif command_id == "kscreen.mode.set": + out["undo_strategy"] = "re-apply the mode from the pre-change " \ + "topology snapshot" + elif command_id == "powerprofiles.set": + out["undo_strategy"] = "set the previously active profile" + return out + + +def _scalar_str(value: Any) -> str: + return str(value).lower() if isinstance(value, bool) else str(value) + + +def _render_argv(spec: Dict[str, Any], value: Any) -> List[str]: + if spec["binary"] == "kwriteconfig6": + return _kwrite_argv(spec, value) + argv = [spec["binary"]] + pair = value if isinstance(value, dict) else {} + for piece in spec.get("argv", ()): + argv.append(piece.replace("{output}", str(pair.get("output", ""))) + .replace("{mode}", str(pair.get("mode", ""))) + .replace("{profile}", _scalar_str(value)) + .replace("{name}", _scalar_str(value)) + .replace("{value}", _scalar_str(value))) + return argv + + +def run_write(command_id: str, value: Any, + confirm_irreversible: bool = False, + _prev: Optional[Dict[str, Any]] = None) -> Dict[str, Any]: + """Execute ONE catalog write. The caller must have shown + plan_write's artifact and obtained consent — this function is the + apply gate, and nothing conversational ever calls it. + + Returns the run report plus, for reversible commands, the UNDO + RECORD (a plain dict): hand it to ``apply_undo`` to revert. An + undo record is only produced when the write actually succeeded. + """ + off = _guard() + if off: + return off + spec = _spec(command_id) + if spec is None: + return {"error": f"unknown command {command_id!r}"} + bad = _validate_value(spec, value) + if bad: + return {"error": f"invalid value: {bad}"} + if not spec["reversible"] and not confirm_irreversible: + return {"error": f"{command_id} is irreversible per the catalog; " + "pass confirm_irreversible=True after the second " + "confirmation the proposal demands"} + # DESTRUCTIVE risk classes are structurally absent from the catalog; + # the guard stays so a future edit cannot silently bypass review. + if spec["risk"] in ("PRIVILEGED", "DESTRUCTIVE"): + return {"error": f"{command_id} is classified {spec['risk']} — " + "withheld from execution entirely"} + + # capture the pre-change state for the undo record + undo: Optional[Dict[str, Any]] = None + if spec["reversible"] and spec["binary"] == "kwriteconfig6": + old = _spawn(_kread_argv(spec)) + if "error" not in old and old.get("rc") == 0: + undo = {"command": command_id, "kind": "kwriteconfig6", + "old_value": _coerce(spec, old["stdout"].strip()), + "at": datetime.now().isoformat()} + elif command_id == "kscreen.mode.set": + snap = read_kscreen_outputs() + if "error" not in snap: + prior = _prev if isinstance(_prev, dict) else snap + # the inverse pair: the output being changed, its CURRENT + # (pre-change) observed mode + target_output = value.get("output") \ + if isinstance(value, dict) else "" + old_pair = next( + ({"output": o.get("name", ""), + "mode": o.get("current_mode", "")} + for o in prior.get("outputs", []) + if o.get("name") == target_output and o.get("current_mode")), + None) + if old_pair is not None: + undo = {"command": command_id, "kind": "kscreen", + "old_value": old_pair, + "at": datetime.now().isoformat()} + elif command_id == "powerprofiles.set": + snap = read_power_profiles() + if "error" not in snap and snap.get("active"): + undo = {"command": command_id, "kind": "powerprofiles", + "old_value": snap["active"], + "at": datetime.now().isoformat()} + + argv = _render_argv(spec, value) + out = _spawn(argv) + if "error" in out: + return {"error": out["error"], "argv": argv} + if out["rc"] != 0: + return {"error": f"{command_id} exited {out['rc']}", + "argv": argv, "stderr": out["stderr"][:400]} + report: Dict[str, Any] = {"command": command_id, "argv": argv, + "applied": True, "risk": spec["risk"], + "reversible": spec["reversible"]} + if undo is not None: + report["undo_record"] = undo + return report + + +def _coerce(spec: Dict[str, Any], raw: str) -> Any: + """Coerce a value READ back from the tool into the spec's own type + (kreadconfig6 prints 'true'/'false'/digits; the write side wants + bool/int) — so an undo record round-trips through validation.""" + if spec.get("value_kind") == "bool": + if raw.lower() in ("true", "1", "yes", "on"): + return True + if raw.lower() in ("false", "0", "no", "off", ""): + return False + if spec.get("value_kind") == "int": + try: + return int(raw) + except ValueError: + return raw + return raw + + +def apply_undo(record: Dict[str, Any], + confirm_irreversible: bool = False) -> Dict[str, Any]: + """Revert ONE write using its undo record (bounded: one record, one + inverse write — never a replay loop).""" + off = _guard() + if off: + return off + kind = record.get("kind") + if kind == "kwriteconfig6": + return run_write(record["command"], record.get("old_value", "")) + if kind == "powerprofiles": + return run_write("powerprofiles.set", record.get("old_value", "")) + if kind == "kscreen": + old_pair = record.get("old_value") + if not (isinstance(old_pair, dict) and old_pair.get("output") + and old_pair.get("mode")): + return {"error": "the undo record carries no observed " + "prior mode; nothing to revert to"} + return run_write("kscreen.mode.set", old_pair) + return {"error": f"unknown undo record kind {kind!r}"} + + +# --------------------------------------------------------------------------- +# Introspection. +# --------------------------------------------------------------------------- + + +def catalog_lines() -> List[str]: + """The reviewable one-line-per-command listing (ids, binaries, + risk, reversibility).""" + lines = [f"dbus surface catalog ({len(CATALOG)} commands, " + f"kill-switch: capabilities.json dbus_surface=" + f"{capabilities.enabled('dbus_surface')}):"] + for spec in CATALOG: + lines.append(f" {spec['id']} [{spec['binary']}, " + f"{spec['risk']}, " + f"{'reversible' if spec['reversible'] else 'IRREVERSIBLE'}]" + f" {spec['note']}") + return lines diff --git a/plugins/caelestia-assistant/assistant/capabilities/settings/enumerate.py b/plugins/caelestia-assistant/assistant/capabilities/settings/enumerate.py new file mode 100755 index 0000000..d4da89a --- /dev/null +++ b/plugins/caelestia-assistant/assistant/capabilities/settings/enumerate.py @@ -0,0 +1,584 @@ +"""Enumerate every settings leaf of the Caelestia config tree (registry input). + +Walks the C++ config headers into a leaf-key table, verified against the +dev tree @ 70ee7da. + + * ``enumerate_leaves(repo_root)`` — importable, returns the leaf rows as a + list of dicts with the same fields the survey's TSV carried (root, path, + kind, type, default, global_only, header, line, class, macro, + element_type, derived, notes, order). + * ``main()`` — prints the TSV to stdout (``--repo-root`` argument, default + the current directory) instead of writing survey files. + +Walks the ACTUAL C++ headers in ``/shell/plugin/src/Caelestia/Config/``: + + * rootnodes.hpp -> class ConfigRoot (shell.json via the GlobalConfig/Config + singletons/attached objects) and class TokensRoot + (shell-tokens.json via TokenConfig). + * Every class mounted through CONFIG_SUBOBJECT / SETTINGS_SUBOBJECT is + recursively parsed for CONFIG_PROPERTY / + CONFIG_GLOBAL_PROPERTY / CONFIG_ENUM_PROPERTY / + CONFIG_GLOBAL_ENUM_PROPERTY / CONFIG_LIST / + CONFIG_GLOBAL_LIST / SETTINGS_* equivalents. + +Semantics note (verified against the C++ implementation): + settings::Schema::build(meta, Base::staticMetaObject.propertyCount()) + (Settings/schema.cpp:89-131) builds each class's schema from the base's + property count onwards, i.e. a class's schema contains ONLY the properties + declared in its own body. ObjectNode::toJson/loadFromJson iterate + schema().descriptors(). Therefore a mounted instance of a subclass (the one + case in the tree: IconFontStyleConfig : FontStyleConfig at appearance.font.icon) + exposes only its OWN declarations (extraLarge); the inherited family/large/ + medium/small are live QObject properties on the instance but are outside the + settings schema (never serialised/loaded/reset). This walker follows that + "own body only" rule. + +Multi-line macro invocations are parsed by parenthesis balancing that skips +comment/string contents (defaults contain parens inside strings, e.g. +ICON_RULE_REGEX("steam(_app_(default|[0-9]+))?", ...)). + +Read-only with respect to the repository. Stdlib only. +""" + +from __future__ import annotations + +import argparse +import re +import sys +from pathlib import Path + +PROPERTY_MACROS = { + "CONFIG_PROPERTY", "CONFIG_GLOBAL_PROPERTY", + "SETTINGS_PROPERTY", "SETTINGS_GLOBAL_PROPERTY", +} +ENUM_PROPERTY_MACROS = { + "CONFIG_ENUM_PROPERTY", "CONFIG_GLOBAL_ENUM_PROPERTY", +} +SUBOBJECT_MACROS = { + "CONFIG_SUBOBJECT", "CONFIG_GLOBAL_SUBOBJECT", + "SETTINGS_SUBOBJECT", "SETTINGS_GLOBAL_SUBOBJECT", +} +LIST_MACROS = { + "CONFIG_LIST", "CONFIG_GLOBAL_LIST", + "SETTINGS_LIST", "SETTINGS_GLOBAL_LIST", +} +NODE_MACROS = { + "CONFIG_NODE", "CONFIG_NODE_NO_CTOR", + "SETTINGS_NODE", "SETTINGS_NODE_NO_CTOR", +} +LIST_TYPE_MACROS = {"CONFIG_LIST_TYPE", "SETTINGS_LIST_TYPE"} +ALL_MACROS = (PROPERTY_MACROS | ENUM_PROPERTY_MACROS | SUBOBJECT_MACROS + | LIST_MACROS | NODE_MACROS | LIST_TYPE_MACROS) + +MACRO_RE = re.compile( + r"(? str: + """Blank out comment bodies and string/char literal contents (keep newlines).""" + out = list(text) + i, n = 0, len(text) + NORMAL, LINE_C, BLOCK_C, STR, CHR = range(5) + state = NORMAL + while i < n: + c = text[i] + if state == NORMAL: + if c == "/" and i + 1 < n and text[i + 1] == "/": + out[i] = out[i + 1] = " " + state = LINE_C + i += 2 + continue + if c == "/" and i + 1 < n and text[i + 1] == "*": + out[i] = out[i + 1] = " " + state = BLOCK_C + i += 2 + continue + if c == '"': + out[i] = " " + state = STR + i += 1 + continue + if c == "'": + out[i] = " " + state = CHR + i += 1 + continue + i += 1 + continue + if state == LINE_C: + if c == "\n": + state = NORMAL + else: + out[i] = " " + i += 1 + continue + if state == BLOCK_C: + if c == "*" and i + 1 < n and text[i + 1] == "/": + out[i] = out[i + 1] = " " + state = NORMAL + i += 2 + continue + if c != "\n": + out[i] = " " + i += 1 + continue + # STR or CHR + if c == "\\" and i + 1 < n: + out[i] = out[i + 1] = " " + i += 2 + continue + if (state == STR and c == '"') or (state == CHR and c == "'"): + out[i] = " " + state = NORMAL + i += 1 + continue + if c != "\n": + out[i] = " " + i += 1 + return "".join(out) + + +def mask_preprocessor(masked: str) -> str: + """Blank out preprocessor logical lines (handles backslash continuations).""" + lines = masked.split("\n") + out: list[str] = [] + i = 0 + while i < len(lines): + if lines[i].lstrip().startswith("#"): + while True: + out.append(re.sub(r"[^\n]", " ", lines[i])) + if not lines[i].rstrip().endswith("\\"): + i += 1 + break + i += 1 + else: + out.append(lines[i]) + i += 1 + return "\n".join(out) + + +def line_of(text: str, offset: int) -> int: + return text.count("\n", 0, offset) + 1 + + +def collapse_ws(s: str) -> str: + """Collapse whitespace runs outside string/char literals; keep literals verbatim.""" + out: list[str] = [] + in_lit = False + quote = "" + i, n = 0, len(s) + while i < n: + c = s[i] + if in_lit: + out.append(c) + if c == "\\" and i + 1 < n: + out.append(s[i + 1]) + i += 2 + continue + if c == quote: + in_lit = False + i += 1 + continue + if c in "\"'": + in_lit = True + quote = c + out.append(c) + i += 1 + continue + if c.isspace(): + out.append(" ") + while i < n and s[i].isspace(): + i += 1 + continue + out.append(c) + i += 1 + return "".join(out).strip() + + +def unwrap_default_arg(s: str) -> str: + """Unwrap a single DEFAULT_ARG(...) wrapper if it spans the whole string.""" + t = s.strip() + if t.startswith("DEFAULT_ARG(") and t.endswith(")"): + depth = 0 + for i, c in enumerate(t): + if c == "(": + depth += 1 + elif c == ")": + depth -= 1 + if depth == 0 and i != len(t) - 1: + return t # closing paren is not the last char: not a pure wrapper + return t[len("DEFAULT_ARG("):-1] + return t + + +# ---------------------------------------------------------------- parsing + +def split_args(masked_region: str, orig_region: str) -> list[str]: + """Split a macro argument region on top-level commas. + + Depth tracking covers (), {} and <> (templates); string contents are + already blanked in `masked_region`. + """ + parts: list[str] = [] + depth_p = depth_b = depth_a = 0 + start = 0 + for i, c in enumerate(masked_region): + if c == "(": + depth_p += 1 + elif c == ")": + depth_p -= 1 + elif c == "{": + depth_b += 1 + elif c == "}": + depth_b -= 1 + elif c == "<": + depth_a += 1 + elif c == ">": + if depth_a > 0: + depth_a -= 1 + elif c == "," and depth_p == 0 and depth_b == 0 and depth_a == 0: + parts.append(orig_region[start:i]) + start = i + 1 + parts.append(orig_region[start:]) + return [collapse_ws(p) for p in parts] + + +def balanced_paren(masked: str, open_idx: int) -> int: + """Index of the ')' matching the '(' at open_idx (strings already blanked).""" + depth = 0 + for i in range(open_idx, len(masked)): + c = masked[i] + if c == "(": + depth += 1 + elif c == ")": + depth -= 1 + if depth == 0: + return i + raise ValueError(f"unbalanced parens from offset {open_idx}") + + +def balanced_brace(masked: str, open_idx: int) -> int: + depth = 0 + for i in range(open_idx, len(masked)): + c = masked[i] + if c == "{": + depth += 1 + elif c == "}": + depth -= 1 + if depth == 0: + return i + raise ValueError(f"unbalanced braces from offset {open_idx}") + + +class Invocation: + __slots__ = ("name", "args", "line", "start") + + def __init__(self, name: str, args: list[str], line: int, start: int): + self.name = name + self.args = args + self.line = line + self.start = start + + +class ClassInfo: + __slots__ = ("name", "base", "header", "line", "start", "end", "macros", "is_list_wrapper") + + def __init__(self, name, base, header, line, start, end): + self.name = name + self.base = base + self.header = header + self.line = line + self.start = start + self.end = end + self.macros: list[Invocation] = [] + self.is_list_wrapper = False + + +def parse_header(path: Path): + """Return (classes, list_types, free_macros) for one header.""" + text = path.read_text(encoding="utf-8") + masked = mask_preprocessor(mask_comments_and_strings(text)) + + invocations: list[Invocation] = [] + for m in MACRO_RE.finditer(masked): + name = m.group(1) + # next non-space char must be '(' + j = m.end() + while j < len(masked) and masked[j].isspace(): + j += 1 + if j >= len(masked) or masked[j] != "(": + continue + close = balanced_paren(masked, j) + args = split_args(masked[j + 1:close], text[j + 1:close]) + invocations.append(Invocation(name, args, line_of(text, m.start()), m.start())) + + classes: dict[str, ClassInfo] = {} + for m in CLASS_RE.finditer(masked): + name = m.group(1) + base_txt = (m.group(2) or "").strip() + bases = [b for b in re.findall(r"[A-Za-z_][A-Za-z0-9_:]*", base_txt) if b != "public"] + base = bases[0] if bases else "" + end = balanced_brace(masked, m.end() - 1) + classes[name] = ClassInfo(name, base, path.name, line_of(text, m.start()), m.start(), end) + + # attribute macro invocations to the innermost containing class body + free: list[Invocation] = [] + for inv in invocations: + best: ClassInfo | None = None + for ci in classes.values(): + if ci.start <= inv.start <= ci.end: + if best is None or ci.start >= best.start: + best = ci + if best is not None: + best.macros.append(inv) + else: + free.append(inv) + + list_types: dict[str, str] = {} # wrapper class -> element class + for inv in free: + if inv.name in LIST_TYPE_MACROS and len(inv.args) >= 2: + list_types[inv.args[1]] = inv.args[0] + + # Cross-check CONFIG_NODE base vs the class declaration base + for ci in classes.values(): + for inv in ci.macros: + if inv.name in NODE_MACROS and len(inv.args) >= 2: + if ci.base and ci.base != inv.args[1]: + # keep the CONFIG_NODE-declared base (authoritative for the macros) + ci.base = inv.args[1] + else: + ci.base = inv.args[1] + return classes, list_types, free + + +def parse_enums(path: Path) -> dict[str, list[str]]: + """enums.hpp: ENUM(Name, Value, ...) namespace enums.""" + text = path.read_text(encoding="utf-8") + masked = mask_preprocessor(mask_comments_and_strings(text)) + enums: dict[str, list[str]] = {} + for m in re.finditer(r"(? dict: + return { + "root": self.root, + "path": self.path, + "kind": self.kind, + "type": self.type, + "default": self.default, + "global_only": self.global_only, + "header": self.header, + "line": self.line, + "class": self.cls, + "macro": self.macro, + "element_type": self.element, + "derived": self.derived, + "notes": self.notes, + "order": self.order, + } + + +class Enumerator: + def __init__(self, classes, list_types, enums): + self.classes = classes + self.list_types = list_types + self.enums = enums + self.rows: list[Row] = [] + self.anomalies: list[str] = [] + self.mounted_headers: dict[str, set] = {} + self._order = 0 + self._seen: set[tuple[str, str]] = set() + + def _next(self): + self._order += 1 + return self._order + + def _class(self, name: str, where: str) -> ClassInfo | None: + ci = self.classes.get(name) + if ci is None: + self.anomalies.append(f"class {name} not found in any Config header (referenced from {where})") + return ci + + def walk(self, cls_name: str, prefix: str, global_parent: bool, root_label: str, + derived: bool): + key = (root_label, prefix or "(root)") + if key in self._seen: + self.anomalies.append(f"cycle/重复 mount avoided at {key}") + return + self._seen.add(key) + ci = self._class(cls_name, f"mount {prefix or '(root)'}") + if ci is None: + return + self.mounted_headers.setdefault(root_label, set()).add(ci.header) + + for inv in ci.macros: + n = inv.name + if n in NODE_MACROS or n in LIST_TYPE_MACROS: + continue + args = inv.args + if n in SUBOBJECT_MACROS: + if len(args) < 2: + self.anomalies.append(f"{n} with {len(args)} args at {ci.header}:{inv.line}") + continue + typ, name = args[0], args[1] + g = global_parent or n.endswith("GLOBAL_SUBOBJECT") + path = f"{prefix}.{name}" if prefix else name + self.rows.append(Row(root_label, path, "subobject", typ, "", g, + ci.header, inv.line, cls_name, n, "", derived, + "", self._next())) + self.walk(typ, path, g, root_label, derived) + elif n in LIST_MACROS: + if len(args) < 2: + self.anomalies.append(f"{n} with {len(args)} args at {ci.header}:{inv.line}") + continue + typ, name = args[0], args[1] + default = unwrap_default_arg(args[2]) if len(args) > 2 else "" + g = global_parent or n.endswith("GLOBAL_LIST") + path = f"{prefix}.{name}" if prefix else name + elem = typ + note = "" + eci = self.classes.get(self.list_types.get(typ, "")) + if eci is not None: + eprops = sum(1 for x in eci.macros if x.name in (PROPERTY_MACROS | ENUM_PROPERTY_MACROS)) + note = f"element class {eci.name} ({eci.header}:{eci.line}, {eprops} props, not enumerated as tree leaves)" + else: + note = f"element list type {typ} (no element class record)" + self.rows.append(Row(root_label, path, "list", typ, default, g, + ci.header, inv.line, cls_name, n, elem, derived, + note, self._next())) + elif n in PROPERTY_MACROS or n in ENUM_PROPERTY_MACROS: + if len(args) < 2: + self.anomalies.append(f"{n} with {len(args)} args at {ci.header}:{inv.line}") + continue + typ, name = args[0], args[1] + default = unwrap_default_arg(args[2]) if len(args) > 2 else "" + # CONFIG_GLOBAL_ENUM_PROPERTY also ends "...ENUM_PROPERTY", + # not "...GLOBAL_PROPERTY" — both spellings mean global-only. + g = global_parent or n.endswith("GLOBAL_PROPERTY") \ + or n.endswith("GLOBAL_ENUM_PROPERTY") + path = f"{prefix}.{name}" if prefix else name + notes = "" + if n in ENUM_PROPERTY_MACROS: + typ = f"caelestia::config::{typ}::Enum" + vals = self.enums.get(args[0], []) + notes = f"enum {args[0]}: " + "|".join(vals) if vals else f"enum {args[0]} (values not found)" + if len(args) > 3: + extra = ", ".join(args[3:]) + notes = (notes + "; " if notes else "") + f"extra: {extra}" + kind = "map" if typ == "QVariantMap" else "scalar" + self.rows.append(Row(root_label, path, kind, typ, default, g, + ci.header, inv.line, cls_name, n, "", derived, + notes, self._next())) + else: + self.anomalies.append(f"unhandled macro {n} at {ci.header}:{inv.line}") + + +# ---------------------------------------------------------------- API + +def enumerate_leaves(repo_root: str) -> list[dict]: + """Walk the Config headers under ``repo_root`` and return every node row. + + Rows are dicts with the survey TSV's fields (see FIELDS). The config tree + (root == "config", persisted as shell.json) and the derived tokens tree + (root == "tokens", persisted as shell-tokens.json) are both included; + callers filter by ``root``. Deterministic order: (root, path segments, + declaration order). + """ + repo = Path(repo_root) + config_dir = repo / "shell" / "plugin" / "src" / "Caelestia" / "Config" + if not config_dir.is_dir(): + raise FileNotFoundError( + f"{config_dir} does not exist — run from a caelestia checkout") + + headers = sorted(config_dir.glob("*.hpp")) + classes: dict[str, ClassInfo] = {} + list_types: dict[str, str] = {} + for h in headers: + cls, lt, _free = parse_header(h) + for name, ci in cls.items(): + classes[name] = ci + for w, e in lt.items(): + list_types[w] = e + + enums = parse_enums(config_dir / "enums.hpp") + + en = Enumerator(classes, list_types, enums) + + # Root node rows + traversal + en.rows.append(Row("config", "(root)", "subobject", "ConfigRoot", "", False, + "rootnodes.hpp", 34, "ConfigRoot", "CONFIG_NODE_NO_CTOR", "", + False, "root of the shell.json tree (GlobalConfig singleton / Config attached)", en._next())) + en.walk("ConfigRoot", "", False, "config", derived=False) + + en.rows.append(Row("tokens", "(root)", "subobject", "TokensRoot", "", False, + "rootnodes.hpp", 70, "TokensRoot", "CONFIG_NODE_NO_CTOR", "", + True, "root of the shell-tokens.json tree (TokenConfig singleton); DERIVED/computed base values", en._next())) + en.walk("TokensRoot", "", False, "tokens", derived=True) + + rows = sorted(en.rows, key=lambda r: (r.root, r.path.split("."), r.order)) + return [r.as_dict() for r in rows] + + +def main() -> int: + parser = argparse.ArgumentParser( + description="Print the Caelestia config-leaf enumeration as TSV.") + parser.add_argument("--repo-root", default=".", + help="caelestia-kde checkout root (default: current directory)") + args = parser.parse_args() + + try: + rows = enumerate_leaves(args.repo_root) + except FileNotFoundError as exc: + print(f"error: {exc}", file=sys.stderr) + return 1 + + out = sys.stdout + out.write("root\tpath\tkind\ttype\tdefault\tglobal_only\theader\tline\tclass\tmacro\telement_type\tderived\tnotes\n") + for r in rows: + fields = [r["root"], r["path"], r["kind"], r["type"], r["default"], + "yes" if r["global_only"] else "no", r["header"], str(r["line"]), + r["class"], r["macro"], r["element_type"], + "yes" if r["derived"] else "no", r["notes"]] + fields = [x.replace("\t", " ").replace("\n", " ") for x in fields] + out.write("\t".join(fields) + "\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/plugins/caelestia-assistant/assistant/capabilities/settings/envaudit.py b/plugins/caelestia-assistant/assistant/capabilities/settings/envaudit.py new file mode 100644 index 0000000..afe6fca --- /dev/null +++ b/plugins/caelestia-assistant/assistant/capabilities/settings/envaudit.py @@ -0,0 +1,196 @@ +"""assistant.capabilities.settings.envaudit — the environment audit (F21, +exponential-build-5). + +A single read-only pass that answers: "is my environment healthy, and +how do I KNOW?" — by COMPOSING engines that already exist (no new +analysis of its own) and reporting every engine's verdict with the +command that reproduces it: + +- config validity: settings.lint over the live target (unknown keys, + out-of-range/mistyped values, silent no-ops, inert customizations); +- interaction contradictions: the configured values projected through + the cited interaction table (settings.consequences) — e.g. blur + configured while transparency is off (the INERT state); +- upstream drift: the frozen registry's generation fingerprint versus + the current checkout state (the gen_adapter --verify verdict is + expensive, so the audit reports the REGISTRY AGE it knows — the + pinned upstream revision in the corpus metadata — and points at the + exact verify command rather than re-running generation); +- backup coverage: whether the single .assistant-backup slot exists + and matches a point-in-time of the live file (informational); +- environment snapshots (F17): freshness of the newest snapshot + (how long ago, and whether the live content hash still matches it); +- per-screen overrides (F20): the monitors/ directory's files, with + managed/unknown key counts (monitors.discover). + +Read-only end to end. Exit code 0 unless CRITICAL findings exist +(refusals the applier itself would raise); WARN/INFO never block. +""" + +from __future__ import annotations + +import json +from datetime import datetime +from pathlib import Path +from typing import Any, Dict, List, Optional + +from . import consequences, lint, monitors as monitors_mod +from .environments import canonical_hash, read_config + +__all__ = ["audit", "render_lines"] + +CRITICAL = "CRITICAL" +WARN = "WARN" +INFO = "INFO" + + +def audit(target, now: Optional[datetime] = None) -> Dict[str, Any]: + """Run every check over the live environment (read-only). ``now`` + anchors snapshot freshness (default: a fixed epoch — callers pass + the real clock; the function stays deterministic for tests).""" + target = Path(target) + now = now or datetime(2026, 1, 1, 12, 0, 0) + checks: List[Dict[str, Any]] = [] + + current, problems = read_config(target) + if problems: + for problem in problems: + checks.append({"check": "config-readable", "severity": CRITICAL, + "detail": problem}) + if not current: + return {"target": str(target), "checks": checks, + "critical": len(problems)} + + # 1. Config validity via the existing linter. + findings = lint.lint_file(str(target)) if target.exists() else [] + for finding in findings: + severity = (CRITICAL if finding.get("id") in + ("out-of-range", "mistyped") else WARN) + checks.append({ + "check": "config-lint", "severity": severity, + "rule": finding.get("id"), + "detail": finding.get("message") or json.dumps(finding)[:200], + "evidence": finding, + }) + if not findings: + checks.append({"check": "config-lint", "severity": INFO, + "detail": "no lint findings: every leaf is " + "registry-known and in range"}) + + # 2. Interaction contradictions via the cited consequence table, + # projected over the CONFIGURED values (synthetic "configured" + # ops so the edge conditions evaluate). Only DERIVED/INERT edges + # are reported here — the projection's op-legality conflicts are + # the PLANNER's domain over proposed ops (the lint already flags + # out-of-range configured values), and paths lint already + # reported are skipped to avoid double-counting. + configured_ops = _ops_from_config(current) + projection = consequences.project(configured_ops, current) + lint_paths = {str(f.get("path")) for f in findings if f.get("path")} + inert = [row for row in projection.get("derived") or [] + if "INERT" in str(row.get("effect", "")) + and str(row.get("effect_path")) not in lint_paths] + for row in inert: + checks.append({ + "check": "interaction-inert", "severity": WARN, + "detail": f"{row.get('effect_path')}: {row.get('effect')}", + "evidence": {"citation": row.get("citation")}, + }) + if not inert: + checks.append({"check": "interaction", "severity": INFO, + "detail": "no additional interaction edge is " + "armed against the configured values " + "beyond the lint findings"}) + + # 3. Snapshot freshness (F17). + from . import environments as env_mod + saved = env_mod.list_environments(target) + if not saved: + checks.append({"check": "snapshots", "severity": INFO, + "detail": "no environment snapshots saved yet " + "(--env-save NAME captures one)"}) + else: + newest = saved[-1] + try: + env = env_mod.get(target, str(newest["name"])) # verifies hash + live_hash = canonical_hash(current) + fresh = (env.get("content_hash") == live_hash) + checks.append({ + "check": "snapshot-fresh", + "severity": INFO if fresh else WARN, + "detail": (f"newest snapshot {newest['name']!r} MATCHES the " + f"live content hash" if fresh else + f"newest snapshot {newest['name']!r} predates the " + f"current config (live hash diverged); " + f"re-snapshot or restore deliberately"), + }) + except env_mod.EnvironmentError as exc: + checks.append({"check": "snapshot-fresh", "severity": CRITICAL, + "detail": f"newest snapshot {newest['name']!r} " + f"failed integrity: {exc}"}) + + # 4. Per-screen overrides (F20). + for row in monitors_mod.discover(target): + if row.get("error"): + checks.append({"check": "monitor-override", "severity": WARN, + "detail": f"{row['screen']}: {row['error']}"}) + else: + detail = (f"{row['screen']}: {row['managed_keys']} managed, " + f"{row['unknown_keys']} unknown key(s) at " + f"{row['path']}") + checks.append({"check": "monitor-override", + "severity": INFO if row["unknown_keys"] == 0 + else WARN, "detail": detail}) + + # 5. Backup slot coverage (informational; the applier owns it). + backup = target.parent / (target.name + ".assistant-backup") + if backup.exists(): + try: + same = json.loads(backup.read_text(encoding="utf-8")) == current + except (OSError, json.JSONDecodeError): + same = False + checks.append({ + "check": "backup-slot", "severity": INFO, + "detail": ("the backup slot matches the live content (the " + "last write predates no further change)" if same + else "a backup slot exists and predates the live " + "content (one level of undo is available)"), + }) + else: + checks.append({"check": "backup-slot", "severity": INFO, + "detail": "no backup slot yet (nothing applied)"}) + + critical = sum(1 for c in checks if c["severity"] == CRITICAL) + return {"target": str(target), "checks": checks, "critical": critical} + + +def _ops_from_config(current: Dict[str, Any]) -> List[Dict[str, Any]]: + """Synthetic set ops (tool, action, value) for every registry-known + configured path, so the consequence projection evaluates the + CONFIGURED state.""" + from .environments import _flatten + from assistant.adapters.caelestia.registry import tool_by_path + ops: List[Dict[str, Any]] = [] + for path, value in sorted(_flatten(current).items()): + spec = tool_by_path(path) + if spec is None: + continue + ops.append({"tool": spec.name, "action": "set", "value": value, + "raw": f"configured: {path}={value!r}"}) + return ops + + +def render_lines(result: Dict[str, Any]) -> List[str]: + lines = [f"environment audit for {result['target']} " + f"(read-only; {len(result['checks'])} check(s)):"] + order = {CRITICAL: 0, WARN: 1, INFO: 2} + for check in sorted(result["checks"], + key=lambda c: order.get(c["severity"], 3)): + lines.append(f" [{check['severity']:<8}] {check['check']}: " + f"{check['detail']}") + if result["critical"]: + lines.append(f"{result['critical']} CRITICAL finding(s) — the " + f"applier would refuse writes until resolved") + else: + lines.append("no critical findings") + return lines diff --git a/plugins/caelestia-assistant/assistant/capabilities/settings/environments.py b/plugins/caelestia-assistant/assistant/capabilities/settings/environments.py new file mode 100644 index 0000000..1b81bba --- /dev/null +++ b/plugins/caelestia-assistant/assistant/capabilities/settings/environments.py @@ -0,0 +1,354 @@ +"""assistant.capabilities.settings.environments — named environment snapshots (F17) +and portable export/import (F18) for exponential-build-5. + +Issue #120's Phase 3 roadmap: "workspace profiles ... monitor-specific +layouts ... workspace automation". Before any of those can be safe, +there needs to be a way to capture the WHOLE current environment, name +it, get back to it, and move it between machines. That is this module. + +An ENVIRONMENT is a named snapshot of: + +- the target shell.json content (parsed, canonical-hash pinned), +- the saved macros and profiles lists (captured metadata, so an export + carries the user's composed bundles; RESTORE does not touch them — + they are restored through their own explicit commands, F9/C3). + +DISCIPLINE (the whole point): + +- STORAGE: inside the existing undo-history file under a bounded + ``"environments"`` key (MAX_ENVIRONMENTS=8, FIFO) — the same file, + the same ``history._save`` atomic path, the same sibling path as the + ``undo_log`` (A3), ``macros`` (C3) and ``profiles`` (F9) precedents. + The documented write scope of the settings layer does not grow. +- RESTORE IS A PLAN, NOT A WRITE: the snapshot's registry-known keys + are turned into plain planner ops (set for changed/new values, unset + for keys the snapshot lacks that the live file has), validated by the + ordinary planner, previewed, and applied only behind the standard + --apply/--confirm gates. Keys the registry does not manage are + REPORTED, never touched — the assistant does not know their shape + and refuses to guess. +- INTEGRITY: every snapshot pins the sha256 of its canonical content; + ``show`` verifies and names mismatches (a snapshot that fails its own + hash is an error entry, never a restore source). + +F18 EXPORT/IMPORT (same module, the migration half): + +- export writes a PORTABLE BUNDLE to a caller-chosen path: schema + version, the snapshot, and provenance (registry tool count at capture + time, created_at). Nothing else is written. +- import is REVIEW-ONLY: the bundle is validated (schema, hash, + registry drift), the shell.json content is diffed against the live + file, and the environment is stored as a NEW named snapshot marked + ``imported``; nothing is applied by importing. The user previews and + restores through the ordinary F17 path if they want it. + +Pure module apart from the documented history-file writes behind the +explicit verbs: no execution, no network, no RNG. +""" + +from __future__ import annotations + +import hashlib +import json +import re +from datetime import datetime, timezone +from pathlib import Path +from typing import Any, Dict, List, Optional, Tuple, Union + +from . import history +from assistant.adapters.caelestia.registry import TOOL_SPECS + +__all__ = ["EnvironmentError", "MAX_ENVIRONMENTS", "ENVIRONMENTS_KEY", + "SCHEMA_VERSION", "NAME_RE", "canonical_hash", "save", + "list_environments", "delete", "get", "diff_to_ops", + "export_bundle", "import_bundle"] + +MAX_ENVIRONMENTS = 8 +ENVIRONMENTS_KEY = "environments" +SCHEMA_VERSION = 1 + +NAME_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9 _.\-]{0,31}") + +TOOL_PATHS = {spec.path: spec.name for spec in TOOL_SPECS} + +FileTarget = Union[str, Path] + + +class EnvironmentError(ValueError): + """Raised for every refusal (unknown environment, bad name, hash + mismatch, schema drift); the caller renders the reason.""" + + +def canonical_hash(content: Dict[str, Any]) -> str: + return hashlib.sha256( + json.dumps(content, sort_keys=True, separators=(",", ":"), + ensure_ascii=False).encode("utf-8")).hexdigest() + + +def _load_envs(target) -> List[Dict[str, Any]]: + return [dict(e) for e in + history._load(target).get(ENVIRONMENTS_KEY, [])] + + +def _save_envs(target, envs: List[Dict[str, Any]]) -> None: + data = history._load(target) + data[ENVIRONMENTS_KEY] = envs + history._save(target, data) + + +def _registry_managed(node: Any, prefix: str = "", + out: Optional[Dict[str, Any]] = None) -> Dict[str, Any]: + """Flatten a config tree to dotted paths, keeping ONLY the paths the + registry manages (the planner can validate and write those).""" + if out is None: + out = {} + if isinstance(node, dict): + for key, value in node.items(): + path = f"{prefix}.{key}" if prefix else key + if isinstance(value, dict): + _registry_managed(value, path, out) + elif path in TOOL_PATHS: + out[path] = value + return out + + +def read_config(target) -> Tuple[Dict[str, Any], List[str]]: + """The live file parsed ({} when absent) + the list of problems + (unparseable content is an honest empty-with-problems, never a + crash — a restore against a corrupt file must still be previewable).""" + try: + text = Path(target).read_text(encoding="utf-8") + except OSError: + return {}, ["the target file does not exist yet"] + try: + data = json.loads(text) + except json.JSONDecodeError as exc: + return {}, [f"the target file is not valid JSON: {exc}"] + if not isinstance(data, dict): + return {}, ["the target file is not a JSON object"] + return data, [] + + +def save(target, name: str) -> Dict[str, Any]: + """Snapshot the current environment (target content + macros + + profiles metadata) under a bounded, hash-pinned name. Writes only + the history file's "environments" key. Duplicate names refuse + (delete first); the store is FIFO-bounded.""" + if not NAME_RE.fullmatch(str(name or "")): + raise EnvironmentError( + f"environment names must match {NAME_RE.pattern!r} — got " + f"{name!r}") + content, problems = read_config(target) + if problems and content == {} and "not exist" not in problems[0]: + raise EnvironmentError(f"cannot snapshot: {problems[0]}") + data = history._load(target) + envs = data.get(ENVIRONMENTS_KEY, []) + if any(e.get("name") == name for e in envs): + raise EnvironmentError( + f"environment {name!r} already exists; delete it first " + f"(--env-delete {name})") + entry = { + "name": name, + "created_at": datetime.now(timezone.utc).isoformat(timespec="seconds"), + "content_hash": canonical_hash(content), + "content": content, + "registry_tools": len(TOOL_SPECS), + "macros": [dict(m) for m in data.get("macros", [])], + "profiles": [dict(p) for p in data.get("profiles", [])], + } + envs.append(entry) + data[ENVIRONMENTS_KEY] = envs[-MAX_ENVIRONMENTS:] # FIFO bound + history._save(target, data) + return {k: v for k, v in entry.items() if k != "content"} | { + "paths": _count_leaves(content)} + + +def _count_leaves(node: Any) -> int: + if isinstance(node, dict): + return sum(_count_leaves(v) for v in node.values()) + return 1 + + +def list_environments(target) -> List[Dict[str, Any]]: + """The saved environments, oldest first, WITHOUT their content + (read-only).""" + return [{k: v for k, v in env.items() if k != "content"} + for env in _load_envs(target)] + + +def get(target, name: str, verify: bool = True) -> Dict[str, Any]: + """One environment by name. With verify, a hash mismatch raises — + a snapshot that fails its own integrity is never a restore source.""" + for env in _load_envs(target): + if env.get("name") == name: + if verify: + expected = env.get("content_hash") + actual = canonical_hash(env.get("content") or {}) + if expected != actual: + raise EnvironmentError( + f"environment {name!r} FAILED its integrity check " + f"(stored hash {expected!r} != actual {actual!r}); " + f"it will not be restored or exported") + return env + saved = [str(e.get("name")) for e in _load_envs(target)] + raise EnvironmentError( + f"unknown environment {name!r}; saved environments: " + + (", ".join(saved) if saved else "(none yet; save one with " + "--env-save)")) + + +def delete(target, name: str) -> Dict[str, Any]: + """Remove one environment by name (an explicit user command).""" + envs = _load_envs(target) + kept = [e for e in envs if e.get("name") != name] + if len(kept) == len(envs): + raise EnvironmentError( + f"unknown environment {name!r}; saved environments: " + + (", ".join(str(e.get("name")) for e in envs) if envs + else "(none)")) + _save_envs(target, kept) + return {"deleted": name} + + + + +def _flatten(node: Any, prefix: str = "", + out: Optional[Dict[str, Any]] = None) -> Dict[str, Any]: + """Flatten a config tree to dotted paths (all leaves).""" + if out is None: + out = {} + if isinstance(node, dict): + for key, value in node.items(): + path = f"{prefix}.{key}" if prefix else key + if isinstance(value, dict): + _flatten(value, path, out) + else: + out[path] = value + return out + + +def _unknown(d: Dict[str, Any]) -> List[str]: + all_flat = _flatten(d) + return sorted(p for p in all_flat if p not in TOOL_PATHS) + + +def diff_to_ops(target, name: str) -> Dict[str, Any]: + """The restore plan's RAW MATERIAL (read-only, no planner call): + registry-known paths that differ between the live file and the + snapshot become {tool, action, value} set ops (and unset ops for + live keys the snapshot lacks); unknown keys are REPORTED, split by + direction (only-in-snapshot, only-in-live), and never planned.""" + env = get(target, name) # verifies integrity + snapshot: Dict[str, Any] = env.get("content") or {} + live, _problems = read_config(target) + snap_flat = _registry_managed(snapshot) + live_flat = _registry_managed(live) + set_ops: List[Dict[str, Any]] = [] + reset_ops: List[Dict[str, Any]] = [] + for path in sorted(set(snap_flat) | set(live_flat)): + if path in snap_flat and path not in live_flat: + set_ops.append({"tool": TOOL_PATHS[path], "action": "set", + "value": snap_flat[path], + "raw": f"env restore {name}: {path}=" + f"{snap_flat[path]!r}"}) + elif path in snap_flat and path in live_flat and \ + snap_flat[path] != live_flat[path]: + set_ops.append({"tool": TOOL_PATHS[path], "action": "set", + "value": snap_flat[path], + "raw": f"env restore {name}: {path} " + f"{live_flat[path]!r} -> " + f"{snap_flat[path]!r}"}) + elif path not in snap_flat and path in live_flat: + spec = next((s for s in TOOL_SPECS if s.path == path), None) + default = getattr(spec, "default", None) + reset_ops.append({"tool": TOOL_PATHS[path], "action": "set", + "value": default, + "raw": f"env restore {name}: {path} " + f"{live_flat[path]!r} -> registry " + f"default {default!r} (the snapshot " + f"lacks this key; the applier cannot " + f"remove keys, so restore resets it)"}) + return { + "name": name, + "set_ops": set_ops, + "reset_ops": reset_ops, + "unknown_only_in_snapshot": _unknown(snapshot), + "unknown_only_in_live": _unknown(live), + "identical": not (set_ops or reset_ops), + } + + +# --------------------------------------------------------------------------- +# F18: portable export / review-only import. +# --------------------------------------------------------------------------- + +def export_bundle(target, name: str) -> Dict[str, Any]: + """The portable bundle for one verified environment (a plain dict — + the CLI writes it to the user-chosen path; this module never picks + paths).""" + env = get(target, name) # verifies integrity + return { + "schema": SCHEMA_VERSION, + "kind": "caelestia-assistant-environment", + "created_at": env.get("created_at"), + "registry_tools": env.get("registry_tools"), + "content_hash": env.get("content_hash"), + "content": env.get("content"), + "macros": env.get("macros", []), + "profiles": env.get("profiles", []), + } + + +def import_bundle(target, bundle: Dict[str, Any], + name: str) -> Dict[str, Any]: + """Import a bundle as a NEW snapshot, REVIEW-ONLY: schema and hash + are validated, registry drift is measured and reported, and the + import lands as a stored environment marked imported=true. NOTHING + is applied — restoring rides the ordinary F17 diff/plan/consent + path. The target file itself is never written by the import.""" + if not isinstance(bundle, dict) or \ + bundle.get("kind") != "caelestia-assistant-environment": + raise EnvironmentError( + "not a caelestia-assistant environment bundle (missing kind)") + if bundle.get("schema") != SCHEMA_VERSION: + raise EnvironmentError( + f"unsupported bundle schema {bundle.get('schema')!r} " + f"(expected {SCHEMA_VERSION}) — re-export from the source " + f"machine") + content = bundle.get("content") + if not isinstance(content, dict): + raise EnvironmentError("bundle content is not a JSON object") + actual = canonical_hash(content) + if actual != bundle.get("content_hash"): + raise EnvironmentError( + f"bundle FAILED its integrity check (declared " + f"{bundle.get('content_hash')!r} != actual {actual!r})") + if not NAME_RE.fullmatch(str(name or "")): + raise EnvironmentError( + f"environment names must match {NAME_RE.pattern!r} — got " + f"{name!r}") + data = history._load(target) + envs = data.get(ENVIRONMENTS_KEY, []) + if any(e.get("name") == name for e in envs): + raise EnvironmentError( + f"environment {name!r} already exists locally; import under " + f"a different name") + drift = {"bundled_tools": bundle.get("registry_tools"), + "local_tools": len(TOOL_SPECS)} + unknown = sorted(p for p in _flatten(content) if p not in TOOL_PATHS) + entry = { + "name": name, + "created_at": datetime.now(timezone.utc).isoformat(timespec="seconds"), + "content_hash": actual, + "content": content, + "registry_tools": len(TOOL_SPECS), + "macros": bundle.get("macros", []), + "profiles": bundle.get("profiles", []), + "imported": True, + "import_drift": drift, + "import_unknown_paths": unknown, + } + envs.append(entry) + data[ENVIRONMENTS_KEY] = envs[-MAX_ENVIRONMENTS:] + history._save(target, data) + return {k: v for k, v in entry.items() if k != "content"} diff --git a/plugins/caelestia-assistant/assistant/capabilities/settings/explain.py b/plugins/caelestia-assistant/assistant/capabilities/settings/explain.py new file mode 100755 index 0000000..69cdf37 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/capabilities/settings/explain.py @@ -0,0 +1,511 @@ +"""Explainability for the settings layer (issue #120), read-only. + +Read-only: this module never writes anything. It answers "why does it look +like this" questions against the live config state (the target shell.json, +with registry defaults for unset keys — the same effective-value semantics +ConfigObject's fallback gives the QML side), in the exact style the issue +itself shows: + + "Blur is enabled because Glass Mode is currently active." + "The launcher scale is currently set to 1.25x." + +Grounding is the same registry + citations as every other tool: causal +answers come from registry.EXPLAIN_RULES (each rule carries its own +file:line citations); with no rule firing, the +answer is the live value readback with validation, default and the C++ +declaration citation. + +Honesty note (offline vs in-shell): the QML service evaluates the same +rules with LIVE session flags (GameMode.enabled, Colours.light). This CLI +only sees the file, so rules referencing _gamemode/_light do not fire +here — they fall through to the value readback instead of guessing. +""" + +from __future__ import annotations + +import re +from pathlib import Path +from typing import Any, Dict, List, Optional, Tuple, Union + +from .parser import _NOUN_RES, _noun_matched, _normalize +from assistant.adapters.caelestia.registry import EXPLAIN_RULES, ToolSpec, tool_by_name, tool_by_path + +FileTarget = Union[str, Path] + +# Read-only adjective forms the \b-bounded write-path nouns intentionally +# do not match (the write path stays byte-frozen; only the read +# path learns these). Keep this list small and obvious. +EXPLAIN_SYNONYMS: Dict[str, str] = { + "blurry": "blur", + "fuzzy": "blur", + "laggy": "animations", + "sluggish": "animations", + "hide": "auto hide", + "hides": "auto hide", + "hidden": "auto hide", + "disappear": "auto hide", + "disappears": "auto hide", +} + +# Phenomenon adjectives that should pick a specific candidate when that +# candidate is already noun-matched ("why is my bar big" -> the SIZE tool, +# not the position tool). Read-only; the write path is unchanged. +EXPLAIN_PREFERENCES: Dict[str, str] = { + "big": "setBarScale", + "large": "setBarScale", + "huge": "setBarScale", + "small": "setBarScale", + "tiny": "setBarScale", + "giant": "setDockIconSize", + "slow": "setAnimationSpeed", + "fast": "setAnimationSpeed", + "speedy": "setAnimationSpeed", + "snappy": "setAnimationSpeed", +} + + +class ExplainError(RuntimeError): + """Raised when a question cannot be answered.""" + + +def _spec_json(spec: ToolSpec) -> Dict[str, Any]: + """Explicit JSON shape for the ``spec`` attached to an explain answer. + + The raw ``ToolSpec`` dataclass is not JSON-serializable, and the + explain result rides through ``cortex`` ``--json`` output and the + brain bridge's ``json.dumps`` — so the spec is flattened field by + field here, mirroring the tools.json row (the same explicit-dict + discipline the PLAN verdict's candidates use). Never a bare object. + """ + return { + "name": spec.name, + "path": spec.path, + "kind": spec.kind, + "default": spec.default, + "minimum": spec.minimum, + "maximum": spec.maximum, + "enum": list(spec.enum) if spec.enum is not None else None, + "global_only": spec.global_only, + "step": spec.step, + "nouns": list(spec.nouns), + "group": spec.group, + "citations": [list(citation) for citation in spec.citations], + "string_max_len": spec.string_max_len, + } + + +def _read_state(target: FileTarget, specs: List[ToolSpec]) -> Dict[str, Any]: + """Effective state for the given specs: file value, else default.""" + import json + + path = Path(target) + data: Dict[str, Any] = {} + if path.exists(): + try: + parsed = json.loads(path.read_text(encoding="utf-8")) + if isinstance(parsed, dict): + data = parsed + except (OSError, ValueError): + raise ExplainError( + f"target file {path} cannot be parsed; nothing was written" + ) + state: Dict[str, Any] = {} + for spec in specs: + node: Any = data + for segment in spec.path.split("."): + if not isinstance(node, dict) or segment not in node: + node = None + break + node = node[segment] + state[spec.path] = spec.default if node is None else node + return state + + +def _paths_in(expr: str) -> List[str]: + """Dotted paths referenced by a rule's `when` predicate.""" + out: List[str] = [] + for token in re.findall(r"[A-Za-z_][\w.]*", expr): + if token not in ("true", "false") and token not in out: + out.append(token) + return out + + +def _values_equal(have: Any, want: Any) -> bool: + if have == want: + return True + if isinstance(have, (int, float)) and isinstance(want, (int, float)) \ + and not isinstance(have, bool) and not isinstance(want, bool): + return abs(float(have) - float(want)) < 1e-9 + if isinstance(have, bool) and isinstance(want, str): + return str(have).lower() == want.lower() + return False + + +def _eval_when(rule: Dict[str, Any], state: Dict[str, Any]) -> bool: + """The restricted predicate grammar (same spec as the QML service): + `path == value` / `!=` / `>` / `<` joined by ` and `. Unknown state + keys (live-session flags the file cannot know) make the rule NOT fire.""" + clauses = str(rule["when"]).split(" and ") + for clause in clauses: + m = re.match(r"^\s*([\w.]+)\s*(==|!=|>|<)\s*(.+?)\s*$", clause) + if not m: + return False + key, op, raw = m.group(1), m.group(2), m.group(3) + have = state.get(key) + if have is None: + return False + if raw == "true": + want: Any = True + elif raw == "false": + want = False + elif re.fullmatch(r"-?\d+(\.\d+)?", raw): + want = float(raw) if "." in raw else int(raw) + else: + want = raw.strip("\"'") + if op == "==": + ok = _values_equal(have, want) + elif op == "!=": + ok = not _values_equal(have, want) + elif op == ">": + ok = isinstance(have, (int, float)) and have > want + else: + ok = isinstance(have, (int, float)) and have < want + if not ok: + return False + return True + + +def _fmt(value: Any) -> str: + if value is True: + return "on" + if value is False: + return "off" + if isinstance(value, float): + return f"{round(value, 2):g}" + return str(value) + + +def _render(template: str, state: Dict[str, Any], cites: Tuple[str, ...]) -> str: + """Render an answer template. Placeholders: + {dotted.path} -> formatted value; {cite}/{citeN} -> citations; + {a|b} -> alternation resolved by the first numeric value placeholder + in the template (> 1 picks the first option). Same spec as QML.""" + out = template + first_numeric: Optional[float] = None + m = re.search(r"\{([A-Za-z_][\w.]*)\}", out) + if m: + v = state.get(m.group(1)) + if isinstance(v, (int, float)) and not isinstance(v, bool): + first_numeric = float(v) + out = re.sub( + r"\{([^{}|]+)\|([^{}]+)\}", + lambda mm: mm.group(1) if (first_numeric is not None and first_numeric > 1) + else mm.group(2), + out, + ) + out = re.sub( + r"\{cite(\d*)\}", + lambda mm: cites[int(mm.group(1)) - 1] if mm.group(1) + else (cites[0] if cites else ""), + out, + ) + out = re.sub( + r"\{([A-Za-z_][\w.]*)\}", + lambda mm: _fmt(state[mm.group(1)]) if mm.group(1) in state else mm.group(0), + out, + ) + return out + + +def resolve_spec(query: str) -> Optional[ToolSpec]: + """A path, a tool name, or a noun-matched question -> one ToolSpec. + + Noun matching reuses the parser's own matcher (so the write and read + surfaces share one noun grammar), with two READ-ONLY refinements the + frozen write path deliberately does not get: + + - EXPLAIN_SYNONYMS: adjective forms ("blurry" -> "blur") that the + \\b-bounded write-path nouns intentionally do not match; + - phenomenon preference: for "why is my X so Y" questions, candidates + whose noun matches in the predicate tail (after is/looks/seems/so) + win over candidates that only matched the subject ("dock" is + incidental in "why is my dock blurry" — the phenomenon is blur). + + Ambiguity that survives both refinements does not guess: None.""" + q = query.strip() + spec = tool_by_path(q) or tool_by_name(q) + if spec is not None: + return spec + text = _normalize(q) + for adj, noun in EXPLAIN_SYNONYMS.items(): + if re.search(rf"\b{re.escape(adj)}\b", text): + text = text.replace(adj, noun) + matched = _noun_matched(text) + if len(matched) > 1: + # Preference adjectives first: an explicit phenomenon word picks + # its tool when that tool is among the candidates. + for word, tool_name in EXPLAIN_PREFERENCES.items(): + if re.search(rf"\b{re.escape(word)}\b", text): + preferred = next((s for s in matched if s.name == tool_name), None) + if preferred is not None: + return preferred + # Phenomenon preference: in "why is my X so Y", Y (the predicate) + # comes LAST — the candidate whose noun matches latest in the + # sentence is the phenomenon being asked about; the subject ("dock" + # in "why is my dock blurry") is incidental. Deterministic and + # position-based; ties stay ambiguous (no guessing). + def last_position(spec: ToolSpec) -> int: + best = -1 + for regex in _NOUN_RES[spec.name]: + for m in regex.finditer(text): + best = max(best, m.end()) + return best + + positions = {spec.name: last_position(spec) for spec in matched} + latest = max(positions.values()) + winners = [s for s in matched if positions[s.name] == latest] + if len(winners) == 1: + return winners[0] + matched = winners + if len(matched) == 1: + return matched[0] + return None + + +def explain(query: str, target: FileTarget) -> Dict[str, Any]: + """Answer one explainability question against the target file. + + Returns {ok, answer, cites, rule, spec} — ``spec`` flattened to a + JSON-serializable dict (see ``_spec_json``), never the raw dataclass. + Never writes. + """ + spec = resolve_spec(query) + if spec is None: + candidates = _noun_matched(_normalize(query)) + if candidates: + names = ", ".join(s.name for s in candidates) + raise ExplainError( + f"the question's noun matches are ambiguous ({names}); " + "name the setting explicitly (a path or a tool name)" + ) + raise ExplainError( + f"cannot resolve {query!r} to a registry setting " + f"(see --list-tools for paths)" + ) + + needed = [spec.path] + for rule in EXPLAIN_RULES: + if rule["path"] != spec.path: + continue + for p in _paths_in(str(rule["when"])): + if p not in needed: + needed.append(p) + state = _read_state(target, [tool_by_path(p) for p in needed if tool_by_path(p)]) + + for rule in EXPLAIN_RULES: + if rule["path"] != spec.path: + continue + if _eval_when(rule, state): + cites = tuple(str(c) for c in rule["cites"]) # type: ignore[arg-type] + return { + "ok": True, + "answer": _render(str(rule["answer"]), state, cites), + "cites": cites, + "rule": True, + "spec": _spec_json(spec), + } + + # Value readback fallback, in the issue's own style. + cite = spec.citations[0][0] if spec.citations else "" + if spec.kind == "enum": + validation = "one of " + "|".join(str(v) for v in (spec.enum or ())) + elif spec.kind == "bool": + validation = "on/off" + elif spec.kind == "string": + validation = "string" + else: + validation = f"range {spec.minimum}-{spec.maximum}" + value = state.get(spec.path, spec.default) + answer = ( + f"The {spec.path} is currently set to {_fmt(value)} " + f"({validation}, default {_fmt(spec.default)}" + + (f"; {cite}" if cite else "") + ")." + ) + return { + "ok": True, + "answer": answer, + "cites": tuple(c[0] for c in spec.citations[:2]), + "rule": False, + "spec": _spec_json(spec), + } + + +# --------------------------------------------------------------------------- +# Multi-hop provenance (issue #120 Phase 1.3) — read-only backward walk: +# current value <- which apply set it (undo history) +# <- which preset/tool call produced that apply (ledger) +# <- that preset's approval rate for this user (bandit) +# Stop at the first ledger entry found or MAX_PROVENANCE_HOPS, whichever +# comes first. Every source is read; nothing is written, ever. +# --------------------------------------------------------------------------- + +MAX_PROVENANCE_HOPS = 5 + + +def _call_paths(ops: List[Any]) -> List[str]: + """Registry paths touched by a ledger diff's call list.""" + from assistant.adapters.caelestia.registry import tool_by_name + + paths: List[str] = [] + for call in ops or []: + if not isinstance(call, dict): + continue + tool = str(call.get("tool", "")) + spec = tool_by_name(tool) + if spec is not None: + paths.append(spec.path) + return paths + + +def _ledger_settings_items(ledger_path: Optional[FileTarget]) -> List[Dict[str, Any]]: + """The ledger's decided settings proposals, newest decision last-walked + first. Missing file -> []. Unreadable -> [] (provenance is best-effort + and read-only; it must never break the explain answer).""" + import json as _json + + if not ledger_path: + return [] + path = Path(ledger_path) + if not path.exists(): + return [] + try: + data = _json.loads(path.read_text(encoding="utf-8")) + except (OSError, ValueError): + return [] + items = data.get("proposals", []) if isinstance(data, dict) else [] + return [i for i in items + if isinstance(i, dict) and i.get("kind") == "settings"] + + +def provenance(query: str, target: FileTarget, + ledger_path: Optional[FileTarget] = None, + bandit_state: Optional[Dict[str, Any]] = None, + max_hops: int = MAX_PROVENANCE_HOPS) -> Dict[str, Any]: + """Backward provenance chain for one setting, fully read-only. + + Returns {ok, path, value, hops, chain, stopped_by} where chain is a + list of rendered hop strings (newest first) and stopped_by names the + stop rule ("no more sources", "ledger entry", or "hop limit"). + """ + from . import history as history_mod + + spec = resolve_spec(query) + if spec is None: + raise ExplainError( + f"cannot resolve {query!r} to a registry setting " + f"(see --list-tools for paths)" + ) + + chain: List[Dict[str, Any]] = [] + stopped_by = "no more sources" + hops = 0 + + # Hop 1: the undo history — which apply set the value most recently. + apply_entry = None + try: + for entry in history_mod.entries(target): # newest first + if any(op.get("path") == spec.path for op in entry.get("ops", [])): + apply_entry = entry + break + except history_mod.HistoryError: + apply_entry = None + if apply_entry is not None and hops < max_hops: + hops += 1 + label = str(apply_entry.get("label") or "(unlabelled)") + chain.append({ + "hop": hops, + "source": "apply history", + "detail": (f"apply #{apply_entry.get('id')} at {apply_entry.get('at')} " + f"set {spec.path} (label: {label})"), + }) + elif apply_entry is not None: + stopped_by = "hop limit" + + # Hop 2: the ledger — which proposal/tool call produced that apply + # (matched by target file + touched path; the ledger file stores + # proposals oldest-first, so walk reversed() = newest first). + ledger_hit = None + items = _ledger_settings_items(ledger_path) + for item in reversed(items): + diff = item.get("diff") or {} + if str(diff.get("file", "")) != str(Path(target)): + continue + if spec.path in _call_paths(diff.get("calls")): + ledger_hit = item + break + if ledger_hit is not None: + if hops < max_hops: + hops += 1 + status = str(ledger_hit.get("status", "?")) + decided = ledger_hit.get("decided_at") or "?" + reason = str(ledger_hit.get("reason") or "") + preset = (ledger_hit.get("diff") or {}).get("preset") + detail = (f"ledger proposal #{ledger_hit.get('id')} ({status} at " + f"{decided}): {reason or 'settings change'}") + if preset: + detail += f" — via preset '{preset}'" + chain.append({ + "hop": hops, + "source": "ledger", + "detail": detail, + "preset": preset, + "status": status, + }) + stopped_by = "ledger entry" + else: + stopped_by = "hop limit" + + # Hop 3: the preset bandit — that preset's approval rate for this user + # (Beta-Binomial posterior mean; preset_bandit.py's NamedBandit arms). + preset_name = None + for hop in chain: + if hop.get("source") == "ledger" and hop.get("preset"): + preset_name = hop["preset"] + break + if preset_name and bandit_state and hops < max_hops: + arms = bandit_state.get("arms") or {} + arm = arms.get(str(preset_name)) + if isinstance(arm, (list, tuple)) and len(arm) == 2: + alpha, beta = float(arm[0]), float(arm[1]) + if alpha + beta > 2.0: # more than the prior (1, 1): real data + hops += 1 + mean = alpha / (alpha + beta) + chain.append({ + "hop": hops, + "source": "preset bandit", + "detail": (f"preset '{preset_name}' approval estimate for " + f"this user: {mean:.2f} " + f"(Beta({alpha:g}, {beta:g}) posterior mean, " + "Thompson-sampling arm)"), + }) + + if len(chain) >= max_hops and stopped_by == "no more sources": + stopped_by = "hop limit" + + return { + "ok": True, + "path": spec.path, + "value": None, # filled by explain(); kept explicit here + "hops": hops, + "chain": chain, + "stopped_by": stopped_by, + } + + +def render_provenance(result: Dict[str, Any]) -> List[str]: + """Plain-text provenance chain for the --explain output.""" + lines = [f"provenance for {result['path']} ({result['hops']} hop(s), " + f"stopped by: {result['stopped_by']})"] + for hop in result["chain"]: + lines.append(f" <- hop {hop['hop']} [{hop['source']}]: {hop['detail']}") + return lines diff --git a/plugins/caelestia-assistant/assistant/capabilities/settings/gen_adapter.py b/plugins/caelestia-assistant/assistant/capabilities/settings/gen_adapter.py new file mode 100644 index 0000000..95df084 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/capabilities/settings/gen_adapter.py @@ -0,0 +1,228 @@ +"""settings.gen_adapter — the registry-generation adapter interface +(phase 2.6). + +The contract this formalizes (previously implicit in build_registry's +CLI + the drift test): + +1. **ONE canonical serialization**: every adapter's dict output renders + through ``canonical_bytes`` — ``json.dumps(data, indent=2, + ensure_ascii=False) + "\\n"`` — and that rendering is THE artifact. + The committed tools.json, the regeneration CLI, and the drift guard + all use this one function, so "byte-identical output" is a property + of the pipeline, not a convention each caller re-implements. +2. **Determinism**: the same (adapter, checkout) pair MUST produce + byte-identical output — no clock, no randomness, no environment + dependence. ``verify()`` proves it: build, render, compare against + a committed artifact, and report drift as a structured diff summary + (never a silent pass). +3. **Registration**: adapters register in ``ADAPTERS`` (name -> build + callable ``repo_root -> dict``). The shipped canonical adapter is + ``cpp-headers`` (build_registry.build — the ONLY settings-layer + piece that reads the caelestia checkout). A third-party adapter + (a fork's generator, a future schema source) registers the same + way; its output must still satisfy the registry loader's schema, + which ``verify_output_schema`` checks structurally. + +CLI: ``python3 -m assistant.capabilities.settings gen_adapter [--adapter NAME] +[--repo-root PATH] [--output PATH] [--verify]`` — generate or verify; +``--verify`` never writes, it compares and reports. + +Safety: generation is a build-time, developer-run act — the runtime +registry loader (registry.py) is untouched, reads the committed +tools.json, and never executes generator code. +""" + +from __future__ import annotations + +import json +import sys +from pathlib import Path +from typing import Any, Callable, Dict, List, Optional + +from . import build_registry + +__all__ = [ + "ADAPTERS", "CANONICAL_ADAPTER", "canonical_bytes", "generate", + "verify", "verify_output_schema", "drift_summary", "main", +] + +# The registered adapters: name -> build(repo_root: str) -> dict. +# Registering a new adapter is a reviewable diff (this dict is pinned +# by test to exactly the canonical name today). +ADAPTERS: Dict[str, Callable[[str], Dict[str, Any]]] = { + "cpp-headers": build_registry.build, +} + +CANONICAL_ADAPTER = "cpp-headers" + + +def canonical_bytes(data: Dict[str, Any]) -> bytes: + """The ONE rendering of a registry build. Every producer and every + comparison goes through here (byte-identity lives in the pipeline, + not in per-caller conventions).""" + return (json.dumps(data, indent=2, ensure_ascii=False) + "\n").encode( + "utf-8") + + +def generate(adapter: str, repo_root: str) -> bytes: + """Build + canonically render one adapter's output.""" + if adapter not in ADAPTERS: + raise ValueError(f"unknown adapter {adapter!r} " + f"(have: {sorted(ADAPTERS)})") + return canonical_bytes(ADAPTERS[adapter](repo_root)) + + +def verify_output_schema(data: Dict[str, Any]) -> List[str]: + """Structural sanity of an adapter's output — the registry loader's + own expectations: meta/tools/not_exposed/presets/explain_rules with + the fields the loader reads. Third-party adapters must satisfy the + same shape (this check says WHY, field by field).""" + problems: List[str] = [] + for key in ("meta", "tools", "not_exposed", "presets", + "explain_rules"): + if key not in data: + problems.append(f"missing top-level key {key!r}") + tools = data.get("tools") + if not isinstance(tools, list) or not tools: + problems.append("tools must be a non-empty list") + tools = [] + for i, tool in enumerate(tools): + if not isinstance(tool, dict): + problems.append(f"tool[{i}] is not an object") + continue + for field in ("name", "path", "kind", "group", "citations"): + if field not in tool: + problems.append(f"tool[{i}] ({tool.get('name', '?')}) " + f"missing {field!r}") + if tool.get("kind") not in ("bool", "int", "float", "enum", + "string"): + problems.append(f"tool {tool.get('name', '?')}: unknown kind " + f"{tool.get('kind')!r}") + meta = data.get("meta") + if isinstance(meta, dict): + for field in ("generator", "repo_commit", "tool_count"): + if field not in meta: + problems.append(f"meta missing {field!r}") + return problems + + +def drift_summary(expected: bytes, actual: bytes) -> Dict[str, Any]: + """A structured, bounded drift report: counts + the first differing + line numbers (never a wall of text).""" + exp_lines = expected.decode("utf-8", errors="replace").splitlines() + act_lines = actual.decode("utf-8", errors="replace").splitlines() + diffs: List[Dict[str, int]] = [] + for i in range(max(len(exp_lines), len(act_lines))): + e = exp_lines[i] if i < len(exp_lines) else None + a = act_lines[i] if i < len(act_lines) else None + if e != a: + diffs.append({"line": i + 1}) + if len(diffs) >= 10: + break + return {"identical": expected == actual, + "n_expected_lines": len(exp_lines), + "n_actual_lines": len(act_lines), + "first_diffs": diffs} + + +def verify(adapter: str, repo_root: str, + committed_path: Path) -> Dict[str, Any]: + """The byte-identity guard as a function: build, render, compare + against the committed artifact, report drift (and schema problems) + structurally. Read-only — never writes.""" + if adapter not in ADAPTERS: + return {"error": f"unknown adapter {adapter!r} " + f"(have: {sorted(ADAPTERS)})"} + if not committed_path.exists(): + return {"error": f"no committed artifact at {committed_path}"} + data = ADAPTERS[adapter](repo_root) + schema_problems = verify_output_schema(data) + rendered = canonical_bytes(data) + committed = committed_path.read_bytes() + report = drift_summary(committed, rendered) + report.update({"adapter": adapter, "repo_root": str(repo_root), + "committed_path": str(committed_path), + "schema_problems": schema_problems}) + return report + + +def main(argv: Optional[List[str]] = None) -> int: + import argparse + + here = Path(__file__).resolve().parent + ap = argparse.ArgumentParser( + prog="caelestia-assist settings gen_adapter", + description="the registry-generation adapter interface: generate " + "or verify the committed tools.json (byte-identity " + "guard; --verify never writes)") + ap.add_argument("--adapter", default=CANONICAL_ADAPTER, + choices=sorted(ADAPTERS), + help="the registered generator (default: the shipped " + "cpp-headers walker)") + ap.add_argument("--repo-root", default=None, + help="caelestia checkout root (default: auto-locate)") + ap.add_argument("--output", default=None, + help="output path (default: tools.json beside this " + "module)") + ap.add_argument("--verify", action="store_true", + help="read-only: build, render, and compare against " + "the committed artifact; report drift and exit " + "non-zero on any") + args = ap.parse_args(argv) + + root = Path(args.repo_root) if args.repo_root else \ + build_registry.find_repo_root(here) + if root is None or not root.exists(): + print("error: cannot locate a caelestia checkout " + "(need shell/plugin/src/Caelestia/Config under the root)", + file=sys.stderr) + return 2 + + out = Path(args.output) if args.output else here / "tools.json" + + if args.verify: + report = verify(args.adapter, str(root), out) + if "error" in report: + print(f"error: {report['error']}", file=sys.stderr) + return 2 + if report["schema_problems"]: + for problem in report["schema_problems"]: + print(f"schema: {problem}", file=sys.stderr) + if report["identical"] and not report["schema_problems"]: + print(f"OK: {out.name} is byte-identical to the " + f"{args.adapter} adapter's output for {root}") + return 0 + print(f"DRIFT: {report['n_expected_lines']} committed lines vs " + f"{report['n_actual_lines']} generated; first diff at line " + f"{report['first_diffs'][0]['line'] if report['first_diffs'] else '?'}", + file=sys.stderr) + print("regenerate with: python3 -m assistant.capabilities.settings gen_adapter " + "--adapter {a} --repo-root {r}".format(a=args.adapter, + r=root), + file=sys.stderr) + return 1 + + data = ADAPTERS[args.adapter](str(root)) + problems = verify_output_schema(data) + if problems: + print("error: adapter output fails the schema check — refusing " + "to write:", file=sys.stderr) + for problem in problems: + print(f" - {problem}", file=sys.stderr) + return 1 + blob = canonical_bytes(data) + tmp = out.with_name(out.name + ".tmp") + tmp.write_bytes(blob) + import os + os.replace(tmp, out) + meta = data.get("meta", {}) + print(f"wrote {out}") + print(f" tools: {meta.get('tool_count', '?')} by group: " + f"{meta.get('group_counts', {})}") + print(f" not exposed: {meta.get('not_exposed_count', '?')} " + f"({meta.get('excluded_by_rule', '?')})") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/plugins/caelestia-assistant/assistant/capabilities/settings/history.py b/plugins/caelestia-assistant/assistant/capabilities/settings/history.py new file mode 100755 index 0000000..92e6a69 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/capabilities/settings/history.py @@ -0,0 +1,292 @@ +"""Bounded undo history for the settings layer (issue #120). + +Issue #120 asks for "a small history" so that "Undo the last change", +"Restore yesterday's theme" and "Revert my last customization" are all +answerable — not just the single most recent write. This module is the +data half: a ring of the last MAX_ENTRIES applies (oldest evicted first), +persisted as a sibling of the target file at +``.assistant-history.json``. + +The WRITE half stays in applier.py (the package's only writer): +- applier.apply(..., label=...) records an entry after every successful + write; +- undo()/undo_by_id() build the reverse plan and hand it back to + applier.apply with record_history=False, so an undo never appears in + the history as a new apply (undo consumes; redo is deliberately not + offered — the issue asks for undo). + +Entry schema: {"id": int, "at": ISO-8601, "label": str, + "ops": [{"path": str, "old": value, "new": value}]} +File schema: {"next_id": int, "entries": [entry, ...]} (newest first). + +Pure data + JSON I/O on exactly one sibling path; no execution, no +network, no other file is touched. +""" + +from __future__ import annotations + +import json +import os +from datetime import datetime, timezone +from pathlib import Path +from typing import Any, Dict, List, Tuple, Union + +from assistant.adapters.caelestia.registry import tool_by_path + +HISTORY_SUFFIX = ".assistant-history.json" +MAX_ENTRIES = 12 # >= the required 10; oldest evicted first + +# A3 — the PII-stripped negative-example store. Every UNDO (the user +# rejecting an applied change by reverting it) appends one record per +# undone op: {tool, magnitude, direction, quick} and NOTHING else — no +# timestamp, no label, no old/new values, no raw text (the PII-strip +# rule). ``quick`` is computed AT UNDO TIME from the ring itself: the +# undone apply was still the head of the bounded history when it was +# reverted, i.e. an immediate revert with no later apply separating it +# from the top — a relative fact about the interaction, not a time, so +# it stays inside the strip rule while letting calibration weight +# approve-then-immediately-revert apart from a selective old restore. +# The store lives INSIDE the existing history file (same _save atomic +# write path, same sibling path — no new write surface) and survives +# the 12-entry ring's evictions; it is itself bounded (FIFO at +# UNDO_LOG_MAX) so the config directory cannot grow without limit — the +# same discipline the settings design notes (see module docstrings) applies to the ring. +UNDO_LOG_MAX = 500 +UNDO_LOG_KEY = "undo_log" + +FileTarget = Union[str, Path] + + +class HistoryError(RuntimeError): + """Raised when the history cannot be read or an undo is impossible.""" + + +def _resolved(file_path: FileTarget) -> Path: + return Path(os.path.realpath(str(file_path))) + + +def history_path(target: FileTarget) -> Path: + return _resolved(target).with_name(_resolved(target).name + HISTORY_SUFFIX) + + +def _load(target: FileTarget) -> Dict[str, Any]: + path = history_path(target) + if not path.exists(): + return {"next_id": 1, "entries": []} + try: + data = json.loads(path.read_text(encoding="utf-8")) + except (OSError, ValueError) as exc: + raise HistoryError( + f"history file {path} is unreadable ({exc}); undo is refused, " + "nothing was written" + ) from exc + if not isinstance(data, dict) or not isinstance(data.get("entries"), list): + raise HistoryError( + f"history file {path} is not a valid history document; undo is " + "refused, nothing was written" + ) + data.setdefault("next_id", len(data["entries"]) + 1) + if not isinstance(data.get(UNDO_LOG_KEY), list): + data[UNDO_LOG_KEY] = [] + return data + + +def _save(target: FileTarget, data: Dict[str, Any]) -> None: + path = history_path(target) + data["entries"] = data["entries"][:MAX_ENTRIES] # FIFO: oldest evicted + log = data.setdefault(UNDO_LOG_KEY, []) + data[UNDO_LOG_KEY] = log[-UNDO_LOG_MAX:] # bounded: oldest evicted + tmp = path.with_name(path.name + ".tmp") + tmp.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8") + os.replace(tmp, path) + + +def record(target: FileTarget, label: str, + ops: List[Dict[str, Any]]) -> Dict[str, Any]: + """Append one apply to the ring (called by applier.apply only, after a + successful write). Oldest entries are evicted beyond MAX_ENTRIES.""" + data = _load(target) + entry = { + "id": int(data["next_id"]), + "at": datetime.now(timezone.utc).isoformat(timespec="seconds"), + "label": str(label or ""), + "ops": [ + {"path": str(op["path"]), + "old": op.get("old"), + "new": op.get("new")} + for op in ops + ], + } + data["next_id"] = int(data["next_id"]) + 1 + data["entries"].insert(0, entry) + _save(target, data) + return entry + + +def entries(target: FileTarget) -> List[Dict[str, Any]]: + """The undo history, newest first (a copy).""" + return [dict(e) for e in _load(target)["entries"]] + + +def undo_log(target: FileTarget) -> List[Dict[str, Any]]: + """The PII-stripped negative-example store (a copy, oldest first). + + Records are {"tool": registry tool name, "magnitude": float, + "direction": -1|0|+1, "quick": bool} — nothing else, by construction + (see _negative_records). ``quick`` marks an immediate revert: the + undone apply was still the head of the bounded ring, so nothing was + applied between it and the undo. Read-only; the brain layer folds + these into Beta-Binomial calibration as explicit negative signal, + weighting a quick revert stronger than a plain reject.""" + return [dict(rec) for rec in _load(target).get(UNDO_LOG_KEY, [])] + + +def _negative_records(entry: Dict[str, Any], + quick: bool = False) -> List[Dict[str, Any]]: + """A3: PII-strip one history entry into negative-example records. + + One record per undone op whose path resolves to a registry tool: + the TOOL (registry id), the MAGNITUDE of the applied change + (|new - old| for numbers; 1.0 for bools), its DIRECTION (sign of + new - old; +1 = turned on for bools), and QUICK (the undone apply + was still the head of the bounded ring at undo time — an immediate + revert, no later apply in between; computed by the caller from the + ring, never stored as a time). No timestamps, no labels, no values, + no raw text — the record cannot identify a person, a file, or a + time, which is what makes keeping it forever acceptable. + Pure: operates on the passed entry only. + """ + records: List[Dict[str, Any]] = [] + for op in entry.get("ops", []): + spec = tool_by_path(str(op.get("path", ""))) + if spec is None: + continue + old, new = op.get("old"), op.get("new") + if spec.kind == "bool": + records.append({"tool": spec.name, "magnitude": 1.0, + "direction": 1 if new is True else -1, + "quick": bool(quick)}) + elif isinstance(new, (int, float)) and not isinstance(new, bool): + # old=None means the key was ABSENT before the apply: the + # registry default is the honest baseline (a scale of 1.3 + # introduced against default 1.0 is magnitude 0.3, not 1.3). + baseline = old if isinstance(old, (int, float)) and not isinstance(old, bool) \ + else spec.default + if isinstance(baseline, (int, float)) and not isinstance(baseline, bool): + delta = float(new) - float(baseline) + records.append({"tool": spec.name, + "magnitude": abs(delta), + "direction": (delta > 0) - (delta < 0), + "quick": bool(quick)}) + else: + records.append({"tool": spec.name, "magnitude": 0.0, + "direction": 0, "quick": bool(quick)}) + else: + # enum/string values carry choice information, not a magnitude — + # only the fact of the undo is retained, direction 0. + records.append({"tool": spec.name, "magnitude": 0.0, + "direction": 0, "quick": bool(quick)}) + return records + + +def _reverse_plan(entry: Dict[str, Any]) -> Tuple[Dict[str, Any], List[str]]: + """Build an applier plan that restores the entry's old values.""" + plan_entries: List[Dict[str, Any]] = [] + skipped: List[str] = [] + for op in entry.get("ops", []): + path = str(op.get("path", "")) + spec = tool_by_path(path) + if spec is None: + skipped.append(path) + continue + plan_entries.append({ + "tool": spec.name, + "path": path, + "action": "set", + "raw": f"undo #{entry.get('id')} {path}", + "new": op.get("old"), + # old=None means the key was ABSENT before that apply: the undo + # removes it again (applier._deep_unset) instead of writing null. + "unset": op.get("old") is None, + }) + plan = {"entries": plan_entries, "apply_blocked": False} + return plan, skipped + + +def undo(target: FileTarget, steps: int = 1) -> Dict[str, Any]: + """Undo the newest `steps` applies (default 1). Returns the applier's + result for the combined reverse plan. Consumed entries are removed.""" + from .applier import apply as apply_plan # local import: applier writes + + if steps < 1: + raise HistoryError("undo steps must be >= 1") + data = _load(target) + if not data["entries"]: + return {"restored": False, + "message": "nothing to undo (the history is empty)"} + steps = min(steps, len(data["entries"])) + combined: List[Dict[str, Any]] = [] + labels: List[str] = [] + negative: List[Dict[str, Any]] = [] + for _ in range(steps): + entry = data["entries"][0] + plan, skipped = _reverse_plan(entry) + combined.extend(plan["entries"]) + labels.append(str(entry.get("label") or f"#{entry.get('id')}")) + negative.extend(_negative_records(entry, quick=True)) # A3: keep the PII-stripped trail + data["entries"].pop(0) + if negative: + data.setdefault(UNDO_LOG_KEY, []).extend(negative) + if not combined: + _save(target, data) + return {"restored": False, + "message": "the history entries reference no registry paths; " + "they were consumed without a write"} + result = apply_plan({"entries": combined, "apply_blocked": False}, + target, write=True, record_history=False) + _save(target, data) + note = f"undid {steps} apply entr{'y' if steps == 1 else 'ies'} ({'; '.join(labels)})" + result["message"] = f"{note}; {result.get('message', '')}".strip("; ") + return result + + +def undo_by_id(target: FileTarget, entry_id: int) -> Dict[str, Any]: + """Revert one specific history entry ('restore yesterday's theme'): + the entry's old values are written back and the entry is consumed. + Entries applied AFTER it are left as they are — reverting an old entry + can produce a state that never existed if later applies touched the + same keys; that is inherent to per-entry undo and stated plainly.""" + from .applier import apply as apply_plan + + data = _load(target) + index = next((i for i, e in enumerate(data["entries"]) + if int(e.get("id", -1)) == int(entry_id)), -1) + if index == -1: + raise HistoryError( + f"no history entry with id {entry_id}; see --history" + ) + entry = data["entries"][index] + plan, skipped = _reverse_plan(entry) + data["entries"].pop(index) + # quick only for an immediate revert: the entry was still the head of + # the bounded ring, so no later apply separates it from the undo. + negative = _negative_records(entry, quick=(index == 0)) # A3: keep the PII-stripped trail + if negative: + data.setdefault(UNDO_LOG_KEY, []).extend(negative) + if not plan["entries"]: + _save(target, data) + return {"restored": False, + "message": f"entry #{entry_id} references no registry paths; " + "consumed without a write"} + result = apply_plan(plan, target, write=True, record_history=False) + _save(target, data) + label = entry.get("label") or "unlabelled" + at = entry.get("at", "?") + n = len(entry.get("ops", [])) + result["message"] = ( + f"reverted '{label}' ({n} change(s), applied {at}); " + + result.get("message", "") + ).strip("; ") + if skipped: + result["skipped_paths"] = skipped + return result diff --git a/plugins/caelestia-assistant/assistant/capabilities/settings/lint.py b/plugins/caelestia-assistant/assistant/capabilities/settings/lint.py new file mode 100644 index 0000000..37cc2a3 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/capabilities/settings/lint.py @@ -0,0 +1,256 @@ +"""Config health linter for shell.json (issue #120 Phase 1.1). + +A deterministic rule engine over the target config — the same discipline as +assistant/diagnostics/engine.py, but applied to the live shell.json instead +of pasted logs. Read-only: it never writes, it only reports findings. + +Checks (each grounded in the frozen registry, never guessed): + +1. unknown-key — a leaf present in shell.json that is neither a registry + tool path nor a known not_exposed path. Likely stale, + renamed upstream, or hand-edited; the shell's ConfigObject + would silently ignore it. +2. out-of-range — a leaf whose value is outside the shipped Nexus control + range transcribed in tools.json (the same range the + planner enforces on every apply; a hand edit is not + validated that way, so drift lands here). +3. type-mismatch — a leaf whose JSON type differs from the registry kind + (bool/int/float/string/enum). +4. silent-noop — a leaf that is currently having no effect because a + gate it depends on is off. Grounded in the registry's + own EXPLAIN_RULES: the blur regions gate on + transparency.enabled && blur together + (shell/modules/drawers/blur/BlurOffsets.qml:17), so + blur=true with transparency disabled is inert. +5. inert-customized — a strength/value leaf that differs from its default + while its master switch is off: the customization is + currently inert (reported as info, not an error). + +Every finding carries: id, path, severity (error|warning|info), message, +cite (the registry fact that grounds it) and a fix hint. Exit semantics are +the CLI's decision; nothing here fails or writes. + +lint_rules_ok() validates this module's own rule table (used by +`caelestia-assist selfcheck`, so a malformed lint rule fails the selfcheck +the same way a malformed rules.d file does). +""" + +from __future__ import annotations + +import json +from pathlib import Path +from typing import Any, Dict, List, Optional, Union + +from assistant.adapters.caelestia.registry import NOT_EXPOSED, TOOL_COUNT, tool_by_path + +FileTarget = Union[str, Path] + +# Gates for the silent-noop / inert-customized rules, stated as +# (gate_path, gated_path, gate_value, grounded_cite). The blur gate is the +# registry's own explain rule (see module docstring) — the only cross-key +# gate the shipped config documents in terms shell.json itself can express. +_NOOP_GATES = ( + { + "id": "silent-noop-blur-without-transparency", + "gate": "appearance.transparency.enabled", + "gate_value": False, + "gated": "appearance.blur", + "gated_value": True, + "severity": "warning", + "cite": ("assistant/settings/tools.json explain_rules[1] — " + "shell/modules/drawers/blur/BlurOffsets.qml:17"), + "message": ("blur is enabled but has no effect while transparency is " + "disabled: the blur regions gate on transparency.enabled " + "&& blur together"), + "fix": "enable appearance.transparency.enabled, or leave blur off", + }, + { + "id": "inert-customized-transparency-base", + "gate": "appearance.transparency.enabled", + "gate_value": False, + "gated": "appearance.transparency.base", + "gated_value": "__non_default__", + "severity": "info", + "cite": ("assistant/settings/registry.py — appearance.transparency.base " + "default 0.85 (shipped Nexus control, SliderRow)"), + "message": ("transparency.base is customized but currently inert: " + "transparency is disabled"), + "fix": ("re-enable appearance.transparency.enabled, or accept the " + "customization is dormant"), + }, +) + + +def flatten_leaves(node: Any, prefix: str = "") -> List[tuple]: + """Flatten a nested JSON object to [(dotted_path, value)]. + + Public since exponential-build-3 Phase 2: brain/topology.py + flattened the same shape with its own identical private walker + (found by the repo's own MinHash scan) — this is the one + implementation now (brain importing from settings is the + precedented direction: brain/service.py::settings_bridge).""" + leaves: List[tuple] = [] + if isinstance(node, dict): + for key, value in node.items(): + path = f"{prefix}.{key}" if prefix else str(key) + if isinstance(value, dict): + leaves.extend(flatten_leaves(value, path)) + else: + leaves.append((path, value)) + return leaves + + +def _known_non_tool_paths(specs: Optional[List[Any]]) -> List[str]: + """Registry paths that exist in shell.json but are not exposed as tools + (the not_exposed table: real ConfigObject leaves the assistant must not + manage — credentials, endpoints, internal state).""" + from assistant.adapters.caelestia.registry import NOT_EXPOSED # (path, reason) pairs from tools.json + + return [path for path, _reason in NOT_EXPOSED] + + +def _read_config(target: FileTarget) -> Dict[str, Any]: + path = Path(target) + if not path.exists(): + return {} + parsed = json.loads(path.read_text(encoding="utf-8")) + if not isinstance(parsed, dict): + raise ValueError(f"{path} is not a JSON object") + return parsed + + +def lint(config: Dict[str, Any], specs: Optional[List[Any]] = None) -> List[Dict[str, Any]]: + """Lint one parsed shell.json (dict of dicts) and return findings. + + Deterministic, read-only, and honest: every finding names the registry + fact it is grounded in. No findings does not mean "perfect config" — + it means "nothing this rule set can check is wrong". + """ + from assistant.adapters.caelestia.registry import TOOL_SPECS # the frozen table, import-cheap + + specs = specs if specs is not None else TOOL_SPECS + known_paths = {s.path for s in specs} + findings: List[Dict[str, Any]] = [] + + non_tool_paths = _known_non_tool_paths(specs) + leaves = flatten_leaves(config) + + # Pass 1: per-leaf registry checks. + for path, value in leaves: + spec = tool_by_path(path) + if spec is None: + if path in non_tool_paths: + continue # known ConfigObject leaf, deliberately unmanaged + findings.append({ + "id": "unknown-key", + "path": path, + "severity": "warning", + "message": ("not a registry tool path and not a known " + "non-tool leaf: stale, renamed upstream, or " + "hand-edited; the shell ignores unknown keys"), + "cite": ("assistant/settings/tools.json (%d tool paths, %d not_exposed paths)" + % (TOOL_COUNT, len(NOT_EXPOSED))), + "fix": "remove the key, or check the upstream config name", + }) + continue + # kind check + kind = spec.kind + valid = { + "bool": lambda v: isinstance(v, bool), + "int": lambda v: isinstance(v, int) and not isinstance(v, bool), + "float": lambda v: isinstance(v, (int, float)) and not isinstance(v, bool), + "enum": lambda v: isinstance(v, str), + "string": lambda v: isinstance(v, str), + }[kind] + if not valid(value): + findings.append({ + "id": "type-mismatch", + "path": path, + "severity": "warning", + "message": f"registry kind is {kind}, found {type(value).__name__}", + "cite": f"assistant/settings/tools.json — {path} kind={kind}", + "fix": f"set {path} to a {kind} value", + }) + continue + # range check (numeric only; enums are frozen at build time and + # strings carry no range) + if kind in ("int", "float"): + lo, hi = spec.minimum, spec.maximum + if (lo is not None and value < lo) or (hi is not None and value > hi): + findings.append({ + "id": "out-of-range", + "path": path, + "severity": "warning", + "message": (f"value {value} is outside the shipped control " + f"range {lo}-{hi}; the next planned apply of " + "this key would be rejected"), + "cite": f"assistant/settings/tools.json — {path} range {lo}-{hi}", + "fix": f"set {path} between {lo} and {hi}", + }) + + # Pass 2: cross-key gate rules (silent no-ops / inert customizations). + flat = dict(leaves) + by_path: Dict[str, Any] = {} + for path, value in leaves: + by_path.setdefault(path, value) + for rule in _NOOP_GATES: + gate_value = by_path.get(rule["gate"]) + gated_value = by_path.get(rule["gated"]) + if gate_value != rule["gate_value"] or gated_value is None: + continue + if rule["gated_value"] == "__non_default__": + spec = tool_by_path(rule["gated"]) + if spec is None or gated_value == spec.default: + continue + elif gated_value != rule["gated_value"]: + continue + findings.append({ + "id": rule["id"], + "path": rule["gated"], + "severity": rule["severity"], + "message": rule["message"], + "cite": rule["cite"], + "fix": rule["fix"], + }) + + return findings + + +def lint_file(target: FileTarget) -> List[Dict[str, Any]]: + """Lint the JSON file at target (missing file -> no findings).""" + return lint(_read_config(target)) + + +def render_findings(findings: List[Dict[str, Any]]) -> List[str]: + """Plain-text rendering, one line per finding plus its fix hint.""" + if not findings: + return ["config lint: no findings"] + lines = [f"config lint: {len(findings)} finding(s)"] + for f in findings: + lines.append(f"- [{f['severity']}] {f['id']} @ {f['path']}: {f['message']}") + lines.append(f" grounded in: {f['cite']}") + lines.append(f" fix: {f['fix']}") + return lines + + +def lint_rules_ok() -> List[str]: + """Structural self-validation of the rule table above (same spirit as + schema_lint.check_rule_files): every gate rule must name registry paths + that actually exist, have a severity the renderer understands, and carry + message/cite/fix strings. Returns a list of failures (empty = OK).""" + from assistant.adapters.caelestia.registry import NOT_EXPOSED, TOOL_COUNT, tool_by_path as _tbp + + failures: List[str] = [] + severities = {"error", "warning", "info"} + for rule in _NOOP_GATES: + rid = rule.get("id", "") + for key in ("gate", "gated", "message", "cite", "fix", "severity"): + if key not in rule: + failures.append(f"lint rule {rid}: missing {key!r}") + if rule.get("severity") not in severities: + failures.append(f"lint rule {rid}: bad severity {rule.get('severity')!r}") + if _tbp(str(rule.get("gate", ""))) is None: + failures.append(f"lint rule {rid}: gate {rule.get('gate')!r} is not a registry path") + if _tbp(str(rule.get("gated", ""))) is None: + failures.append(f"lint rule {rid}: gated {rule.get('gated')!r} is not a registry path") + return failures diff --git a/plugins/caelestia-assistant/assistant/capabilities/settings/macros.py b/plugins/caelestia-assistant/assistant/capabilities/settings/macros.py new file mode 100644 index 0000000..6d3acc2 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/capabilities/settings/macros.py @@ -0,0 +1,210 @@ +"""Settings macros — capture an APPROVED proposal sequence as a named, +replayable template (exponential-build-3 C3). + +Cypher (ed.) 1993, "Watch What I Do: Programming by Demonstration", +MIT Press — the programming-by-demonstration pattern: a demonstrated +action sequence (here: a settings change the user previewed, consented +to, and had applied) is recorded under a name and replayed on demand. +The capture/replay machinery itself is not novel and is not claimed to +be; what is engineered here is the CONSENT DISCIPLINE around it, which +is the whole point in a layer whose only writer is a gated applier. + +THE CONSENT CONTRACT (read before trusting a replay): + +- a macro is captured ONLY from an undo-history entry — i.e. from a + proposal sequence that already passed the full preview -> consent -> + apply gate once. There is deliberately no way to capture a macro + from an unapplied plan: a template is a record of something the user + actually approved, not something they merely asked about; +- REPLAY NEVER WRITES BY ITSELF. ``macro_ops`` returns plain planner + ops (the same shape ``presets.preset_ops`` produces), so a replay + rides the ordinary plan/render path: dry-run preview by default, and + even with ``--apply`` the CLI demands the second consent + (``--confirm`` or the interactive y/N) for EVERY macro — single-op + macros included, deliberately stronger than the plain >1-change + rule, because a replay's contents may no longer be in the user's + head. The applied replay records its OWN history entry + (label "macro: NAME"), so bounded undo works per replay; +- replay re-validates against the LIVE registry: ops carry tool names + and the planner resolves them against the current tool table and the + current file state. A macro recorded against an older registry (a + renamed/removed tool) produces an honest error entry and a blocked + apply, never a silent write; a macro whose values are already in + place is an honest no-op ("no changes needed"). + +STORAGE (no new write surface): the macro store lives INSIDE the +existing undo-history file at ``.assistant-history.json``, +under a bounded ``"macros"`` key — the same file, the same +``history._save`` atomic write path, the same sibling path as the A3 +``undo_log`` precedent, so the applier's documented four-path write +scope (and test_safety.py's directory-snapshot assertion of it) is +unchanged. Capture and delete are explicit user commands (like undo +itself); the target file is never touched by this module — the +applier behind ``--apply``/``--confirm`` remains the only writer of +shell.json. The store is bounded (MAX_MACROS, FIFO: oldest capture +evicted first) so the config directory cannot grow without limit, the +same discipline the history ring applies. + +Each stored macro is {"name", "label" (the captured request sentence), +"from_id" (the source history entry), "captured_at" (ISO-8601), "ops": +[{"tool", "path", "value"}]} — the APPLIED values only; the old values +stay in the history entry where they belong (a macro is not an undo +artifact). + +Pure module apart from the documented history-file reads/writes: no +execution, no network, no RNG; same inputs -> same stored bytes +(the captured_at timestamp is the one field that differs per call, by +design and by precedent — history.record does the same). +""" + +from __future__ import annotations + +import re +from datetime import datetime, timezone +from pathlib import Path +from typing import Any, Dict, List, Optional, Union + +from . import history +from assistant.adapters.caelestia.registry import tool_by_path + +__all__ = ["MacroError", "MAX_MACROS", "list_macros", "save", + "macro_ops", "delete"] + +MAX_MACROS = 16 +MACROS_KEY = "macros" + +# Macro names: start alnum, then alnum/space/underscore/dot/dash, at +# most 32 chars — generous enough for "focus mode" or +# "evening-gaming.v2", narrow enough to stay unambiguous in a CLI flag. +NAME_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9 _.\-]{0,31}") + +FileTarget = Union[str, Path] + + +class MacroError(ValueError): + """Raised for every refusal (unknown macro, bad name, empty or + stale source entry, duplicate name); the caller renders the reason + — nothing is guessed, nothing is silently overwritten.""" + + +def list_macros(target: FileTarget) -> List[Dict[str, Any]]: + """The saved macros, oldest capture first (a copy). Read-only.""" + return [dict(m) for m in history._load(target).get(MACROS_KEY, [])] + + +def save(target: FileTarget, name: str, + from_id: Optional[int] = None) -> Dict[str, Any]: + """Capture one APPROVED apply (an undo-history entry) as a macro. + + ``from_id`` selects the entry (see ``--history`` for ids); the + default is the NEWEST entry — "save what I just did". The entry's + applied ops are re-resolved against the live registry at capture + time: a path the registry no longer knows refuses the whole capture + (named), because a partially stale template is worse than none. + Writes only the history file's "macros" key (see the module + docstring); never the target.""" + if not NAME_RE.fullmatch(str(name or "")): + raise MacroError( + f"macro names must match {NAME_RE.pattern!r} (start with a " + f"letter or digit; letters, digits, spaces, '_', '.', '-' " + f"afterwards; at most 32 characters) — got {name!r}") + data = history._load(target) + entries = data.get("entries", []) + if not entries: + raise MacroError( + "nothing to capture: the undo history is empty (a macro " + "records an apply you already approved; apply something " + "first, then capture it)") + if from_id is None: + entry = entries[0] + from_id = entry.get("id") + else: + entry = next((e for e in entries + if int(e.get("id", -1)) == int(from_id)), None) + if entry is None: + raise MacroError( + f"no history entry with id {from_id}; see --history " + "for the ids in the bounded ring") + if any(m.get("name") == name for m in data.get(MACROS_KEY, [])): + raise MacroError( + f"a macro named {name!r} already exists; delete it first " + f"(--macro-delete {name}) — captures never silently " + "overwrite") + ops: List[Dict[str, Any]] = [] + stale = [] + for op in entry.get("ops", []): + path = str(op.get("path", "")) + spec = tool_by_path(path) + if spec is None: + stale.append(path) + continue + ops.append({"tool": spec.name, "path": spec.path, + "value": op.get("new")}) + if stale: + raise MacroError( + f"history entry #{from_id} references path(s) no longer in " + f"the registry: {', '.join(sorted(set(stale)))}; refusing " + "to capture a partially stale macro (delete nothing, fix " + "nothing — the sequence as applied cannot be replayed " + "honestly)") + if not ops: + raise MacroError( + f"history entry #{from_id} references no registry paths; " + "there is nothing replayable to capture") + macro = { + "name": name, + "label": str(entry.get("label") or ""), + "from_id": from_id, + "captured_at": datetime.now(timezone.utc).isoformat( + timespec="seconds"), + "ops": ops, + } + data.setdefault(MACROS_KEY, []).append(macro) + data[MACROS_KEY] = data[MACROS_KEY][-MAX_MACROS:] # FIFO eviction + history._save(target, data) + return macro + + +def macro_ops(target: FileTarget, name: str) -> List[Dict[str, Any]]: + """A macro's replay ops, in the plain planner-op shape (the same + shape ``presets.preset_ops`` produces: tool / action / value / + raw), so the replay rides the ordinary plan -> preview -> consent + path with no bespoke writer. Read-only; raises MacroError for an + unknown name (listing the saved ones).""" + for macro in history._load(target).get(MACROS_KEY, []): + if macro.get("name") == name: + return [ + {"tool": str(op.get("tool")), + "action": "set", + "value": op.get("value"), + "raw": f"macro {name}: {op.get('tool')}=" + f"{op.get('value')!r}"} + for op in macro.get("ops", []) + ] + saved = [str(m.get("name")) for m in + history._load(target).get(MACROS_KEY, [])] + hint = (", ".join(saved) if saved + else "(no macros saved yet; capture one with --macro-save)") + raise MacroError(f"unknown macro {name!r}; saved macros: {hint}") + + +def delete(target: FileTarget, name: str) -> Dict[str, Any]: + """Remove one macro by name (an explicit user command; writes only + the history file's "macros" key). Raises MacroError for an unknown + name — never a silent no-op delete.""" + data = history._load(target) + macros = data.get(MACROS_KEY, []) + kept = [m for m in macros if m.get("name") != name] + if len(kept) == len(macros): + saved = [str(m.get("name")) for m in macros] + raise MacroError( + f"unknown macro {name!r}; saved macros: " + + (", ".join(saved) if saved else "(none)")) + removed = next(m for m in macros if m.get("name") == name) + if kept: + data[MACROS_KEY] = kept + else: + data.pop(MACROS_KEY, None) + history._save(target, data) + return {"deleted": name, "from_id": removed.get("from_id"), + "ops": len(removed.get("ops", []))} diff --git a/plugins/caelestia-assistant/assistant/capabilities/settings/manifest.py b/plugins/caelestia-assistant/assistant/capabilities/settings/manifest.py new file mode 100644 index 0000000..669e20f --- /dev/null +++ b/plugins/caelestia-assistant/assistant/capabilities/settings/manifest.py @@ -0,0 +1,10 @@ +"""Manifest for the settings capability: permissions, risk tier, budgets.""" +from assistant.capabilities._registry import CapManifest + +MANIFEST = CapManifest( + name="settings", + permissions=("settings:read", "settings:write-behind-confirm",), + risk_tier="confirm", + latency_budget_ms=600, + memory_budget_mb=40, +) diff --git a/plugins/caelestia-assistant/assistant/capabilities/settings/monitors.py b/plugins/caelestia-assistant/assistant/capabilities/settings/monitors.py new file mode 100644 index 0000000..9c66284 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/capabilities/settings/monitors.py @@ -0,0 +1,137 @@ +"""assistant.capabilities.settings.monitors — monitor-aware planning (F20, +exponential-build-5; issue #120 b6d, closed from NOT_IMPLEMENTED). + +What upstream actually provides (verified against the checkout, cited): + +- EVERY config type layers per-screen overrides: ``Root::forScreen`` + (shell/plugin/src/Caelestia/Config/rootnodes.cpp:87-94) reads + ``monitorConfigDir()`` (shell/plugin/src/Caelestia/Config/common.cpp:15-17, + i.e. ``/monitors``) with the SAME file name as the global + config — so ``~/.config/caelestia/monitors//shell.json`` + overrides shell.json for that screen, same schema; +- the shipped Nexus DesktopPage writes per-screen values through + ``GlobalConfig.forScreen`` (shell/modules/nexus/pages/DesktopPage.qml:33); +- a handful of GLOBAL keys select monitor BEHAVIOR (notifs.monitor + "all"|"focused", bar.workspaces.perMonitor, tabSwitch.allScreens, ...) + — the registry already carries them with their own citations. + +What a stdlib-only assistant CANNOT do (honest): enumerate the +CONNECTED screens — that lives in Quickshell/Wayland. This module +therefore works with the override FILES that exist (or are explicitly +named) and never invents screen names. + +Design: ``--monitor NAME`` is a TARGET RESOLVER, not a new writer. It +points the ordinary settings machinery (parser, planner, applier, +backup sibling, history) at +``/monitors//shell.json``; everything else — dry-run +default, validation, confirmation, undo — is exactly the machinery +that already exists for shell.json. ``--monitors`` is the read-only +report: discovered override files, their registry-valid/unknown keys, +and the monitor-behavior tools with citations. +""" + +from __future__ import annotations + +import re +from pathlib import Path +from typing import Any, Dict, List, Optional + +from assistant.adapters.caelestia.registry import TOOL_SPECS + +__all__ = ["MONITOR_NAME_RE", "monitors_dir", "resolve_target", + "discover", "monitor_behavior_tools"] + +MONITOR_NAME_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.\-]{0,63}") + +# Registry tools whose SEMANTICS select or scope monitor behavior +# (path-verified; each carries its own upstream citations). +_BEHAVIOR_PATTERNS = ( + "monitor", "screen", "allscreens", +) + + +def monitors_dir(target: Path) -> Path: + """The monitors override directory for a config target: siblings of + the target file (the target's parent IS the config dir).""" + return Path(target).parent / "monitors" + + +def resolve_target(target: Path, monitor: str) -> Path: + """The override file for one screen name. The name is validated + (no separators, no traversal — a screen name is a single path + component); the file itself need not exist yet (planning against a + not-yet-written override is the same as planning against an empty + config).""" + if not MONITOR_NAME_RE.fullmatch(str(monitor or "")): + raise ValueError( + f"monitor names must match {MONITOR_NAME_RE.pattern!r} " + f"(a single path component; no '/', no '..') — got " + f"{monitor!r}") + return monitors_dir(target) / str(monitor) / Path(target).name + + +def _flatten(node: Any, prefix: str = "", + out: Optional[Dict[str, Any]] = None) -> Dict[str, Any]: + if out is None: + out = {} + if isinstance(node, dict): + for key, value in node.items(): + path = f"{prefix}.{key}" if prefix else key + if isinstance(value, dict): + _flatten(value, path, out) + else: + out[path] = value + return out + + +def discover(target: Path) -> List[Dict[str, Any]]: + """The override files that ALREADY exist under monitors/ (read-only + discovery of files, not of connected screens — see the module + docstring). Each entry reports how many of its keys are + registry-managed and how many are unknown to the registry.""" + import json + base = monitors_dir(target) + found: List[Dict[str, Any]] = [] + if not base.is_dir(): + return found + known_paths = {spec.path for spec in TOOL_SPECS} + for screen_dir in sorted(base.iterdir()): + if not screen_dir.is_dir(): + continue + override = screen_dir / Path(target).name + if not override.is_file(): + continue + managed = unknown = 0 + try: + content = json.loads(override.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError): + found.append({"screen": screen_dir.name, "path": str(override), + "error": "not valid JSON"}) + continue + for path in _flatten(content if isinstance(content, dict) else {}): + if path in known_paths: + managed += 1 + else: + unknown += 1 + found.append({"screen": screen_dir.name, "path": str(override), + "managed_keys": managed, "unknown_keys": unknown}) + return found + + +def monitor_behavior_tools() -> List[Dict[str, Any]]: + """The global registry tools that select or scope monitor behavior, + with their citations (read-only metadata for the --monitors + report).""" + rows = [] + for spec in TOOL_SPECS: + atoms = (spec.name + " " + spec.path).lower().replace(".", " ") + if any(pattern in atoms for pattern in _BEHAVIOR_PATTERNS): + rows.append({ + "name": spec.name, + "path": spec.path, + "kind": spec.kind, + "default": spec.default, + "enum": list(spec.enum) if spec.enum else None, + "citations": list(spec.citations), + }) + return rows diff --git a/plugins/caelestia-assistant/assistant/capabilities/settings/optimize.py b/plugins/caelestia-assistant/assistant/capabilities/settings/optimize.py new file mode 100644 index 0000000..4e9a465 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/capabilities/settings/optimize.py @@ -0,0 +1,569 @@ +"""settings.optimize — optimization profiles, Pareto presets, conflict solving. + +Issue #120 Phase 3 ("Context-aware recommendations / Desktop optimization +profiles") as a deterministic, model-free module. Three capabilities: + +1. PROFILES — each objective profile (gaming, battery, minimal, comfort, + accessibility) is a scored preference direction over the registry groups. + `score_plan(profile, ops)` scores a set of tool calls for how well it + serves the objective; `recommend(profile, k)` returns the registry's + highest-leverage default-deviations for that objective, with reasons. + +2. PARETO — `pareto_profiles(ops_sets)` computes the non-dominated frontier + across multiple profiles at once (genius.optimize.pareto_frontier), so + "gaming vs battery" is answered with the actual trade-off set, not a + single patronising "best". + +3. SYNTHESIS — `synthesize(profile, constraints)` finds the setting vector + closest to the profile's ideal point while satisfying hard constraints, + via coordinate descent over the continuous axes and a bounded enumeration + over enum/bool axes. `check_conflicts` runs AC-3 arc-consistency over + declared constraint pairs and reports UNSAT early with the conflicting + domains — "compact AND bar scale 1.6" is refused with reasons, never + half-applied. + +Every produced op flows through the existing planner/applier gates exactly +like any other settings request: this module PROPOSES, it never writes. +""" +from __future__ import annotations + +from typing import Any, Dict, List, Optional, Sequence, Tuple + +from assistant.adapters.caelestia.registry import ToolSpec, tool_by_name +from assistant.capabilities.genius.optimize import pareto_frontier + +__all__ = ["PROFILES", "score_plan", "recommend", "pareto_profiles", + "synthesize", "check_conflicts", "ConstraintError", + "preference_drift"] + +# --------------------------------------------------------------------------- +# 1. Objective profiles +# --------------------------------------------------------------------------- +# Each profile maps registry GROUPS to a preference direction and weight. +# Groups not listed are neutral. `ideal` names per-tool ideal deviations from +# default for the top tools of that objective (1.0 == "push to the useful +# extreme", validated against the registry range at synthesis time). + +PROFILES: Dict[str, Dict[str, Any]] = { + "gaming": { + "description": "fewest composited effects, fastest shell, silent osd", + "groups": { + "effects": ("decrease", 1.0), + "animations": ("decrease", 0.9), + "notifications": ("decrease", 0.7), + "osd": ("decrease", 0.6), + "blur": ("decrease", 0.8), + }, + "target": { + "setAnimationSpeed": 0.4, + "setBlurEnabled": False, + "setTransparencyEnabled": False, + "setGameModeDisableHyprlandAnimations": True, + "setGameModeDisableHyprlandBlur": True, + "setLivePreviews": False, + "setRoundingScale": 0.6, + }, + }, + "battery": { + "description": "less compositing and polling, dimmer luminance effects", + "groups": { + "effects": ("decrease", 0.9), + "blur": ("decrease", 0.9), + "animations": ("decrease", 0.6), + "wallpaper-scheme": ("decrease", 0.3), + }, + "target": { + "setBlurEnabled": False, + "setTransparencyEnabled": False, + "setDisableWallpaperBlur": True, + "setLivePreviews": False, + "setAnimationSpeed": 0.6, + }, + }, + "minimal": { + "description": "smaller surfaces, tighter spacing, fewer decorations", + "groups": { + "bar": ("decrease", 0.7), + "dock": ("decrease", 0.8), + "appearance": ("decrease", 0.6), + "animations": ("decrease", 0.4), + }, + "target": { + "setBarScale": 0.7, + "setDockIconSize": 20, + "setRoundingScale": 0.5, + "setSpacingScale": 0.7, + "setDockBadges": False, + "setLivePreviews": False, + }, + }, + "comfort": { + "description": "larger surfaces, softer motion, easier reading", + "groups": { + "bar": ("increase", 0.6), + "dock": ("increase", 0.6), + "appearance": ("increase", 0.5), + "animations": ("increase", 0.3), + }, + "target": { + "setBarScale": 1.2, + "setDockIconSize": 40, + "setRoundingScale": 1.2, + "setSpacingScale": 1.15, + }, + }, + "accessibility": { + "description": "maximum legibility: large targets, slow motion, clear osd", + "groups": { + "bar": ("increase", 0.8), + "dock": ("increase", 0.8), + "animations": ("decrease", 0.5), + "osd": ("increase", 0.4), + "notifications": ("increase", 0.5), + }, + "target": { + "setBarScale": 1.4, + "setDockIconSize": 48, + "setAnimationSpeed": 1.4, + "setSpacingScale": 1.3, + }, + }, +} + + +def _clamped_ideal(tool: ToolSpec, ideal: Any) -> Any: + """Ideal deviation validated against the registry — out-of-range ideals + are pushed to the nearest legal extreme, never clamped silently into an + invalid op (the planner would reject them anyway).""" + if tool.kind == "bool": + return bool(ideal) + if tool.kind == "enum": + return ideal if tool.enum and ideal in tool.enum else ( + tool.enum[0] if tool.enum else None) + if tool.kind in ("int", "float") and isinstance(ideal, (int, float)): + lo = tool.minimum if tool.minimum is not None else ideal + hi = tool.maximum if tool.maximum is not None else ideal + v = min(hi, max(lo, float(ideal))) + return int(round(v)) if tool.kind == "int" else v + return None + + +def score_plan(profile: str, ops: Sequence[Dict[str, Any]]) -> Dict[str, Any]: + """Score a plan (list of {"tool": name, "value": v}) against a profile. + + The score is the weight-averaged agreement between each op's direction + and the profile's group preferences, normalised to [0, 1]. Unknown tools + count as neutral; ops the profile disagrees with subtract.""" + if profile not in PROFILES: + raise ValueError(f"unknown profile {profile!r}; have {sorted(PROFILES)}") + spec = PROFILES[profile] + groups = spec["groups"] + total_w, score = 0.0, 0.0 + per_op: List[Dict[str, Any]] = [] + for op in ops: + tool = tool_by_name(str(op.get("tool", ""))) + if tool is None: + per_op.append({"tool": op.get("tool"), "agreement": None, + "reason": "unknown tool"}) + continue + direction = _op_direction(tool, op.get("value")) + entry = groups.get(tool.group) + if entry is None: + agreement, weight = 0.5, 0.2 + else: + want, weight = entry + agreement = 1.0 if direction == want else ( + 0.5 if direction == "toggle" else 0.0) + score += agreement * weight + total_w += weight + per_op.append({"tool": tool.name, "group": tool.group, + "direction": direction, + "agreement": round(agreement, 2)}) + norm = round(score / total_w, 3) if total_w else 0.0 + return { + "profile": profile, + "score": norm, + "verdict": ("serves this objective" if norm >= 0.7 else + "mixed for this objective" if norm >= 0.45 else + "works against this objective"), + "per_op": per_op, + } + + +def _op_direction(tool: ToolSpec, value: Any) -> str: + if tool.kind == "bool" or tool.kind == "enum": + return "toggle" + default = tool.default + if isinstance(value, (int, float)) and isinstance(default, (int, float)): + if value > default: + return "increase" + if value < default: + return "decrease" + return "set" + + +def recommend(profile: str, k: int = 6) -> Dict[str, Any]: + """The profile's target ops, validated against the registry, strongest + first. These are PROPOSALS: the planner still range/type-checks them and + the applier still gates them behind explicit confirmation.""" + if profile not in PROFILES: + raise ValueError(f"unknown profile {profile!r}; have {sorted(PROFILES)}") + target = PROFILES[profile]["target"] + ops: List[Dict[str, Any]] = [] + skipped: List[str] = [] + for name, ideal in target.items(): + tool = tool_by_name(name) + if tool is None: + skipped.append(f"{name}: not in this registry build") + continue + v = _clamped_ideal(tool, ideal) + if v is None: + skipped.append(f"{name}: ideal value not representable") + continue + ops.append({"tool": tool.name, "value": v, + "path": tool.path, + "reason": f"{PROFILES[profile]['description']} — " + f"{tool.name} -> {v!r}"}) + return {"profile": profile, + "description": PROFILES[profile]["description"], + "ops": ops[:k], "skipped": skipped} + + +# --------------------------------------------------------------------------- +# 2. Pareto across profiles +# --------------------------------------------------------------------------- + +def pareto_profiles(ops_sets: Dict[str, Sequence[Dict[str, Any]]]) -> Dict[str, Any]: + """Given candidate op-sets (e.g. the recommend() output per profile), + score each against EVERY profile and return the non-dominated frontier + plus the per-profile score matrix. Axes = profiles, all maximised.""" + axes = sorted(ops_sets) + points: List[Dict[str, float]] = [] + meta: List[Dict[str, Any]] = [] + for label, ops in ops_sets.items(): + scores = {a: score_plan(a, ops)["score"] for a in axes} + # axis values must be sortable numbers; flip: use score directly, + # dominance direction handled below (max on every axis) + point = {a: scores[a] for a in axes} + points.append(point) + meta.append({"label": label, "ops": list(ops), "scores": scores}) + # pareto_frontier is min-oriented per direction; pass directions='max' + front = pareto_frontier(points, axes, ["max"] * len(axes)) + front_ids = {id(p) for p in front["front"]} + frontier = [m for m, p in zip(meta, points) if id(p) in front_ids] + dominated = [m for m, p in zip(meta, points) if id(p) not in front_ids] + return {"axes": axes, "frontier": frontier, "dominated": dominated, + "score_matrix": [m["scores"] for m in meta], + "labels": [m["label"] for m in meta]} + + +# --------------------------------------------------------------------------- +# 3. Synthesis + constraint solving +# --------------------------------------------------------------------------- + +class ConstraintError(ValueError): + """Raised when constraints are unsatisfiable; `.domains` carries the + conflicting variables' reduced domains for the error message.""" + + +def _axis(tool: ToolSpec) -> Tuple[str, List[Any]]: + """A synthesis axis: every value the tool may legally take. + int/float axes are stepped by tool.step (bounded enumeration, same + semantics as the Nexus steppers); bool/enum axes are their domains.""" + if tool.kind == "bool": + return tool.name, [False, True] + if tool.kind == "enum": + return tool.name, list(tool.enum or []) + lo = float(tool.minimum if tool.minimum is not None else tool.default) + hi = float(tool.maximum if tool.maximum is not None else tool.default) + step = float(tool.step) if tool.step else (hi - lo) / 8.0 or 1.0 + values: List[float] = [] + v = lo + guard = 0 + while v < hi - 1e-9 and guard < 200: + values.append(v) + v += step + guard += 1 + values.append(hi) + if tool.kind == "int": + return tool.name, sorted({int(round(v)) for v in values}) + return tool.name, sorted({round(v, 6) for v in values}) + + +def check_conflicts(ops: Sequence[Dict[str, Any]], + constraints: Sequence[Tuple[str, str, str]]) -> Dict[str, Any]: + """AC-3 arc consistency over the requested variables. + + constraints: (tool_a, relation, tool_b) where relation is one of + "!=" values must differ + "<" a's value < b's value + ">" a's value > b's value + "with" if a is set then b must be set too (co-presence) + + Domains START at each tool's full legal registry range (the same values + the Nexus steppers can reach), AC-3 narrows them, and the REQUESTED + values are then checked against the narrowed domains: a request that no + longer has support is the conflict, reported with the surviving domain — + never clamped, never half-applied. + """ + domains: Dict[str, List[Any]] = {} + order: List[str] = [] + for op in ops: + tool = tool_by_name(str(op.get("tool", ""))) + if tool is None: + continue + name, dom = _axis(tool) + if name not in domains: + domains[name] = dom + order.append(name) + requested: Dict[str, Any] = { + str(op.get("tool")): op.get("value") for op in ops + if tool_by_name(str(op.get("tool", ""))) is not None} + + def _supported(rel: str, va: Any, db: List[Any]) -> bool: + if rel == "!=": + return any(va != vb for vb in db) + if rel == "<": + return any(float(va) < float(vb) for vb in db) + if rel == ">": + return any(float(va) > float(vb) for vb in db) + return True # "with": co-presence satisfied by b existing + + changed = True + while changed: + changed = False + for a, rel, b in constraints: + if a not in domains or b not in domains: + continue + keep_a = [va for va in domains[a] if _supported(rel, va, domains[b])] + if not keep_a: + raise ConstraintError( + f"unsatisfiable arc {a} {rel} {b}: domain({a})=" + f"{domains[a]} has no support in domain({b})={domains[b]}") + if len(keep_a) != len(domains[a]): + domains[a] = keep_a + changed = True + # reverse arc for symmetry + rev = {"<": ">", ">": "<", "!=": "!=", "with": "with"}[rel] + keep_b = [vb for vb in domains[b] if _supported(rev, vb, domains[a])] + if not keep_b: + raise ConstraintError( + f"unsatisfiable arc {b} {rev} {a}: domain({b})=" + f"{domains[b]} has no support in domain({a})={domains[a]}") + if len(keep_b) != len(domains[b]): + domains[b] = keep_b + changed = True + + pruned = [] + for name in order: + want = requested.get(name) + if want is None: + continue + if tool_by_name(name).kind in ("int", "float"): + survives = any(abs(float(v) - float(want)) <= 1e-9 + for v in domains[name]) + else: + survives = want in domains[name] + if not survives: + pruned.append({"tool": name, "requested": want, + "surviving_domain": domains[name]}) + if pruned: + first = pruned[0] + raise ConstraintError( + f"conflict: {first['tool']}={first['requested']!r} has no support " + f"after constraint propagation; surviving domain " + f"{first['surviving_domain']}") + return {"consistent": True, "domains": {k: domains[k] for k in order}, + "requested": requested} + + +def synthesize(profile: str, + constraints: Sequence[Tuple[str, str, str]] = (), + pinned: Optional[Dict[str, Any]] = None, + max_ops: int = 8) -> Dict[str, Any]: + """Closest legal plan to the profile's ideal point under hard constraints. + + Method: bounded coordinate descent. For each axis (registry tool with a + finite legal domain) pick the value minimising |value - ideal| subject + to arc-consistency with every other axis's current choice (a small + joint check over the constraint arcs, retried a few passes because the + axes interact through the constraints). Deterministic; no RNG.""" + if profile not in PROFILES: + raise ValueError(f"unknown profile {profile!r}; have {sorted(PROFILES)}") + target = dict(PROFILES[profile]["target"]) + if pinned: + target.update(pinned) + + axes: Dict[str, Tuple[ToolSpec, List[Any], Any]] = {} + for name, ideal in target.items(): + tool = tool_by_name(name) + if tool is None: + continue + _n, dom = _axis(tool) + ideal_v = _clamped_ideal(tool, ideal) + axes[name] = (tool, dom, ideal_v) + + assignment: Dict[str, Any] = {} + # pass 1: per-axis nearest-to-ideal + for name, (_tool, dom, ideal_v) in axes.items(): + if ideal_v is None: + assignment[name] = dom[len(dom) // 2] + else: + assignment[name] = min(dom, key=lambda v: abs(float(v) - float(ideal_v))) + + def _arc_ok(rel: str, va: Any, vb: Any) -> bool: + return {"!=": lambda: va != vb, + "<": lambda: float(va) < float(vb), + ">": lambda: float(va) > float(vb), + "with": lambda: True}[rel]() + + def _satisfying_candidates(rel: str, mover: str, vo: Any, + a: str, b: str) -> List[Any]: + """Values for `mover` that satisfy the arc given the OTHER side is + already fixed at vo — constraint-directed, not blind.""" + dom = axes[mover][1] + if rel == "!=": + return [v for v in dom if v != vo] + if rel == "<": # a < b + return ([v for v in dom if float(v) > float(vo)] if mover == b + else [v for v in dom if float(v) < float(vo)]) + if rel == ">": # a > b + return ([v for v in dom if float(v) < float(vo)] if mover == b + else [v for v in dom if float(v) > float(vo)]) + return [] + + # pass 2: repair constraint violations, moving the side that can actually + # fix the arc (b first, then a), always toward its own ideal + for _pass in range(6): + violated = next(((a, rel, b) for a, rel, b in constraints + if a in assignment and b in assignment + and not _arc_ok(rel, assignment[a], assignment[b])), None) + if violated is None: + break + a, rel, b = violated + repaired = False + for mover in (b, a): + other = a if mover == b else b + cands = _satisfying_candidates(rel, mover, assignment[other], a, b) + if not cands: + continue + _tool, _dom, ideal_v = axes[mover] + if ideal_v is None: + assignment[mover] = cands[len(cands) // 2] + else: + assignment[mover] = min( + cands, key=lambda v: abs(float(v) - float(ideal_v))) + if _arc_ok(rel, assignment[a], assignment[b]): + repaired = True + break + if not repaired: + raise ConstraintError( + f"cannot satisfy {a} {rel} {b} with " + f"domains {axes[a][1]} / {axes[b][1]}") + ops = [] + for name in sorted(assignment): + tool, _dom, ideal_v = axes[name] + v = assignment[name] + ops.append({"tool": name, "value": v, "path": tool.path, + "ideal": ideal_v, + "delta_from_ideal": (abs(float(v) - float(ideal_v)) + if isinstance(ideal_v, (int, float)) + and isinstance(v, (int, float)) else 0)}) + ops.sort(key=lambda o: -o["delta_from_ideal"]) + ops = ops[:max_ops] + return {"profile": profile, "ops": ops, + "constraints_checked": len(constraints), + "note": "proposal only — planner validation and the apply gate still apply"} + + + + +# --------------------------------------------------------------------------- +# 5. Config drift vs the preference posterior (B2, issue #120 adjacent) +# --------------------------------------------------------------------------- + +def preference_drift(config, posterior, specs=None, min_evidence=3, + evidence_cap=10, reject_below=0.4): + """Distance between a LIVE config and a Beta-Binomial preference + posterior (B2). PURE: plain data in, plain data out — no file reads, + no writes; the caller (brain side) owns the live file and the model. + + Semantics — "drift" means the config sits in a direction this user's + own decision history says they REJECT: + + - every ranged numeric tool (float/int with a range) whose live value + differs from the registry default contributes its normalized + offset direction (increase/decrease) and magnitude |pos - default|; + - the posterior row for (group, direction) with at least + ``min_evidence`` decisions votes: a low acceptance mean (below + ``reject_below``) is REJECTION of that direction; + - a tool drifts when its live direction is rejected, weighted by + offset magnitude x rejection depth x evidence weight + (min(n, cap)/cap — one decision is one decision, capped at 10); + - tools with thin evidence (< ``min_evidence`` decisions) are + reported in ``thin`` and never scored (the honest abstain the + preference model itself applies). + + Returns {"score": 0..1, "evaluated": k, "flags": [...], "thin": [...]}. + """ + from assistant.adapters.caelestia.registry import TOOL_SPECS as _SPECS + if specs is None: + specs = _SPECS + flags = [] + thin = [] + total = 0.0 + evaluated = 0 + for spec in specs: + if spec.kind not in ("float", "int"): + continue + if spec.minimum is None or spec.maximum is None: + continue + # Resolve the live value along the dotted path (read-only walk). + node = config + missing = False + for segment in spec.path.split("."): + if isinstance(node, dict) and segment in node: + node = node[segment] + else: + missing = True + break + if missing or not isinstance(node, (int, float)) or isinstance(node, bool): + continue + span = float(spec.maximum) - float(spec.minimum) + if span <= 0: + continue + default = spec.default + if not isinstance(default, (int, float)) or isinstance(default, bool): + continue + pos = (float(node) - float(spec.minimum)) / span + dpos = (float(default) - float(spec.minimum)) / span + offset = pos - dpos + if abs(offset) < 1e-9: + continue # at default: no directional claim to disagree with + direction = "increase" if offset > 0 else "decrease" + magnitude = min(1.0, abs(offset)) + row = posterior.get((spec.group or spec.path.split(".")[0], direction)) + evaluated += 1 + if row is None or row.get("n", 0) < min_evidence: + thin.append({"tool": spec.name, "path": spec.path, + "group": spec.group or spec.path.split(".")[0], + "direction": direction, + "n": 0 if row is None else row.get("n", 0)}) + continue + mean = float(row.get("p_accept", 0.5)) + if mean < reject_below: + depth = (reject_below - mean) / reject_below + weight = min(row.get("n", 0), evidence_cap) / float(evidence_cap) + total += magnitude * depth * weight + flags.append({ + "tool": spec.name, "path": spec.path, + "group": spec.group or spec.path.split(".")[0], + "direction": direction, + "live": node, "default": default, + "p_accept": round(mean, 3), "n": row.get("n", 0), + "weight": round(magnitude * depth * weight, 4), + }) + flags.sort(key=lambda f: -f["weight"]) + score = round(min(1.0, total / max(1, evaluated)), 4) + return {"score": score, "evaluated": evaluated, + "flags": flags, "thin": thin} diff --git a/plugins/caelestia-assistant/assistant/capabilities/settings/parser.py b/plugins/caelestia-assistant/assistant/capabilities/settings/parser.py new file mode 100755 index 0000000..a36f695 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/capabilities/settings/parser.py @@ -0,0 +1,674 @@ +"""Intent parser for the settings layer (the settings design notes (see module docstrings) §3): text -> ops. + +Guarantees: + +- PURE function: ``parse(text)`` performs no file I/O, reads no environment + variable, no clock, no randomness — identical input always yields an + identical result (the same guarantee as Layer 1's engine, ``engine.py``). +- Deterministic grammar, no scoring, no ML: fixed precedence — normalize, + preset check FIRST, scheme/wallpaper dead-ends, explanatory dead-ends, + then per-tool noun+cue matching (§3.3). stdlib ``re`` only, every regex + compiled exactly once at module level. +- The parser never resolves values that need the current file state: + relative ops carry only the factor (multiply) or the signed step count + (step, ±1); the planner resolves them against the real current values. +- Honest verdicts (§3.2): INTENT / AMBIGUOUS / NO_INTENT / SUGGESTED. + AMBIGUOUS never silently picks a tool; NO_INTENT says so and lists what + IS supported; SUGGESTED emits inert ``SUGGESTED_NOT_EXECUTED:`` strings + for the scheme/wallpaper system, which lives outside shell.json. +- Nothing in this module can write, execute, or touch the network — by + construction, since it opens nothing at all. +""" + +from __future__ import annotations + +import re +from typing import Any, Dict, List, Optional, Tuple + +from assistant.adapters.caelestia.registry import ToolSpec, TOOL_SPECS, describe, tool_by_name, tool_by_path +from . import slots as _slots + +# --------------------------------------------------------------------------- +# Grammar (§3.4), compiled once. All matching happens on normalized text +# (lowercase, single spaces), so the patterns are written lowercase. +# --------------------------------------------------------------------------- + +NUM_RE = re.compile(r"-?\d+(?:\.\d+)?") +PCT_RE = re.compile(r"(\d+(?:\.\d+)?)\s*%") + +RESET_RE = re.compile(r"\b(?:reset|default)\b") + +# Numeric direction vocabularies, per class (§3.4). Transparency phrases are +# multi-word and must be matched BEFORE the bare size words they contain +# ("more transparent" contains "more"; "less transparent" contains "less"). +SIZE_DOWN_RE = re.compile(r"\b(?:thinner|smaller|slimmer|shrink|reduce|decrease|less|lower|down|tighter|denser)\b") +SIZE_UP_RE = re.compile(r"\b(?:thicker|bigger|larger|wider|grow|increase|more|raise|up|roomier|spacious)\b") +ANIM_DOWN_RE = re.compile(r"\b(?:faster|quicker|snappier)\b") +ANIM_UP_RE = re.compile(r"\b(?:slower|smoother)\b") +TRANS_DOWN_RE = re.compile(r"\b(?:more transparent|see-through|lighter)\b") +TRANS_UP_RE = re.compile(r"\b(?:more opaque|more solid|less transparent)\b") + +BOOL_ON_RE = re.compile(r"\b(?:turn on|switch on|enable|show|on)\b") +BOOL_OFF_RE = re.compile(r"\b(?:turn off|switch off|disable|hide|off)\b") + +# Position words, with "edge"/"side" tolerated adjacent (§3.4). +POSITION_RE = re.compile(r"\b(top|bottom|left|right)\b(?:\s+(?:edge|side))?") + +# Preset triggers (§3.7) — checked FIRST, before per-tool synonyms. +COMPACT_RE = re.compile(r"\b(?:more compact|compact|denser|tighter)\b") +MINIMAL_RE = re.compile(r"\b(?:minimalist|minimal look|minimal|cleaner look|simpler look)\b") + +# Scheme/wallpaper nouns (§3.3 step 3) — requests that live OUTSIDE +# shell.json, answered with inert suggestions only ([C25]). +SCHEME_NOUN_RE = re.compile(r"\b(?:accent color|color scheme|theme colors?|accents?|schemes?|palettes?)\b") +WALLPAPER_NOUN_RE = re.compile(r"\b(?:wallpapers?|background images?|desktop backgrounds?)\b") + +# Explanatory dead-end patterns (§3.6). +DOCK_NOUN_RE = re.compile(r"\bdocks?\b") +NOTIFS_NOUN_RE = re.compile(r"\bnotifications?\b") +TRANSPARENCY_NOUN_RE = re.compile(r"\btransparency\b") +FONT_FAMILY_RE = re.compile(r"\b(?:font famil(?:y|ies)|font names?|typefaces?)\b") + +# §3.4, setBorderThickness noun-list parenthetical: "remove the +# border" / "borderless" -> absolute 0 (the shipped UI's own "Set to 0 for a +# borderless look", AppearancePage.qml:108-115). +BORDERLESS_RE = re.compile(r"\bborderless\b") +REMOVE_RE = re.compile(r"\bremove\b") + +# §3.4: the phrase "pitch black" is itself the on-cue for the +# bezel-mode tool when the sentence carries no other value phrase — the +# exact mirror of the "borderless" -> 0 rule ("make the shell pitch black" +# has no on/off word to scan). With an explicit on/off word ("disable pitch +# black") or a comparative ("less pitch black") the standard §3.4/§3.5 +# paths handle it instead and this cue stays out of the phrase list. +PITCH_BLACK_RE = re.compile(r"\bpitch black\b") + +# Per-tool noun regexes (§3.4), precompiled from the registry. +_NOUN_RES: Dict[str, List[re.Pattern[str]]] = { + spec.name: [re.compile(r"\b(?:" + group + r")\b") for group in spec.nouns] + for spec in TOOL_SPECS +} + +# Direction-word applicability classes (§3.3 step 5, §3.4). Numeric tools +# split into size / animation / transparency classes; each class answers +# only its own direction vocabulary (plus plain numbers and percents). +# The registry also holds noun-silent direct-address tools (nouns only +# on the 18-tool core) — they are NOT part of the +# natural-language surface, so only noun-bearing tools are size-class +# members (the targetless candidate list stays the 18-tool core set). +_ANIM_TOOLS = frozenset({"setAnimationSpeed"}) +_TRANS_TOOLS = frozenset({"setTransparencyBase"}) +_SIZE_TOOLS = frozenset( + spec.name for spec in TOOL_SPECS + if spec.nouns and spec.kind in ("float", "int") + and spec.name not in _ANIM_TOOLS | _TRANS_TOOLS +) +_NUMERIC_TOOLS = _SIZE_TOOLS | _ANIM_TOOLS | _TRANS_TOOLS + +# Honest note texts (verbatim from the settings design notes (see module docstrings) where quoted). +_BOOL_NO_STRENGTH_LABELS = { + "setBlurEnabled": "blur", + "setLivePreviews": "live previews", + "setBarPersistent": "bar persistence", + "setPitchBlack": "pitch black (bezel mode)", + # setDockBadges: the honest note for comparatives on the app-badges + # toggle — same §3.5 shape as the other bool tools above. + "setDockBadges": "app badges", +} +_ANIM_INVERSION_NOTE = "durations scale: lower = faster" +_PRESET_NOTE = ( + "preset values are conservative defaults, not an upstream-defined look" +) + +SCHEME_SUGGESTIONS = [ + "SUGGESTED_NOT_EXECUTED: caelestia scheme list", + "SUGGESTED_NOT_EXECUTED: caelestia scheme set -n ", +] +WALLPAPER_SUGGESTIONS = [ + "SUGGESTED_NOT_EXECUTED: caelestia wallpaper -f ", + "SUGGESTED_NOT_EXECUTED: caelestia wallpaper -r (random)", +] +SCHEME_NOTE = ( + "accent colors live in the scheme system (state under $XDG_STATE_HOME/caelestia), " + "not shell.json; the assistant cannot validate scheme names, so the color word is not parsed" +) +WALLPAPER_NOTE = ( + "wallpapers live in the scheme system (caelestia wallpaper, state under " + "$XDG_STATE_HOME/caelestia), not shell.json; the assistant cannot validate file paths" +) + +SPLIT_QUESTION = ( + "multiple value phrases found in one request; split that into separate " + "requests (one change per request)" +) +PERCENT_QUESTION = ( + "percent of what? say e.g. '20% bigger', or give a plain number like 1.2" +) + + +# --------------------------------------------------------------------------- +# Normalization and scanning helpers (all pure). +# --------------------------------------------------------------------------- + + +def _normalize(text: str) -> str: + """§3.3 step 1: lowercase, collapse whitespace, strip surrounding quotes + and trailing ``.,!?``. Keeps ``%``, ``.`` and ``-`` so decimals and + negatives survive.""" + cleaned = text.strip() + if len(cleaned) >= 2 and cleaned[0] == cleaned[-1] and cleaned[0] in "'\"": + cleaned = cleaned[1:-1].strip() + cleaned = cleaned.rstrip(".,!?").strip() + cleaned = re.sub(r"\s+", " ", cleaned) + return cleaned.lower() + + +def _mask(text: str, spans: List[Tuple[int, int]]) -> str: + """Blank out the given spans so later scans cannot re-match them.""" + chars = list(text) + for start, end in spans: + for idx in range(start, min(end, len(chars))): + chars[idx] = " " + return "".join(chars) + + +def _scan_pcts(text: str) -> List[Dict[str, Any]]: + out: List[Dict[str, Any]] = [] + for match in PCT_RE.finditer(text): + out.append({"kind": "percent", "value": float(match.group(1)), "raw": match.group(0), "pos": match.start()}) + return out + + +def _scan_numbers(text: str) -> List[Dict[str, Any]]: + out: List[Dict[str, Any]] = [] + for match in NUM_RE.finditer(text): + out.append({"kind": "number", "value": float(match.group(0)), "raw": match.group(0), "pos": match.start()}) + return out + + +def _scan_directions(text: str) -> List[Dict[str, Any]]: + """Numeric direction words (size/animation/transparency classes). + + Transparency phrases are matched first and masked out, so their bare + size words ("more", "less") are never double-counted. + """ + matches: List[Dict[str, Any]] = [] + masked = text + for regex, klass, sign in ( + (TRANS_DOWN_RE, "trans", -1), + (TRANS_UP_RE, "trans", +1), + (SIZE_DOWN_RE, "size", -1), + (SIZE_UP_RE, "size", +1), + (ANIM_DOWN_RE, "anim", -1), + (ANIM_UP_RE, "anim", +1), + ): + found = list(regex.finditer(masked)) + for match in found: + matches.append({"kind": "direction", "class": klass, "sign": sign, "raw": match.group(0), "pos": match.start()}) + masked = _mask(masked, [m.span() for m in found]) + matches.sort(key=lambda item: item["pos"]) + return matches + + +def _scan_bools(text: str) -> List[Dict[str, Any]]: + out: List[Dict[str, Any]] = [] + for regex, value in ((BOOL_ON_RE, True), (BOOL_OFF_RE, False)): + for match in regex.finditer(text): + out.append({"kind": "bool", "value": value, "raw": match.group(0), "pos": match.start()}) + out.sort(key=lambda item: item["pos"]) + return out + + +def _scan_positions(text: str) -> List[Dict[str, Any]]: + out: List[Dict[str, Any]] = [] + for match in POSITION_RE.finditer(text): + out.append({"kind": "position", "value": match.group(1), "raw": match.group(0), "pos": match.start()}) + return out + + +def _noun_matched(text: str) -> List[ToolSpec]: + """Specs whose noun groups ALL appear in the text (§3.3 step 5). + + A noun-silent tool (nouns == (), the direct-address tools) + matches NOTHING — ``all([])`` is vacuously True, so the empty noun + list must be guarded explicitly, not treated as a universal match. + """ + matched: List[ToolSpec] = [] + for spec in TOOL_SPECS: + if spec.nouns and all(regex.search(text) for regex in _NOUN_RES[spec.name]): + matched.append(spec) + return matched + + +def _op(tool: str, action: str, value: Any, raw: str, note: Optional[str] = None) -> Dict[str, Any]: + op: Dict[str, Any] = {"tool": tool, "action": action, "value": value, "raw": raw} + if note: + op["note"] = note + return op + + +def _bool_note(tool: str, raw: str, value: bool) -> str: + """§3.5: comparatives on bool tools map to on/off WITH the honest note.""" + label = _BOOL_NO_STRENGTH_LABELS.get(tool, "this setting") + return ( + f"{label} in shell.json is on/off only — there is no strength to {raw}; " + f"{'enabling' if value else 'disabling'} it" + ) + + +def _result(verdict: str, ops: Optional[List[Dict[str, Any]]] = None, + candidates: Optional[List[Dict[str, Any]]] = None, + question: Optional[str] = None, notes: Optional[List[str]] = None, + suggestions: Optional[List[str]] = None) -> Dict[str, Any]: + return { + "verdict": verdict, + "ops": ops or [], + "candidates": candidates or [], + "question": question, + "notes": notes or [], + "suggestions": suggestions or [], + } + + +# --------------------------------------------------------------------------- +# Verdict builders for the fixed special cases (§3.6, §3.3 steps 2-3). +# --------------------------------------------------------------------------- + + +def _preset_ops(trigger: str, values: Dict[str, float]) -> List[Dict[str, Any]]: + ops: List[Dict[str, Any]] = [] + for path, value in values.items(): + spec = tool_by_path(path) + if spec is None: # cannot happen: presets name registry paths only + continue + ops.append(_op(spec.name, "set", value, trigger)) + return ops + + +def _scheme_wallpaper(text: str) -> Optional[Dict[str, Any]]: + scheme = bool(SCHEME_NOUN_RE.search(text)) + wallpaper = bool(WALLPAPER_NOUN_RE.search(text)) + if not scheme and not wallpaper: + return None + suggestions: List[str] = [] + notes: List[str] = [] + if scheme: + suggestions.extend(SCHEME_SUGGESTIONS) + notes.append(SCHEME_NOTE) + if wallpaper: + suggestions.extend(WALLPAPER_SUGGESTIONS) + notes.append(WALLPAPER_NOTE) + notes.append("nothing was executed and nothing was written; these are inert suggestions only") + return _result("SUGGESTED", notes=notes, suggestions=suggestions) + + +def _dead_ends(text: str) -> Optional[Dict[str, Any]]: + """§3.6 explanatory dead-ends, evaluated before per-tool matching.""" + if DOCK_NOUN_RE.search(text) and POSITION_RE.search(text): + return _result( + "AMBIGUOUS", + candidates=[{"tool": "setBarPosition", "description": "bar.position — move the WHOLE bar (top/bottom/left/right)"}], + notes=[ + "dock left/right placement is not a shell.json key: the dock is a " + "bar element whose placement is the 'zone' of its entry in bar.entries " + "(set in Nexus -> Panels -> Taskbar -> Elements)", + ], + question=( + "the dock's left/right placement is set in Nexus -> Panels -> Taskbar -> " + "Elements; did you mean to move the whole bar? if so, say e.g. " + "'move the bar to the left'" + ), + ) + + if NOTIFS_NOUN_RE.search(text) and (BOOL_ON_RE.search(text) or BOOL_OFF_RE.search(text)): + return _result( + "NO_INTENT", + notes=[ + "no upstream 'notifications enabled' boolean exists (notifsconfig.hpp has " + "maxPopups/maxNotifs/expire etc., none an on/off switch); notifications " + "toggling is deliberately unmapped", + ], + question=( + "there is no notifications on/off setting to change; for the counts that " + "ARE tools say e.g. 'set the max notification popups to 5' or 'keep at " + "most 200 stored notifications' — other notification behavior lives in " + "Nexus" + ), + ) + + if TRANSPARENCY_NOUN_RE.search(text) and (BOOL_ON_RE.search(text) or BOOL_OFF_RE.search(text)): + return _result( + "NO_INTENT", + notes=[ + "appearance.transparency.enabled exists upstream but is deliberately not a tool " + "permitted tools; turning transparency off also disables blur in the " + "upstream UI (AppearancePage.qml:132-136)", + ], + question=( + "did you mean the transparency LEVEL? say e.g. 'make panels more " + "transparent' or 'set the transparency to 0.7'" + ), + ) + + if FONT_FAMILY_RE.search(text): + return _result( + "NO_INTENT", + notes=[ + "only the font SIZE scale (appearance.font.scale) is a core tool; font " + "family/name lives in the appearance.font.*.family string trees, out of scope", + ], + question="did you mean the font size? say e.g. 'make the font bigger' or 'set the font scale to 1.2'", + ) + + return None + + +def _no_intent() -> Dict[str, Any]: + """§3.2 NO_INTENT: honest answer + the full supported-settings list + + pointers to Nexus and the troubleshooting layers.""" + notes = ["no supported setting matched this request; the supported settings are:"] + notes.extend(f" {describe(spec)}" for spec in TOOL_SPECS) + notes.append( + "you can also change these in Nexus (the shell's settings UI); for troubleshooting " + "questions use the other assistant layers, e.g. python3 -m assistant.core.ask_pipeline \"\"" + ) + return _result( + "NO_INTENT", + notes=notes, + question="rephrase with a tool noun plus a value or a direction (run --list-tools to see them all)", + ) + + +# --------------------------------------------------------------------------- +# The single-phrase resolution (§3.3 steps 5-7, §3.4). +# --------------------------------------------------------------------------- + + +def _distinct_key(phrase: Dict[str, Any]) -> Tuple[Any, ...]: + """Value phrases are 'distinct' by their resolved value (§3.3 step 6): + 'smaller' and 'thinner' are one phrase (both = one step down); 'bigger' + and 'smaller' are two; '1.2' and '0.5' are two.""" + if phrase["kind"] == "direction": + return ("direction", phrase["class"], phrase["sign"]) + if phrase["kind"] == "percent": + return ("percent", phrase["value"]) + return (phrase["kind"], phrase["value"]) + + +def _resolve_single(phrase: Dict[str, Any], noun_specs: List[ToolSpec]) -> List[Dict[str, Any]]: + """Apply the one value phrase to every noun-matched tool it fits.""" + ops: List[Dict[str, Any]] = [] + kind = phrase["kind"] + + if kind == "number": + for spec in noun_specs: + if spec.kind in ("float", "int"): + ops.append(_op(spec.name, "set", phrase["value"], phrase["raw"])) + elif spec.kind == "bool": + # §3.4: any number on a bool tool -> the planner REJECTS it. + ops.append(_op(spec.name, "set", phrase["value"], phrase["raw"])) + # enum tool: a plain number is not an applicable cue. + + elif kind == "percent": + comparative = phrase.get("comparative") + if comparative is None: + # §3.4: bare percent is absolute ONLY on the transparency base + # (its own UI displays percent); bool tools get a REJECTED op; + # any other numeric tool makes the whole request AMBIGUOUS. + numeric_matched = [s for s in noun_specs if s.kind in ("float", "int")] + non_trans = [s for s in numeric_matched if s.name not in _TRANS_TOOLS] + if non_trans: + return [] # caller turns this into the PERCENT AMBIGUOUS verdict + for spec in noun_specs: + ops.append(_op(spec.name, "set", phrase["value"] / 100.0, phrase["raw"])) + else: + sign = comparative["sign"] + factor = 1.0 + sign * phrase["value"] / 100.0 + for spec in noun_specs: + if spec.kind in ("float", "int"): + ops.append(_op(spec.name, "multiply", factor, f"{phrase['raw']} {comparative['raw']}")) + elif spec.kind == "bool": + ops.append(_op(spec.name, "set", phrase["value"] / 100.0, phrase["raw"])) + + elif kind == "direction": + klass, sign, raw = phrase["class"], phrase["sign"], phrase["raw"] + for spec in noun_specs: + if spec.name in _ANIM_TOOLS and klass == "anim": + ops.append(_op(spec.name, "step", sign, raw, note=_ANIM_INVERSION_NOTE)) + elif spec.name in _TRANS_TOOLS and klass == "trans": + ops.append(_op(spec.name, "step", sign, raw)) + elif spec.kind in ("float", "int") and klass == "size": + if spec.name in _ANIM_TOOLS or spec.name in _TRANS_TOOLS: + continue # size vocabulary does not fit anim/transparency tools + ops.append(_op(spec.name, "step", sign, raw)) + elif spec.kind == "bool" and klass == "size": + # §3.5: comparative words on bool tools map to on/off + note. + value = sign > 0 + ops.append(_op(spec.name, "set", value, raw, note=_bool_note(spec.name, raw, value))) + + elif kind == "bool": + for spec in noun_specs: + if spec.kind == "bool": + ops.append(_op(spec.name, "set", phrase["value"], phrase["raw"])) + + elif kind == "position": + for spec in noun_specs: + if spec.kind == "enum": + ops.append(_op(spec.name, "set", phrase["value"], phrase["raw"])) + + elif kind == "reset": + # §3.4: "reset"/"default" + tool noun -> set to the registry default. + for spec in noun_specs: + ops.append(_op(spec.name, "set", spec.default, phrase["raw"])) + + return ops + + +def _candidates_from_specs(specs: List[ToolSpec]) -> List[Dict[str, Any]]: + return [{"tool": spec.name, "description": describe(spec)} for spec in specs] + + +# --------------------------------------------------------------------------- +# parse() — the public pure function (§3). +# --------------------------------------------------------------------------- + + +def parse(text: str) -> Dict[str, Any]: + """Parse one natural-language settings request into a verdict + ops. + + See the module docstring for the guarantees; the settings design notes (see module docstrings) §3 is the + normative grammar. Value resolution (current values, clamping) happens + only in the planner, never here. + """ + normalized = _normalize(text) + if not normalized: + return _no_intent() + + # §3.3 step 2 — preset check FIRST ("compact" is never consumed by + # per-tool synonyms; "tighter"/"denser" belong to the presets). + compact = COMPACT_RE.search(normalized) + minimal = MINIMAL_RE.search(normalized) + if compact: + ops = _preset_ops(compact.group(0), { + "bar.scale": 0.85, + "appearance.spacing.scale": 0.9, + "appearance.padding.scale": 0.9, + }) + return _result("INTENT", ops=ops, notes=[f"preset 'compact': {_PRESET_NOTE}"]) + if minimal: + ops = _preset_ops(minimal.group(0), { + "bar.scale": 0.8, + "appearance.spacing.scale": 0.9, + "appearance.padding.scale": 0.9, + "appearance.rounding.scale": 0.9, + }) + return _result("INTENT", ops=ops, notes=[f"preset 'minimal': {_PRESET_NOTE}"]) + + # §3.3 step 3 — scheme/wallpaper: SUGGESTED, inert strings only. + suggested = _scheme_wallpaper(normalized) + if suggested is not None: + return suggested + + # §3.3 step 4 — explanatory dead-ends. + dead_end = _dead_ends(normalized) + if dead_end is not None: + return dead_end + + # §3.3 step 5 — which tools does the sentence name? + noun_specs = _noun_matched(normalized) + + # §3.4 — scan the value phrases. Percents are masked before the plain + # number scan so "20%" never also counts as the number 20. + pcts = _scan_pcts(normalized) + without_pcts = _mask(normalized, [(p["pos"], p["pos"] + len(p["raw"])) for p in pcts]) + numbers = _scan_numbers(without_pcts) + directions = _scan_directions(normalized) + bools = _scan_bools(normalized) + positions = _scan_positions(normalized) + reset = RESET_RE.search(normalized) is not None + + # "borderless" (or "remove" + the border noun) is the absolute-0 cue; + # the word itself implies the border tool even without the bare noun + # (word boundaries keep \bborder\b from matching inside "borderless"). + borderless = BORDERLESS_RE.search(normalized) + removed = REMOVE_RE.search(normalized) and any( + spec.name == "setBorderThickness" for spec in noun_specs + ) + if borderless: + border_spec = tool_by_name("setBorderThickness") + if border_spec is not None and border_spec not in noun_specs: + noun_specs = noun_specs + [border_spec] + + # §3.4: "make the shell pitch black" — the phrase implies the + # bezel-mode tool AND its on value, but ONLY when the sentence carries no + # other value phrase (an explicit on/off word, a comparative/size word, a + # number, a percent or a reset request all take the standard paths + # instead, so e.g. "disable pitch black", "reset the pitch black mode" + # and "less pitch black" keep their §3.4/§3.5 readings and never collide + # with this implicit cue). + pitch_black_cue = bool( + PITCH_BLACK_RE.search(normalized) + and not (BOOL_ON_RE.search(normalized) or BOOL_OFF_RE.search(normalized)) + and not directions + and not pcts + and not numbers + and not reset + ) + if pitch_black_cue: + pitch_black_spec = tool_by_name("setPitchBlack") + if pitch_black_spec is not None and pitch_black_spec not in noun_specs: + noun_specs = noun_specs + [pitch_black_spec] + + phrases: List[Dict[str, Any]] = [] + if borderless or removed: + raw = borderless.group(0) if borderless else "remove" + phrases.append({"kind": "number", "value": 0.0, "raw": raw, "pos": -1}) + if pitch_black_cue: + phrases.append({"kind": "bool", "value": True, "raw": "pitch black", "pos": -1}) + for pct in pcts: + pct = dict(pct) + # A percent consumes the first numeric direction word as its + # comparative (§3.4); with no comparative it is absolute on the + # transparency base only. + pct["comparative"] = directions[0] if directions else None + phrases.append(pct) + phrases.extend(numbers) + if not pcts and not numbers: + # A plain number/percent governs any direction word in the same + # sentence (§3.4: "direction word WITHOUT a number -> step"), so + # directions only count as standalone phrases in their absence. + phrases.extend(directions) + phrases.extend(bools) + phrases.extend(positions) + if reset: + phrases.append({"kind": "reset", "value": True, "raw": "reset", "pos": -1}) + + seen: List[Tuple[Any, ...]] = [] + distinct: List[Dict[str, Any]] = [] + for phrase in phrases: + key = _distinct_key(phrase) + if key not in seen: + seen.append(key) + distinct.append(phrase) + + if len(distinct) >= 2: + # §3.3 step 6 — several value phrases: never guess the split. + return _result("AMBIGUOUS", question=SPLIT_QUESTION) + + if distinct: + phrase = distinct[0] + ops = _resolve_single(phrase, noun_specs) + if phrase["kind"] == "percent" and phrase.get("comparative") is None and not ops and noun_specs: + # Bare percent on a non-transparency numeric tool (§3.4). + return _result("AMBIGUOUS", question=PERCENT_QUESTION) + if ops: + return _result("INTENT", ops=ops) + if noun_specs: + # §3.8 — compositional slot-grammar recovery (A1): the frozen + # grammar could not assemble a value phrase for these nouns; + # the slot grammar gets one deterministic chance to compose + # {intensifier, target, direction, dimension} before the honest + # AMBIGUOUS verdict stands. Never runs when the frozen grammar + # succeeded, so every frozen output is byte-identical. + recovered = _slots.recover(normalized, noun_specs) + if recovered is not None: + return recovered + # §3.3 step 7 — noun matched, no applicable cue. + names = ", ".join(spec.name for spec in noun_specs) + return _result( + "AMBIGUOUS", + candidates=_candidates_from_specs(noun_specs), + question=( + f"what should I do with {names}? give a value, a direction, or on/off " + "wording (e.g. 'make it bigger', 'set it to 1.2', 'turn it off')" + ), + ) + # No noun matched: only a size direction word carries meaning for + # step 8 (§3.3 step 8) — numbers, percents, bools and position + # words without a noun are NO_INTENT, handled by the fallthrough. + if phrase["kind"] == "direction": + return _targetless(phrase) + + if directions and not noun_specs: + # §3.3 step 8 — direction word, no noun: fixed candidate list of the + # numeric tools whose direction vocabulary matched, registry order. + return _targetless(directions[0]) + + if noun_specs: + # §3.8 recovery, second hook: a noun matched but NO value phrase of + # any frozen kind was found (e.g. "thin out the bar") — same one + # deterministic slot-grammar chance before the AMBIGUOUS verdict. + recovered = _slots.recover(normalized, noun_specs) + if recovered is not None: + return recovered + names = ", ".join(spec.name for spec in noun_specs) + return _result( + "AMBIGUOUS", + candidates=_candidates_from_specs(noun_specs), + question=( + f"what should I do with {names}? give a value, a direction, or on/off " + "wording (e.g. 'make it bigger', 'set it to 1.2', 'turn it off')" + ), + ) + + return _no_intent() + + +def _targetless(direction: Dict[str, Any]) -> Dict[str, Any]: + """§3.3 step 8: 'make it smaller' — list every numeric tool whose + direction vocabulary matched, in registry order.""" + klass = direction["class"] + if klass == "anim": + specs = [s for s in TOOL_SPECS if s.name in _ANIM_TOOLS] + elif klass == "trans": + specs = [s for s in TOOL_SPECS if s.name in _TRANS_TOOLS] + else: + specs = [s for s in TOOL_SPECS if s.name in _SIZE_TOOLS] + return _result( + "AMBIGUOUS", + candidates=_candidates_from_specs(specs), + question=( + "which setting did you mean? name it, e.g. 'make the bar smaller' or " + "'set the rounding to 1.5'" + ), + ) diff --git a/plugins/caelestia-assistant/assistant/capabilities/settings/plain.py b/plugins/caelestia-assistant/assistant/capabilities/settings/plain.py new file mode 100644 index 0000000..5fe755f --- /dev/null +++ b/plugins/caelestia-assistant/assistant/capabilities/settings/plain.py @@ -0,0 +1,139 @@ +"""assistant.capabilities.settings.plain — accessible output mode (F24, +exponential-build-5; the interaction-polish companion to F22). + +Two surfaces, one contract: + +1. PLAIN OUTPUT (``--plain`` or ``CAELESTIA_ASSISTANT_PLAIN=1``): + a screen-reader-friendly rendering contract, enforced by test — + no ANSI escapes, no box-drawing or table decorations, no emoji, + deterministic ordering, one fact per line. The settings layer's + output is already plain text by construction; this module makes + that a TESTED GUARANTEE and gives the two widest tables + (``--list-tools``, ``--history``) an explicitly linear form: + ``to_linear_rows`` renders header/row pairs as + ``key=value`` lines instead of aligned columns, so screen readers + get one fact per line in a stable order (aligned columns read as + word soup row by row). + +2. THE REDUCED-MOTION RECIPE (``--a11y-recipe``): F22 answers "are + these colors readable?"; the missing half for motion-sensitive + users is a documented, inert recipe that composes ALREADY-VALIDATED + registry knobs into a reduced-motion profile (F9's composition does + the write-path work on request). The recipe prints the exact + SUGGESTED_NOT_EXECUTED command; nothing is saved or applied without + the user running it through the normal preview/consent gates. Every + knob cites its upstream config declaration (the registry carries + the citations; they travel here verbatim). + +Pure module: no I/O, no environment reads outside the documented +helper, no RNG. +""" + +from __future__ import annotations + +import os +import re +from typing import Any, Dict, Iterable, List, Optional, Sequence + +__all__ = ["plain_requested", "FORBIDDEN_PLAIN_RE", "to_linear_rows", + "REDUCED_MOTION_RECIPE", "recipe_command", "render_recipe"] + +_FORBIDDEN_PATTERNS = ( + r"\x1b\[[0-9;]*m", # ANSI SGR + r"\x1b\][^\x07]*\x07", # OSC + r"[─│┌┐└┘├┤┬┴┼═║╔╗╚╝╠╣╦╩╬]", # box drawing + r"[\U0001F300-\U0001FAFF\u2705\u2714\u2716\u26A0\u26D4]", # emoji/symbols +) +FORBIDDEN_PLAIN_RE = re.compile("|".join(_FORBIDDEN_PATTERNS)) + + +def plain_requested(explicit: Optional[bool] = None) -> bool: + """True when plain output is requested: an explicit CLI flag wins, + else the CAELESTIA_ASSISTANT_PLAIN environment variable (any of + 1/true/yes/on, case-insensitive).""" + if explicit is not None: + return explicit + return os.environ.get("CAELESTIA_ASSISTANT_PLAIN", "").strip().lower() \ + in ("1", "true", "yes", "on") + + +def to_linear_rows(headers: Sequence[str], + rows: Iterable[Sequence[Any]]) -> List[str]: + """A table as one-fact-per-line records. Ordering is the input's + (callers pass deterministically-ordered rows); each record is + separated by a blank line so screen readers hear a complete record + before the next begins.""" + out: List[str] = [] + for index, row in enumerate(rows, start=1): + out.append(f"record {index}:") + for header, value in zip(headers, row): + out.append(f" {header}: {value}") + return out + + +def assert_plain_safe(text: str) -> None: + """Raise AssertionError when text violates the plain contract + (used by the tests that pin the guarantee; cheap enough to call + from any renderer's plain branch).""" + hit = FORBIDDEN_PLAIN_RE.search(text) + assert hit is None, f"plain-output violation: {hit!r} in {text[:80]!r}" + + +# --------------------------------------------------------------------------- +# The reduced-motion recipe (F24): registry-validated knobs only. +# --------------------------------------------------------------------------- + +REDUCED_MOTION_RECIPE: List[Dict[str, Any]] = [ + { + "tool": "setAnimationSpeed", + "value": 0.25, + "why": "the global animation duration scale — 0.25 makes every " + "shell animation four times faster, the largest effect a " + "single key has on perceived motion", + }, + { + "tool": "setBlurEnabled", + "value": False, + "why": "blur is a continuously animating region; disabling it " + "removes constant background compositing motion", + }, + { + "tool": "setLivePreviews", + "value": False, + "why": "dock hover previews animate on every hover", + }, +] + +# Derived, not duplicated: the actual registry validation (range/type) +# happens when the command runs through --profile-save, exactly like a +# user-typed composition. Recipe commands are INERT strings. + + +def recipe_command(profile_name: str = "reduced-motion") -> str: + """The inert one-line composition command for the recipe (F9).""" + sources = " ".join(f"{r['tool']}={str(r['value']).lower()}" + if isinstance(r["value"], bool) + else f"{r['tool']}={r['value']}" + for r in REDUCED_MOTION_RECIPE) + return ("SUGGESTED_NOT_EXECUTED: caelestia-assist settings " + f"--profile-save {profile_name} {sources}") + + +def render_recipe() -> List[str]: + lines = [ + "reduced-motion recipe (F24) — every knob is a registry-validated", + "tool; nothing is saved or applied by printing this:", + "", + ] + for item in REDUCED_MOTION_RECIPE: + lines.append(f" {item['tool']} = {item['value']!r}") + lines.append(f" why: {item['why']}") + lines.append("") + lines.append("one-command composition (rides the F9 profile gates; the") + lines.append("preview shows every change before --apply --confirm):") + lines.append(f" {recipe_command()}") + lines.append("") + lines.append("review the composed result first:") + lines.append("SUGGESTED_NOT_EXECUTED: caelestia-assist settings " + "--profile reduced-motion") + return lines diff --git a/plugins/caelestia-assistant/assistant/capabilities/settings/planner.py b/plugins/caelestia-assistant/assistant/capabilities/settings/planner.py new file mode 100755 index 0000000..a27c081 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/capabilities/settings/planner.py @@ -0,0 +1,336 @@ +"""Planner for the settings layer (the settings design notes (see module docstrings) §4): ops -> a validated plan. + +Guarantees: + +- Read-only until the applier runs: the planner READS the target file once + and never writes anything, anywhere. +- Abort untouched on a broken target: an existing file that is not valid + JSON, or not a JSON object, raises PlannerError and the CLI exits 1 with + the file untouched (#120: "it simply isn't applied" — and the running + shell's own loader would retry-and-toast on it, [C10]). +- No coercion: an existing value whose type disagrees with the registry + kind (or a non-object intermediate key) aborts that ENTRY with a + TYPE_MISMATCH error — never a silent cast or structural repair. +- #120's range rule: an absolute out-of-range value becomes a REJECTED + entry carrying the allowed range; it is listed, not silently dropped. + Relative ops (multiply/step) are CLAMPED to the registry range with a + visible ``clamped`` notice (§7d of the settings design notes (see module docstrings)). +- All-or-nothing: any entry error marks the whole plan ``apply_blocked``; + the applier then refuses to write anything (§4.5). +- Per-monitor overrides are only READ, best-effort, to warn that a global + change will be shadowed; no monitor file is ever written (§4.6). +""" + +from __future__ import annotations + +import glob +import json +from pathlib import Path +from typing import Any, Dict, List, Optional, Tuple, Union + +from assistant.adapters.caelestia.registry import ToolSpec, tool_by_name + + +class PlannerError(RuntimeError): + """Raised when the target file cannot be planned against safely.""" + + +def _read_current(file_path: Path) -> Tuple[Dict[str, Any], List[str]]: + """§4.1: read and parse the target file; missing file -> defaults.""" + if not file_path.exists(): + return {}, ["target file does not exist; defaults assumed (file will be created on apply)"] + try: + raw = file_path.read_bytes() + text = raw.decode("utf-8") + except (OSError, UnicodeDecodeError) as exc: + raise PlannerError(f"cannot read target file {file_path}: {exc}") from exc + try: + loaded = json.loads(text) + except ValueError as exc: + raise PlannerError( + f"target file {file_path} is not valid JSON ({exc}); refusing to touch it" + ) from exc + if not isinstance(loaded, dict): + raise PlannerError( + f"target file {file_path} is valid JSON but not an object; refusing to touch it" + ) + # §4.1: deep-copy the parsed object; the plan holds plain values only. + current = json.loads(json.dumps(loaded)) + return current, [] + + +def _walk(current: Dict[str, Any], spec: ToolSpec) -> Tuple[Optional[Any], Optional[str]]: + """§4.2: resolve the leaf's current value. + + Returns (value, absent_note). Raises _TypeMismatch when an intermediate + segment exists but is not an object. + """ + segments = spec.path.split(".") + node: Any = current + absent_note: Optional[str] = None + for segment in segments[:-1]: + if segment not in node: + return spec.default, "key was absent; default assumed" + node = node[segment] + if not isinstance(node, dict): + raise _TypeMismatch( + f"'{segment}' exists but is not an object; cannot resolve {spec.path}" + ) + leaf = segments[-1] + if leaf not in node: + return spec.default, "key was absent; default assumed" + return node[leaf], absent_note + + +class _TypeMismatch(Exception): + """Internal: the existing structure disagrees with the registry.""" + + +def _existing_type_ok(spec: ToolSpec, value: Any) -> bool: + """§4.3 type check — bool is checked with ``type() is`` because Python's + ``json`` parses ``true`` to ``bool`` and ``1 == True``.""" + if spec.kind in ("float", "int"): + return type(value) in (int, float) # excludes bool (bool subclasses int) + if spec.kind == "bool": + return type(value) is bool + if spec.kind == "enum": + return isinstance(value, str) + return False + + +def _clamp(spec: ToolSpec, value: float) -> Tuple[float, bool]: + clamped = False + if spec.minimum is not None and value < spec.minimum: + value = spec.minimum + clamped = True + if spec.maximum is not None and value > spec.maximum: + value = spec.maximum + clamped = True + return value, clamped + + +def _finalize_number(spec: ToolSpec, value: float) -> float: + """§4.4 deterministic rounding: float tools -> round(new, 2); int tools + -> int(new + 0.5) (all int-tool ranges are non-negative).""" + if spec.kind == "float": + return round(float(value), 2) + return int(value + 0.5) + + +def _resolve_op(op: Dict[str, Any], current: Dict[str, Any]) -> Dict[str, Any]: + """Resolve one parser op against the current file state -> one entry.""" + spec = tool_by_name(str(op.get("tool", ""))) + if spec is None: + return _error_entry(None, op, f"unknown tool {op.get('tool')!r}") + + action = op.get("action") + raw = op.get("raw") + + try: + old, absent = _walk(current, spec) + except _TypeMismatch as exc: + return _error_entry(spec, op, f"TYPE_MISMATCH: {exc}") + + if not _existing_type_ok(spec, old): + return _error_entry( + spec, op, + "TYPE_MISMATCH: existing value " + f"{json.dumps(old) if old is not None else 'null'} at {spec.path} does not match " + f"the registry kind '{spec.kind}'; refusing to coerce", + ) + + value = op.get("value") + + def _compose(detail: Optional[str], extra: Optional[str] = None, + clamped_bound: Optional[float] = None) -> Optional[str]: + """Join the note parts: action detail, absent-key notice, clamped + notice, the tool's standing inversion note (§2), and the op's own + honest note from the parser (§3.5).""" + parts: List[str] = [] + if detail: + parts.append(detail) + if absent: + parts.append(absent) + if clamped_bound is not None: + parts.append(f"clamped to {clamped_bound}") + if spec is not None and spec.name == "setAnimationSpeed": + parts.append("durations scale: lower = faster") + if extra: + parts.append(extra) + return "; ".join(parts) if parts else None + + if action == "set": + if spec.kind == "bool": + if type(value) is not bool: + # §3.4/§3.5: a number or percent on a bool tool is REJECTED, + # never coerced. + return _error_entry( + spec, op, + "this setting is on/off only; it has no magnitude", + old=old, + ) + new: Any = value + elif spec.kind == "enum": + if value not in (spec.enum or ()): + return _error_entry( + spec, op, + f"value {value!r} is not one of {'|'.join(spec.enum or ())}", + old=old, + ) + new = value + else: + if type(value) not in (int, float) or isinstance(value, bool): + return _error_entry(spec, op, f"value {value!r} is not a number", old=old) + if (spec.minimum is not None and value < spec.minimum) or \ + (spec.maximum is not None and value > spec.maximum): + return _error_entry( + spec, op, + f"absolute value {value} is outside the allowed range " + f"{spec.minimum}-{spec.maximum}; it is not applied", + old=old, + ) + new = _finalize_number(spec, float(value)) + return _entry( + spec, action, raw, old, new, False, new == old, + _compose(None, extra=op.get("note")), + ) + + if action in ("multiply", "step"): + if spec.kind == "bool": + return _error_entry( + spec, op, "this setting is on/off only; it has no magnitude", old=old + ) + if spec.kind == "enum": + return _error_entry( + spec, op, "position has no magnitude; use a position word", old=old + ) + if type(old) not in (int, float) or isinstance(old, bool): + return _error_entry( + spec, op, f"existing value at {spec.path} is not a number", old=old + ) + base = float(old) + if action == "multiply": + factor = value if isinstance(value, (int, float)) and not isinstance(value, bool) else 1.0 + computed = base * factor + detail = f"multiply by {factor} ({raw})" + else: + sign = 1 if (isinstance(value, (int, float)) and not isinstance(value, bool) and value > 0) else -1 + computed = base + spec.step * sign + detail = f"step {raw} ({spec.step * sign:+g})" + clamped_value, clamped = _clamp(spec, computed) + new = _finalize_number(spec, clamped_value) + bound: Optional[float] = None + if clamped: + bound = spec.minimum if (spec.minimum is not None and computed < spec.minimum) else spec.maximum + return _entry( + spec, action, raw, old, new, clamped, new == old, + _compose(detail, extra=op.get("note"), clamped_bound=bound), + ) + + return _error_entry(spec, op, f"unknown action {action!r}", old=old) + + +def _entry(spec: ToolSpec, action: str, raw: Optional[str], old: Any, new: Any, + clamped: bool, no_op: bool, note: Optional[str]) -> Dict[str, Any]: + entry = { + "tool": spec.name, + "path": spec.path, + "action": action, + "raw": raw, + "old": old, + "new": new, + "clamped": clamped, + "no_op": no_op, + "note": note, + } + return entry + + +def _error_entry(spec: Optional[ToolSpec], op: Dict[str, Any], error: str, + old: Any = None) -> Dict[str, Any]: + entry = { + "tool": spec.name if spec else str(op.get("tool", "")), + "path": spec.path if spec else "", + "action": op.get("action"), + "raw": op.get("raw"), + "old": old, + "new": None, # an errored entry is never applied + "clamped": False, + "no_op": False, + "note": None, + "error": error, + } + return entry + + +def _monitor_warnings(entries: List[Dict[str, Any]], target: Path) -> List[str]: + """§4.6: read-only, best-effort shadow warning for per-monitor overrides. + + No monitor file is ever written; unparseable/unreadable ones are skipped + silently (they are not ours to judge). global_only tools skip the check — + the loader quarantines global-only keys in overlay files anyway ([C23]). + """ + notes: List[str] = [] + monitors_dir = target.parent / "monitors" + if not monitors_dir.is_dir(): + return notes + seen: set = set() + for monitor_file in sorted(glob.glob(str(monitors_dir / "*" / "shell.json"))): + try: + data = json.loads(Path(monitor_file).read_text(encoding="utf-8")) + except (OSError, ValueError): + continue + if not isinstance(data, dict): + continue + screen = Path(monitor_file).parent.name + for entry in entries: + spec = tool_by_name(entry.get("tool", "")) + if spec is None or spec.global_only: + continue + key = (screen, spec.path) + if key in seen: + continue + node: Any = data + present = True + for segment in spec.path.split("."): + if not isinstance(node, dict) or segment not in node: + present = False + break + node = node[segment] + if present: + seen.add(key) + notes.append( + f"screen '{screen}' has a per-monitor override for this key " + f"({spec.path}); the global change will be shadowed there" + ) + return notes + + +def plan(ops: List[Dict[str, Any]], file_path: Union[str, Path]) -> Dict[str, Any]: + """Resolve parser ops against the target file's current values (§4). + + Returns the plan dict: verdict/file/entries/notes/errors/apply_blocked. + Raises PlannerError when the target file exists but is invalid JSON or + not an object (the CLI exits 1, the file is never touched). + """ + target = Path(file_path) + current, notes = _read_current(target) + + entries: List[Dict[str, Any]] = [] + errors: List[Dict[str, Any]] = [] + for op in ops: + entry = _resolve_op(op, current) + entries.append(entry) + if entry.get("error"): + errors.append({"tool": entry["tool"], "path": entry["path"], "error": entry["error"]}) + + notes.extend(_monitor_warnings(entries, target)) + + return { + "verdict": "INTENT", + "file": str(target), + "entries": entries, + "notes": notes, + "errors": errors, + "apply_blocked": bool(errors), + } diff --git a/plugins/caelestia-assistant/assistant/capabilities/settings/presets.py b/plugins/caelestia-assistant/assistant/capabilities/settings/presets.py new file mode 100755 index 0000000..6372b42 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/capabilities/settings/presets.py @@ -0,0 +1,111 @@ +"""Named presets for the settings layer (issue #120). + +Issue #120's Nexus-integration list names the directions verbatim — +"Optimize for gaming", "Optimize for battery life", "Make this look more +like macOS", "Make this look more minimal" — and this module adds +"compact". A preset here is STRICTLY a bundle of already-validated tool +calls: the data lives in tools.json (generated from curations.PRESETS, +where build_registry._preset_value_ok FAILS THE BUILD if any call violates +its tool's validation), and applying a preset is nothing but planning +those calls through the ordinary planner/applier path. No preset ever +introduces an unvalidated code path. + +Presets are multi-change by construction, so they always go through the +preview-then-confirm flow (cli.py gates the write behind --confirm / an +interactive y-N; the QML service shows the confirm card). +""" + +from __future__ import annotations + +from pathlib import Path +from typing import Any, Dict, List, Optional, Union + +from assistant.adapters.caelestia.registry import PRESETS + +FileTarget = Union[str, Path] + + +class PresetError(RuntimeError): + """Raised when a preset name is unknown or a bundle is malformed.""" + + +def presets() -> List[Dict[str, Any]]: + """Every preset: {name, label, description, calls: [(tool, value)]}.""" + return [dict(p) for p in PRESETS] + + +def preset_by_name(name: str) -> Optional[Dict[str, Any]]: + for preset in PRESETS: + if str(preset["name"]) == name: + return dict(preset) + return None + + +def preset_ops(name: str) -> List[Dict[str, Any]]: + """A preset's bundle as planner ops (set actions, raw = provenance).""" + preset = preset_by_name(name) + if preset is None: + raise PresetError( + f"unknown preset {name!r}; known: " + + ", ".join(str(p["name"]) for p in PRESETS) + ) + ops: List[Dict[str, Any]] = [] + for tool, value in preset["calls"]: # type: ignore[misc] + ops.append({ + "tool": str(tool), + "action": "set", + "value": value, + "raw": f"preset {name}: {tool}={value!r}", + }) + return ops + + +def describe_lines() -> List[str]: + """The --list-presets table.""" + lines = ["caelestia assistant — settings presets " + f"({len(PRESETS)} named bundles of validated tool calls):", ""] + for preset in PRESETS: + calls = ", ".join(f"{tool}={value!r}" + for tool, value in preset["calls"]) # type: ignore[misc] + lines.append(f" {preset['name']:<14} {preset['label']}") + lines.append(f" {'':<14} {preset['description']}") + lines.append(f" {'':<14} calls: {calls}") + lines.append("") + lines.append("Presets are multi-change: applying one always shows the " + "preview and waits for confirmation.") + return lines + + +# --------------------------------------------------------------------------- +# Preset state graph + bounded model-check audit (exponential-build-4 B) +# --------------------------------------------------------------------------- + + +def transition_graph() -> Dict[str, List[str]]: + """The operational state graph of the preset system. + + States are the named presets plus "custom" (any state the applier + did not produce from a preset). Transitions are "apply preset X": + application is currently UNCONDITIONAL — from any state you can + move to any preset state — so the graph is complete by + construction, and the audit below proves the obvious. Its value is + as a GUARD: the moment preset application grows preconditions + (state prerequisites, ordering constraints), this graph is where + the change lands and the audit is what catches a preset that + became unreachable or a dead end — before a user ever sees it. + """ + names = [str(p["name"]) for p in PRESETS] + ["custom"] + return {state: [n for n in names if n != state] for state in names} + + +def audit(node_budget: int = 50_000) -> Dict[str, Any]: + """Bounded model-check of transition_graph(): deadlock states + (exact) and per-preset reachability within one step per hop count + k = number of states (complete graph => SAT proves each in one + hop). ABSTAINs loudly past the budget; additive, nothing gates on + it — this is evidence for a human, not a permission.""" + from assistant.capabilities.genius import sat as sat_mod + + graph = transition_graph() + return sat_mod.graph_audit(graph, "custom", k=len(graph), + node_budget=node_budget) diff --git a/plugins/caelestia-assistant/assistant/capabilities/settings/profile_preview.py b/plugins/caelestia-assistant/assistant/capabilities/settings/profile_preview.py new file mode 100644 index 0000000..63d0616 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/capabilities/settings/profile_preview.py @@ -0,0 +1,180 @@ +"""assistant.capabilities.settings.profile_preview — composite what-if for profiles +(F11, exponential-build-5). + +The single-request what-if (``--what-if``) projects ONE op list through +the interaction graph. A PROFILE is a composition of SOURCES — a preset, +a macro, a call — and the question a user asks before consenting is not +just "what will change?" but "what did each PART of this bundle bring +in, and where do they collide?". This module answers that by composing +engines that already exist and are already tested (no new analysis of +its own): + +- ``profiles.compose_ops`` per source: each source's own op contribution; +- ``profiles.profile_ops``: the composed op list and the conflicts the + source order resolved (F7: nothing dropped silently); +- ``consequences.project`` per source AND for the composite: cited + derived effects and AC-3 conflicts, per part and overall; +- ``planner.plan``: the real validation (ranges, types, no-ops); +- ``sanity.project`` + ``sanity.check``: the WCAG/projected-state + invariants the applier itself will enforce, run here read-only so the + preview shows the refusals BEFORE the consent, not after; +- the registry's group metadata: the blast radius by feature area. + +Read-only end to end: it reads the target file, plans, projects, and +renders — nothing is applied and nothing is written anywhere. +""" + +from __future__ import annotations + +import json +from pathlib import Path +from typing import Any, Dict, List + +from . import consequences, planner, profiles, sanity +from assistant.adapters.caelestia.registry import tool_by_name + +__all__ = ["build", "render"] + + +def _read_current(target: Path) -> Dict[str, Any]: + """The live file's parsed values (read-only; {} on any absence or + parse error — the projection then reports honestly that cross-key + live-state edges were evaluated against an empty state).""" + try: + return json.loads(Path(target).read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError): + return {} + + +def _group_of(tool: str) -> str: + spec = tool_by_name(tool) + return getattr(spec, "group", "?") if spec else "?" + + +def build(target, name: str) -> Dict[str, Any]: + """Assemble the composite preview for one saved profile. Raises + ProfileError for an unknown profile; PlannerError passes through + (the CLI renders it — an out-of-range saved call is exactly the + kind of finding the preview exists to surface).""" + target = Path(target) + ops, conflicts = profiles.profile_ops(target, name) + + sources = next((p.get("sources", []) for p in profiles.list_profiles(target) + if p.get("name") == name), []) + current = _read_current(target) + + per_source: List[Dict[str, Any]] = [] + for src in sources: + kind = src.get("kind") + label = (f"{kind}:{src.get('name')}" if kind != "call" + else f"call {src.get('tool')}={src.get('value')!r}") + try: + src_ops, src_conflicts = profiles.compose_ops(target, [src]) + except profiles.ProfileError as exc: + per_source.append({"label": label, "error": str(exc), + "n_ops": 0, "derived": 0, "conflicts": 0}) + continue + projection = consequences.project(src_ops, current) + per_source.append({ + "label": label, + "n_ops": len(src_ops), + "derived": projection.get("derived") or [], + "conflicts": src_conflicts, + }) + + composite = consequences.project(ops, current) + plan = planner.plan(ops, target) + + projected = sanity.project(current, plan.get("entries", [])) + sanity_report = sanity.check(projected) + + blast: Dict[str, List[str]] = {} + for op in ops: + blast.setdefault(_group_of(str(op["tool"])), []).append(str(op["tool"])) + + return { + "name": name, + "n_ops": len(ops), + "ops": ops, + "conflicts": conflicts, + "per_source": per_source, + "composite": composite, + "plan_blocked": bool(plan.get("apply_blocked")), + "plan_refusals": [e for e in plan.get("entries", []) if e.get("error")], + "sanity": {"refusals": sanity_report.get("refusals", []), + "warnings": sanity_report.get("warnings", [])}, + "blast_radius": {g: sorted(t) for g, t in sorted(blast.items())}, + } + + +def render(view: Dict[str, Any]) -> List[str]: + """Text rendering of the composite preview (the pre-consent artifact).""" + name = view["name"] + lines = [f"profile {name!r} — composite what-if (read-only, nothing " + f"is applied):", + f" composed ops: {view['n_ops']} across " + f"{len(view['blast_radius'])} feature area(s)"] + for group, tools in view["blast_radius"].items(): + lines.append(f" {group}: {', '.join(tools)}") + + if view["conflicts"]: + lines.append(f" composition conflicts resolved by source order " + f"({len(view['conflicts'])}):") + for c in view["conflicts"]: + lines.append(f" - {c['tool']}: {c['dropped']['value']!r} " + f"({c['dropped']['from']}) overridden by " + f"{c['kept']['value']!r} ({c['kept']['from']})") + else: + lines.append(" composition conflicts: none") + + lines.append(" per source:") + for src in view["per_source"]: + if src.get("error"): + lines.append(f" {src['label']}: UNRESOLVED NOW — {src['error']}") + continue + derived = src.get("derived") or [] + conflicts = src.get("conflicts") or [] + lines.append(f" {src['label']}: {src['n_ops']} op(s), " + f"{len(derived)} derived effect(s), " + f"{len(conflicts)} internal conflict(s)") + for row in derived: + lines.append(f" derived: {row.get('from_op')} -> " + f"{row.get('effect_path')} " + f"(cited: {row.get('citation')})") + + composite = view["composite"] + comp_derived = composite.get("derived") or [] + if comp_derived: + lines.append(f" composite derived effects ({len(comp_derived)}):") + for row in comp_derived: + lines.append(f" - {row.get('from_op')} -> " + f"{row.get('effect_path')}: {row.get('effect')}") + lines.append(f" cited: {row.get('citation')} " + f"[{row.get('confidence')}]") + else: + lines.append(" composite derived effects: none in the known " + "interaction table") + + plan_refusals = view.get("plan_refusals") or [] + if view.get("plan_blocked") or plan_refusals: + lines.append(f" PLANNER BLOCKS THIS PROFILE " + f"({len(plan_refusals)} rejected op(s)) — the apply " + f"would refuse:") + for e in plan_refusals: + lines.append(f" - {e.get('tool')}: {e.get('error')}") + sanity_ref = view["sanity"]["refusals"] + sanity_warn = view["sanity"]["warnings"] + if sanity_ref: + lines.append(f" projected-state refusals ({len(sanity_ref)}) — the " + f"applier would refuse the write:") + for row in sanity_ref: + lines.append(f" - {row.get('id')}: {row.get('message')}") + if sanity_warn: + lines.append(f" projected-state warnings ({len(sanity_warn)}):") + for row in sanity_warn: + lines.append(f" - {row.get('id')}: {row.get('message')}") + lines.append(" reversibility: every applied profile goes through the " + "journaled applier (backup + bounded undo history)") + lines.append(" SUGGESTED_NOT_EXECUTED: caelestia-assist settings " + "--profile " + name + " --apply --confirm") + return lines diff --git a/plugins/caelestia-assistant/assistant/capabilities/settings/profiles.py b/plugins/caelestia-assistant/assistant/capabilities/settings/profiles.py new file mode 100644 index 0000000..97c5bb6 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/capabilities/settings/profiles.py @@ -0,0 +1,304 @@ +"""assistant.capabilities.settings.profiles — profile algebra (F9, exponential-build-5). + +Issue #120's Phase 3 asks for "optimization profiles" beyond the five +shipped presets; the A9 conformance table records that gap honestly as +b6b PARTIAL ("preset bundles + the learned pairwise ladder; no profile +algebra/composition"). This module is that algebra — built entirely +from engines that already exist, with no new write surface: + +- a PROFILE is a named, ordered list of SOURCES. A source is a preset + (presets.py — registry-validated bundles), a macro (macros.py — an + APPROVED captured apply), or an explicit single call (registry tool + = JSON value); +- COMPOSITION is deterministic and conflict-reporting: sources apply + in order, LATER WINS per tool, and every overridden earlier value is + reported, never silently dropped (the F7 no-silent-drop invariant); +- the composed ops come out in the plain planner-op shape (the same + shape presets.preset_ops and macros.macro_ops produce), so applying a + profile rides the ordinary plan -> preview -> consent -> applier path + with NO bespoke writer. Multi-change profiles need the standard + --confirm second consent, exactly like presets and macros; +- SAVE re-resolves every source against the LIVE registry and the + saved stores at save time: a preset that no longer exists, a deleted + macro, or a call naming an unknown tool refuses the whole save + (a partially stale composite is worse than none). Value-range + validation stays with the planner at apply time — a saved profile + whose call is now out of range produces an honest plan rejection, + never a silent write. + +STORAGE (no new write surface): profiles live INSIDE the existing +undo-history file at ``.assistant-history.json`` under a +bounded ``"profiles"`` key — the same file, the same ``history._save`` +atomic write path, the same sibling path as the ``macros`` (C3) and +``undo_log`` (A3) precedents. Save and delete are explicit user +commands; the target shell.json is never touched by this module. + +Each stored profile is {"name", "label" (free text), "created_at" +(ISO-8601), "sources": [...]} where sources are +{"kind": "preset"|"macro", "name": ...} or +{"kind": "call", "tool": ..., "value": ...}. + +Pure module apart from the documented history-file reads/writes: no +execution, no network, no RNG; same inputs -> same stored bytes +(created_at is the one field that differs per call, by precedent). +""" + +from __future__ import annotations + +import json +import re +from datetime import datetime, timezone +from pathlib import Path +from typing import Any, Dict, List, Tuple, Union + +from . import history +from . import presets as presets_mod +from assistant.adapters.caelestia.registry import TOOL_SPECS + +__all__ = ["ProfileError", "MAX_PROFILES", "PROFILES_KEY", "NAME_RE", + "parse_source", "list_profiles", "save", "delete", + "compose_ops", "profile_ops", "diff", "render_profile_lines"] + +MAX_PROFILES = 16 +PROFILES_KEY = "profiles" + +NAME_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9 _.\-]{0,31}") + +TOOL_NAMES = frozenset(t.name for t in TOOL_SPECS) + +FileTarget = Union[str, Path] + + +class ProfileError(ValueError): + """Raised for every refusal (unknown profile/source, bad name, + duplicate); the caller renders the reason — nothing is guessed.""" + + +def parse_source(spec: str) -> Dict[str, Any]: + """Parse one CLI source token: ``preset:NAME`` | ``macro:NAME`` | + ``TOOL=VALUE`` (VALUE is JSON, or a plain string on JSON failure — + the --call convention). Pure. Raises ProfileError on a malformed + token; unknown names are checked at save/apply time against the + live registry, not here.""" + spec = str(spec or "").strip() + if spec.startswith("preset:"): + name = spec[len("preset:"):].strip() + if not re.fullmatch(r"[a-z0-9][a-z0-9\-]*", name): + raise ProfileError( + f"preset source needs a preset slug (lowercase letters, " + f"digits, dashes): got {name!r}") + return {"kind": "preset", "name": name} + if spec.startswith("macro:"): + name = spec[len("macro:"):].strip() + if not name: + raise ProfileError("macro source needs a name: macro:NAME") + return {"kind": "macro", "name": name} + if "=" in spec: + tool, _, raw = spec.partition("=") + tool = tool.strip() + if not tool: + raise ProfileError(f"call source needs a tool name: {spec!r}") + try: + value = json.loads(raw) + except (json.JSONDecodeError, ValueError): + value = raw.strip() + return {"kind": "call", "tool": tool, "value": value} + raise ProfileError( + f"cannot parse source {spec!r}; expected preset:NAME, macro:NAME, " + f"or TOOL=VALUE") + + +def _load_profiles(target) -> List[Dict[str, Any]]: + return [dict(p) for p in history._load(target).get(PROFILES_KEY, [])] + + +def list_profiles(target) -> List[Dict[str, Any]]: + """The saved profiles, oldest first (a copy). Read-only.""" + return _load_profiles(target) + + +def save(target, name: str, sources: List[Dict[str, Any]], + label: str = "") -> Dict[str, Any]: + """Save a named profile. Every source is resolved NOW (preset in + the registry's preset table; macro in the saved macro store; call + naming a live registry tool) — an unresolvable source refuses the + whole save. Writes only the history file's "profiles" key; never + the target file. Duplicate names refuse (delete first).""" + if not NAME_RE.fullmatch(str(name or "")): + raise ProfileError( + f"profile names must match {NAME_RE.pattern!r} (start with a " + f"letter or digit; letters, digits, spaces, '_', '.', '-' " + f"afterwards; at most 32 characters) — got {name!r}") + if not sources: + raise ProfileError("a profile needs at least one source") + # Resolve every source now (honest refusal beats a stale composite). + composed, _conflicts = compose_ops(target, sources) + if not composed: + raise ProfileError("a profile must resolve to at least one tool call") + data = history._load(target) + profiles = data.get(PROFILES_KEY, []) + if any(p.get("name") == name for p in profiles): + raise ProfileError( + f"profile {name!r} already exists; delete it first " + f"(--profile-delete {name})") + entry = { + "name": name, + "label": str(label or "")[:200], + "created_at": datetime.now(timezone.utc).isoformat(timespec="seconds"), + "sources": [dict(s) for s in sources], + } + profiles.append(entry) # FIFO eviction below keeps the store bounded + data[PROFILES_KEY] = profiles[-MAX_PROFILES:] + history._save(target, data) + return dict(entry) + + +def delete(target, name: str) -> Dict[str, Any]: + """Remove one profile by name (an explicit user command; writes + only the history file's "profiles" key). Raises ProfileError for + an unknown name — never a silent no-op delete.""" + data = history._load(target) + profiles = data.get(PROFILES_KEY, []) + kept = [p for p in profiles if p.get("name") != name] + if len(kept) == len(profiles): + saved = [str(p.get("name")) for p in profiles] + raise ProfileError( + f"unknown profile {name!r}; saved profiles: " + + (", ".join(saved) if saved else "(none)")) + data[PROFILES_KEY] = kept + history._save(target, data) + gone = next(p for p in profiles if p.get("name") == name) + return {"deleted": name, "sources": len(gone.get("sources", []))} + + +def compose_ops(target, sources: List[Dict[str, Any]] + ) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]]]: + """Resolve and compose sources in order into planner-shaped ops. + + Later wins per tool; every overridden earlier value is reported as + a conflict entry {tool, kept, dropped} (F7: nothing silently + dropped). Read-only. Raises ProfileError for an unresolvable + source (unknown preset/macro/tool).""" + ops_by_tool: Dict[str, Dict[str, Any]] = {} + order: List[str] = [] + conflicts: List[Dict[str, Any]] = [] + for src in sources: + kind = src.get("kind") + if kind == "preset": + name = str(src.get("name", "")) + try: + preset_ops = presets_mod.preset_ops(name) + except presets_mod.PresetError as exc: + raise ProfileError(f"preset source: {exc}") from None + for op in preset_ops: + _absorb(op, f"preset:{name}", ops_by_tool, order, conflicts) + elif kind == "macro": + name = str(src.get("name", "")) + from . import macros as macros_mod + try: + macro_ops = macros_mod.macro_ops(target, name) + except macros_mod.MacroError as exc: + raise ProfileError(f"macro source: {exc}") from None + for op in macro_ops: + _absorb(op, f"macro:{name}", ops_by_tool, order, conflicts) + elif kind == "call": + tool = str(src.get("tool", "")) + if tool not in TOOL_NAMES: + raise ProfileError( + f"call source: {tool!r} is not a registry tool " + f"(the planner validates values at apply time)") + op = {"tool": tool, "action": "set", + "value": src.get("value"), + "raw": f"call: {tool}={src.get('value')!r}"} + _absorb(op, f"call:{tool}", ops_by_tool, order, conflicts) + else: + raise ProfileError(f"unknown source kind {kind!r}") + return [ops_by_tool[t] for t in order], conflicts + + +def _absorb(op: Dict[str, Any], provenance: str, + ops_by_tool: Dict[str, Dict[str, Any]], order: List[str], + conflicts: List[Dict[str, Any]]) -> None: + tool = str(op.get("tool")) + prev = ops_by_tool.get(tool) + if prev is not None and prev.get("value") != op.get("value"): + conflicts.append({ + "tool": tool, + "dropped": {"value": prev.get("value"), "from": prev.get("_from")}, + "kept": {"value": op.get("value"), "from": provenance}, + }) + elif prev is not None: + return # same value re-asserted: not a conflict, not a new op + ops_by_tool[tool] = dict(op) + ops_by_tool[tool]["_from"] = provenance + if tool not in order: + order.append(tool) + + +def profile_ops(target, name: str) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]]]: + """A saved profile's composed ops + conflicts (planner shape). + Raises ProfileError for an unknown profile.""" + for profile in _load_profiles(target): + if profile.get("name") == name: + return compose_ops(target, profile.get("sources", [])) + saved = [str(p.get("name")) for p in _load_profiles(target)] + raise ProfileError( + f"unknown profile {name!r}; saved profiles: " + + (", ".join(saved) if saved else "(none yet; save one with " + "--profile-save)") + f" — {name!r} is not one of them") + + +def diff(target, name_a: str, name_b: str) -> Dict[str, Any]: + """Effective-value diff of two saved profiles: per tool — only A, + only B, or changed (value A -> value B). Deterministic; read-only.""" + ops_a, _ = profile_ops(target, name_a) + ops_b, _ = profile_ops(target, name_b) + va = {op["tool"]: op.get("value") for op in ops_a} + vb = {op["tool"]: op.get("value") for op in ops_b} + rows = [] + for tool in list(va) + [t for t in vb if t not in va]: + a, b = va.get(tool), vb.get(tool) + if tool not in vb: + rows.append({"tool": tool, "kind": "only_a", "a": a}) + elif tool not in va: + rows.append({"tool": tool, "kind": "only_b", "b": b}) + elif a != b: + rows.append({"tool": tool, "kind": "changed", "a": a, "b": b}) + return {"a": name_a, "b": name_b, "rows": rows} + + +def render_profile_lines(target, name: str) -> List[str]: + """The --profile-show table: sources with provenance, the composed + ops, and every composition conflict. Read-only.""" + for profile in _load_profiles(target): + if profile.get("name") == name: + ops, conflicts = compose_ops(target, profile.get("sources", [])) + lines = [f"profile {name!r} — {len(profile.get('sources', []))} " + f"source(s):"] + for src in profile.get("sources", []): + if src.get("kind") == "call": + lines.append(f" source: call {src.get('tool')}=" + f"{src.get('value')!r}") + else: + lines.append(f" source: {src.get('kind')} " + f"{src.get('name')}") + lines.append(f"composed ops ({len(ops)} tool(s), later source " + f"wins per tool):") + for op in ops: + lines.append(f" {op['tool']} = {op.get('value')!r} " + f"[{op.get('_from')}]") + if conflicts: + lines.append(f"conflicts resolved by order " + f"({len(conflicts)}, later wins — none " + f"silently dropped):") + for c in conflicts: + lines.append( + f" {c['tool']}: {c['dropped']['value']!r} " + f"(from {c['dropped']['from']}) overridden by " + f"{c['kept']['value']!r} (from {c['kept']['from']})") + return lines + saved = [str(p.get("name")) for p in _load_profiles(target)] + raise ProfileError( + f"unknown profile {name!r}; saved profiles: " + + (", ".join(saved) if saved else "(none yet; save one with " + "--profile-save)")) diff --git a/plugins/caelestia-assistant/assistant/capabilities/settings/recommend.py b/plugins/caelestia-assistant/assistant/capabilities/settings/recommend.py new file mode 100644 index 0000000..8679c81 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/capabilities/settings/recommend.py @@ -0,0 +1,212 @@ +"""assistant.capabilities.settings.recommend — the value recommender (F29). + +For a NUMERIC tool, propose a value from three evidence tiers with +hierarchical partial pooling: + + 1. the registry default (the upstream-shipped center), + 2. the preset pool (what each optimization profile sets this tool to), + 3. the user's own APPROVED history (values that were actually applied + through the consented applier — never rejected or dry-run values). + +Model (documented, deliberately simple, stdlib-only): conjugate Gaussian. +The population prior is N(mu0, tau^2) over the pooled evidence +(default + preset values); the user's n approved values are the second +level; the posterior is the precision-weighted blend — the classic +partial-pooling shrinkage: with no history you get the prior, with a +long history you get yourself, in between you get shrunk toward the +pool. The credible interval is the posterior's own 95% band, CLAMPED to +the tool's legal range with the clamp reported (a recommendation +outside the registry's range would be a bug, not a opinion). + +Honesty rules: this is a PROPOSAL (inert text, never applied — the +standard dry-run/consent spine owns every write); rejected plans are +learned negatives elsewhere and are NOT part of this estimate (stated); +with zero user history the output says so instead of pretending the +prior is a preference; and the Pareto position against the optimization +profiles is a plain comparison of numbers, not a claim about your +machine's performance. +""" + +from __future__ import annotations + +import json +import math +from pathlib import Path +from typing import Any, Dict, List, Optional, Tuple + +from assistant.adapters.caelestia.registry import ToolSpec, tool_by_name, tool_by_path + +__all__ = ["recommend", "render_recommendation"] + +_Z_95 = 1.959963985 # two-sided 95% Gaussian quantile (documented approx: + # with tiny n a Student-t would be wider; the note + # says so instead of faking rigor) + + +def _preset_pool(spec: ToolSpec) -> List[Tuple[str, float]]: + """(preset_name, value) for every profile that sets this tool.""" + from pathlib import Path as _P + tools_json = _P(__file__).resolve().parents[2] / "adapters" / "caelestia" / "tools.json" + with open(tools_json, "r", encoding="utf-8") as fh: + data = json.load(fh) + out: List[Tuple[str, float]] = [] + for preset in data.get("presets", ()): + for call in preset.get("calls", ()): + if call.get("tool") == spec.name: + v = call.get("value") + if isinstance(v, (int, float)) and not isinstance(v, bool): + out.append((preset["name"], float(v))) + return out + + +def _approved_values(path: str, + ledger_path: Optional[str]) -> List[float]: + """Values the user APPROVED for this path (read-only ledger scan).""" + if not ledger_path: + return [] + p = Path(ledger_path) + if not p.exists(): + return [] + try: + with open(p, "r", encoding="utf-8") as fh: + data = json.load(fh) + except (OSError, ValueError): + return [] + out: List[float] = [] + for entry in data.get("entries", ()): + for op in entry.get("ops", ()): + if op.get("path") == path: + v = op.get("new") + if isinstance(v, (int, float)) and not isinstance(v, bool): + out.append(float(v)) + return out + + +def recommend(tool: str, + ledger_path: Optional[str] = None) -> Dict[str, Any]: + """One numeric tool's recommended value, pooled and honest.""" + spec = tool_by_name(str(tool)) or tool_by_path(str(tool)) + if spec is None: + return {"verdict": "UNKNOWN_TOOL", "tool": str(tool)} + if spec.kind not in ("int", "float"): + return {"verdict": "UNSUPPORTED_KIND", "tool": spec.name, + "kind": spec.kind, + "note": "the recommender is for numeric tools; booleans " + "and enums have no meaningful pooling"} + + pool = _preset_pool(spec) + default = spec.default + prior_points = [float(default)] + [v for _n, v in pool] + mu0 = sum(prior_points) / len(prior_points) + # prior spread: the pooled dispersion, floored so a single-point + # pool (only the default) does not collapse to a delta + var_prior = (sum((v - mu0) ** 2 for v in prior_points) + / len(prior_points)) if len(prior_points) > 1 else 0.0 + var_prior = max(var_prior, 0.25 * ((spec.maximum or 1) - + (spec.minimum or 0)) ** 2 + / 16.0) # quarter of a quarter-range: a weak, honest + # prior strength, documented not derived + k0 = float(len(prior_points)) # pseudo-observation count + + history = _approved_values(spec.path, ledger_path) + n = len(history) + if n: + xbar = sum(history) / n + # the precision floor: preferences cannot be resolved finer + # than the tool's own step (a zero-spread history is "n approvals + # of the same value", not "infinite certainty about it") + span = ((spec.maximum or 1) - (spec.minimum or 0)) + if spec.step: + var_floor = float(spec.step) ** 2 + else: + var_floor = max(span / 8.0, 1e-6) ** 2 + var_data = (sum((v - xbar) ** 2 for v in history) / n) if n > 1 \ + else 0.0 + var_data = max(var_data, var_floor) + prec0, precd = k0 / var_prior, n / var_data + post_var = 1.0 / (prec0 + precd) + post_mean = (prec0 * mu0 + precd * xbar) / (prec0 + precd) + else: + post_mean, post_var = mu0, var_prior / max(k0, 1.0) + + lo, hi = spec.minimum, spec.maximum + clamped = False + value = post_mean + if lo is not None and value < lo: + value, clamped = float(lo), True + if hi is not None and value > hi: + value, clamped = float(hi), True + if spec.kind == "int": + rounded = int(round(value)) + if abs(rounded - value) > 1e-9: + clamped = True + value = rounded + + half = _Z_95 * math.sqrt(post_var) + ci_lo = max(float(lo), value - half) if lo is not None else value - half + ci_hi = min(float(hi), value + half) if hi is not None else value + half + + pareto = [] + for name, v in pool: + if value == v: + pos = "matches" + elif value > v: + pos = "above" + else: + pos = "below" + pareto.append({"profile": name, "value": v, "position": pos}) + + return { + "verdict": "OK", + "tool": spec.name, + "path": spec.path, + "kind": spec.kind, + "range": [lo, hi], + "value": value, + "credible_interval_95": [round(ci_lo, 4), round(ci_hi, 4)], + "clamped": clamped, + "evidence": { + "registry_default": default, + "preset_pool": [{"profile": n_, "value": v} + for n_, v in pool], + "approved_history": history, + "n_history": n, + }, + "pareto_position": pareto, + "note": ("partial pooling: no approved history, so this is the " + "pooled prior — a starting point, not your preference" + if not n else + f"partial pooling: {n} approved value(s) shrunk toward " + "the preset/registry pool by their relative precision") + + ("; interval clamped to the legal range" if clamped else "") + + ("; rejections (learned negatives) are NOT part of this " + "estimate; proposal only — nothing is applied"), + "proposal_only": True, + } + + +def render_recommendation(result: Dict[str, Any]) -> List[str]: + if result.get("verdict") == "UNKNOWN_TOOL": + return [f"recommend: unknown tool {result['tool']!r}"] + if result.get("verdict") == "UNSUPPORTED_KIND": + return [f"recommend: {result['tool']} is {result['kind']} — " + "the recommender is for numeric tools"] + ev = result["evidence"] + lines = [ + f"recommend: {result['tool']} ({result['path']}) -> " + f"{result['value']} [95% interval " + f"{result['credible_interval_95']}]", + f" evidence: registry default {ev['registry_default']}; " + f"preset pool " + + (", ".join(f"{p['profile']}={p['value']}" + for p in ev["preset_pool"]) or "(no profile sets it)") + + f"; approved history {ev['n_history']} value(s)", + ] + if result["pareto_position"]: + lines.append(" vs profiles: " + ", ".join( + f"{p['profile']} ({p['position']} {p['value']})" + for p in result["pareto_position"])) + lines.append(f" {result['note']}") + lines.append(" proposal only — apply through the standard " + "dry-run -> confirm -> journaled apply spine") + return lines diff --git a/plugins/caelestia-assistant/assistant/capabilities/settings/sanity.py b/plugins/caelestia-assistant/assistant/capabilities/settings/sanity.py new file mode 100644 index 0000000..948532c --- /dev/null +++ b/plugins/caelestia-assistant/assistant/capabilities/settings/sanity.py @@ -0,0 +1,184 @@ +"""Pre-write sanity simulator for the settings applier (issue #120 Phase 1.2). + +Deterministic, named-algorithm checks over the POST-apply state, run by +applier.apply() before anything touches the disk — including single-setting +applies, which are exactly the ones that skip the multi-change preview. + +Checks: + +1. Minimum tap-target size (WCAG 2.5.8 "Target Size (Minimum)", 24x24 px): + the projected bar.dock.iconSize below 24 px is reported. The shipped + control allows 16 px, so this is a WARNING with the citation, not a + refusal — refusing would break presets the shipped controls themselves + define (the registry's own `minimal` preset sets 20 px). The assistant + flags the accessibility cost; the shipped range stays the authority. + +2. Projected WCAG contrast (WCAG 2.x relative-luminance contrast ratio, via + assistant/genius/creative.py::contrast_ratio — the same code the + caelestia_genius_palette bridge tool uses): when the caller supplies a + scheme (a {"role": "#hex"} mapping, e.g. exported from the shell's scheme + system), every role pair is contrast-checked on the projected state and a + ratio below 4.5:1 (WCAG 1.4.3 AA, normal text) between a text role and a + background role is a REFUSAL: the apply exits nonzero with nothing + written. When no scheme is supplied the check is honestly skipped — + shell.json itself carries no color leaves (colors live in the scheme + system, outside this write path), and pretending otherwise would be a + fabricated check. + +Refusal semantics: applier.apply raises ApplierError("sanity ... nothing was +written") before the backup file is touched, so a refused apply leaves the +target, its backup, and the undo history byte-identical. Dry-runs (write=False) +never run the gate at all — the caller sees the same dry-run result as before. + +The scheme parameter is optional in every signature; existing callers are +unaffected. +""" + +from __future__ import annotations + +from typing import Any, Dict, List, Optional, Tuple + +# WCAG 2.5.8 minimum target size (CSS px). Shipped control range for +# bar.dock.iconSize is 16-96 (tools.json); default 32. +TAP_TARGET_MIN_PX = 24 +TAP_TARGET_PATH = "bar.dock.iconSize" + +# WCAG 1.4.3 AA minimum contrast for normal text. +CONTRAST_MIN_AA = 4.5 + +# Text roles must be checked against background roles when both are present. +_TEXT_ROLES = ("foreground", "text", "accent") +_BG_ROLES = ("background", "base", "surface") + +_SKIPPED_CONTRAST_NOTE = ( + "contrast check skipped: no scheme colors were supplied to this write " + "path (shell.json carries no color leaves; the scheme system is outside " + "this file's scope)" +) + + +def _dotted_get(config: Dict[str, Any], dotted: str) -> Any: + node: Any = config + for segment in dotted.split("."): + if not isinstance(node, dict) or segment not in node: + return None + node = node[segment] + return node + + +def project(current: Dict[str, Any], entries: List[Dict[str, Any]]) -> Dict[str, Any]: + """Deep-copy `current` with the plan's applicable entries merged in — + the exact state the applier would serialize if it wrote. The deep copy + is a JSON round-trip (the config is JSON by definition, and json is the + already-allow-listed module — no import-policy expansion needed).""" + import json as _json + + projected = _json.loads(_json.dumps(current)) + for entry in entries: + path = str(entry.get("path", "")) + if not path or entry.get("error") or entry.get("no_op"): + continue + if entry.get("unset"): + segments = path.split(".") + node: Any = projected + for segment in segments[:-1]: + if not isinstance(node, dict) or segment not in node: + node = None + break + node = node[segment] + if isinstance(node, dict): + node.pop(segments[-1], None) + continue + value = _json.loads(_json.dumps(entry.get("new"))) # JSON-safe copy + segments = path.split(".") + node = projected + for segment in segments[:-1]: + nxt = node.get(segment) + if not isinstance(nxt, dict): + nxt = {} + node[segment] = nxt + node = nxt + node[segments[-1]] = value + return projected + + +def _contrast_verdicts(scheme: Dict[str, str]) -> Tuple[List[Dict[str, Any]], List[str]]: + """WCAG contrast for every (text role, background role) pair present in + the scheme. Returns (verdicts, unparseable_roles).""" + from assistant.capabilities.genius.creative import contrast_ratio + + verdicts: List[Dict[str, Any]] = [] + bad: List[str] = [] + for text_role in _TEXT_ROLES: + fg = scheme.get(text_role) + if fg is None: + continue + for bg_role in _BG_ROLES: + bg = scheme.get(bg_role) + if bg is None: + continue + try: + result = contrast_ratio(str(fg), str(bg)) + except (ValueError, TypeError): + bad.append(f"{text_role}/{bg_role}") + continue + verdicts.append({ + "text_role": text_role, + "background_role": bg_role, + "ratio": result["ratio"], + "aa_normal_text": result["aa_normal_text"], + }) + return verdicts, bad + + +def check(projected: Dict[str, Any], + scheme: Optional[Dict[str, str]] = None) -> Dict[str, Any]: + """Run the invariant checks over the POST-apply state. + + Returns {"refusals": [...], "warnings": [...], "notes": [...]}. An empty + refusals list means the write may proceed; applier.apply raises before + writing when refusals is non-empty. + """ + refusals: List[Dict[str, Any]] = [] + warnings: List[Dict[str, Any]] = [] + notes: List[str] = [] + + # 1. Tap-target size (WCAG 2.5.8) — warning, not refusal (see docstring). + icon = _dotted_get(projected, TAP_TARGET_PATH) + if isinstance(icon, (int, float)) and not isinstance(icon, bool): + if icon < TAP_TARGET_MIN_PX: + warnings.append({ + "id": "tap-target-below-wcag", + "path": TAP_TARGET_PATH, + "message": (f"projected {TAP_TARGET_PATH}={icon:g}px is below " + f"the WCAG 2.5.8 minimum target size " + f"({TAP_TARGET_MIN_PX}px); the shipped control " + "allows it, so the apply proceeds"), + "cite": (f"WCAG 2.5.8 Target Size (Minimum); " + f"assistant/settings/tools.json {TAP_TARGET_PATH} " + "range 16-96"), + }) + + # 2. Projected WCAG contrast — refusal, but only with scheme context. + if scheme: + verdicts, bad = _contrast_verdicts(scheme) + for v in verdicts: + if v["ratio"] is not None and v["ratio"] < CONTRAST_MIN_AA and \ + v["text_role"] in ("foreground", "text"): + refusals.append({ + "id": "contrast-below-aa", + "path": f"scheme:{v['text_role']}/{v['background_role']}", + "message": (f"projected contrast {v['text_role']} on " + f"{v['background_role']} is {v['ratio']:.2f}:1, " + f"below the WCAG 1.4.3 AA minimum " + f"({CONTRAST_MIN_AA}:1)"), + "cite": ("WCAG 1.4.3 Contrast (Minimum); " + "assistant/genius/creative.py::contrast_ratio"), + }) + if bad: + notes.append("scheme roles with unparseable colors ignored: " + + ", ".join(sorted(bad))) + else: + notes.append(_SKIPPED_CONTRAST_NOTE) + + return {"refusals": refusals, "warnings": warnings, "notes": notes} diff --git a/plugins/caelestia-assistant/assistant/capabilities/settings/slots.py b/plugins/caelestia-assistant/assistant/capabilities/settings/slots.py new file mode 100644 index 0000000..4c026b3 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/capabilities/settings/slots.py @@ -0,0 +1,391 @@ +"""Compositional slot grammar for the settings parser (the settings design notes (see module docstrings) §3.8). + +Issue A1's contract: paraphrases of the SAME intent should route through +ONE grammar — a slot model ``{intensifier, target, direction, dimension}`` +— instead of relying on the frozen grammar's exact phrase lists. + +Design boundary (why this is a RECOVERY layer, not a replacement): + +- ``settings/parser.py``'s frozen grammar is a documented, test-pinned + contract (the package rationale (see module docstrings) §7: "the frozen 18 tools and their natural-language + grammar are preserved byte-for-byte"). This module therefore NEVER runs + when the frozen grammar resolves a request: parser.py calls + ``recover()`` only on the paths where the frozen grammar already gave + up ("noun matched, no applicable cue" — the settings design notes (see module docstrings) §3.3 step 7). Every + frozen-verdict output is byte-identical to before by construction; the + only observable change is that some previously-AMBIGUOUS requests now + resolve to the same ops their canonical phrasings produce. +- The noun (target) surface is NOT grown: targets are exactly the + noun-matched ``ToolSpec`` list the frozen grammar already found. + No new nouns, no new tools, no per-tool phrase lists here — the + extended vocabulary below is per-DIMENSION (size/anim/trans/bool), + composed with the target by class, which is what makes paraphrases + share one grammar. + +The compositional rule (the whole point of A1): a direction WORD and a +dimension do not have to arrive pre-joined ("faster", "more transparent"). +They can arrive separately and be composed: + +- ``speed up`` + animations -> anim, faster -> step DOWN (durations scale) +- ``increase`` + transparency -> trans, more-transparent -> base DOWN +- ``increase`` + opacity -> trans, more-opaque -> base UP + +Formally: ``base_step = sign(word) * polarity(noun)`` where the trans +nouns carry their own polarity (transparency = -1 on the opacity-base +axis, opacity = +1). The same multiplication resolves every +verb/noun combination without listing the phrases. + +Intensifiers ("a bit", "slightly", "a lot", ...) are EXTRACTED and +reported but deliberately magnitude-neutral: the settings design notes (see module docstrings) §3.1 pins +"'a bit / slightly' does NOT change the step count (still ±1) — +documented, deterministic". Extending that pin to strong intensifiers +keeps one rule instead of two. + +Guarantees (same spine as parser.py): + +- PURE: no I/O, no environment, no clock, no randomness. Identical input, + identical output. +- Deterministic, stdlib ``re`` only; every regex compiled once at module + level. Extended vocabulary fires ONLY inside ``recover()``, never inside + the frozen grammar. +- Honest declines: two conflicting direction cues, no fitting target, + a bool cue on a numeric tool, or a magnitude (number/percent) in the + sentence all return ``None`` — the frozen grammar's AMBIGUOUS answer + stands. Recovery adds signal, never guesses. +""" + +from __future__ import annotations + +import re +from typing import Any, Dict, List, Optional, Sequence + +from assistant.adapters.caelestia.registry import ToolSpec + +__all__ = ["extract", "recover", "SLOTS_VERSION"] + +SLOTS_VERSION = 1 + +# --------------------------------------------------------------------------- +# Slot 1 — INTENSIFIER (extracted, reported, magnitude-neutral per §3.1). +# --------------------------------------------------------------------------- + +_LIGHT_INTENSIFIER_RE = re.compile( + r"\b(?:a bit|a little|a tad|a touch|slightly|somewhat|mildly|marginally)\b" +) +_STRONG_INTENSIFIER_RE = re.compile( + r"\b(?:a lot|much|significantly|noticeably|way|far|considerably|" + r"substantially|heavily|drastically|dramatically)\b" +) + +# --------------------------------------------------------------------------- +# Slot 2 — DIRECTION, extended lexicon (recovery path only). +# +# Multi-word verb-particle constructions are matched FIRST and masked out, +# so their particles ("up" in "speed up") are never re-read as bare size +# words. Each entry: (regex, dimension, sign on that dimension's axis). +# sign semantics per axis: +# size : +1 larger, -1 smaller (plain polarity) +# anim : +1 slower (durations UP), -1 faster (durations DOWN) — the +# documented inversion (parser.py §3.4, the settings design notes (see module docstrings) §2) +# trans : sign on the OPACITY-BASE axis (+1 more opaque, -1 more +# transparent); noun polarity multiplies this below +# --------------------------------------------------------------------------- + +_RECOVERY_DIRECTIONS: tuple = ( + # verb-particle constructions (anim axis, sign on the duration axis) + (re.compile(r"\bspeed(?:ing)? up\b"), "anim", -1), + (re.compile(r"\bhurry(?:ing)? up\b"), "anim", -1), + (re.compile(r"\bslow(?:ing)? down\b"), "anim", +1), + (re.compile(r"\bcrank(?:ing)? up\b"), "size", +1), + (re.compile(r"\bcrank(?:ing)? down\b"), "size", -1), + (re.compile(r"\bdial(?:ling)? back\b"), "size", -1), + (re.compile(r"\btone(?:ing)? down\b"), "size", -1), + (re.compile(r"\bbump(?:ing)? up\b"), "size", +1), + (re.compile(r"\bthin(?:ning)? out\b"), "size", -1), + (re.compile(r"\bfatten(?:ing)? up\b"), "size", +1), + # single verbs absent from the frozen vocabularies (§3.4 lists them) + (re.compile(r"\benlarge\b"), "size", +1), + (re.compile(r"\bexpand\b"), "size", +1), + (re.compile(r"\bboost\b"), "size", +1), + (re.compile(r"\bwiden\b"), "size", +1), + (re.compile(r"\bmaximize\b"), "size", +1), + (re.compile(r"\blengthen\b"), "size", +1), + (re.compile(r"\bheighten\b"), "size", +1), + (re.compile(r"\bnarrow\b"), "size", -1), + (re.compile(r"\bminimize\b"), "size", -1), + (re.compile(r"\btrim\b"), "size", -1), + (re.compile(r"\bshorten\b"), "size", -1), + (re.compile(r"\bthin\b"), "size", -1), + (re.compile(r"\bshave\b"), "size", -1), + # transparency axis (sign on the opacity base) + (re.compile(r"\bmore transparent\b"), "trans", -1), + (re.compile(r"\bmore see-through\b"), "trans", -1), + (re.compile(r"\bmore translucent\b"), "trans", -1), + (re.compile(r"\bmore opaque\b"), "trans", +1), + (re.compile(r"\bmore solid\b"), "trans", +1), +) + +# Bare size-direction words the frozen grammar ALREADY knows (§3.4) — reused +# here only for cross-dimension composition (e.g. "increase the +# transparency"), never to re-implement the frozen match. +_GENERIC_UP_RE = re.compile( + r"\b(?:increase|raise|more|grow|raise|boost|higher)\b" +) +_GENERIC_DOWN_RE = re.compile( + r"\b(?:reduce|decrease|less|lower|reduce|fewer)\b" +) + +# Trans-noun polarity on the opacity-base axis (the compositional core): +# "transparency" and "opacity" point in OPPOSITE directions on the same knob. +_TRANS_NOUN_POLARITY = ( + (re.compile(r"\btransparen(?:cy|t)\b"), -1), + (re.compile(r"\bsee-through\b"), -1), + (re.compile(r"\btranslucen(?:t|cy)\b"), -1), + (re.compile(r"\bopacit?y\b|\bopaque\b"), +1), +) + +# Slot 2b — verbal bool cues the frozen grammar does not carry (§3.5 shape). +_BOOL_ACTIVATE_RE = re.compile(r"\b(?:activate|switch on|turn on)\b") +_BOOL_DEACTIVATE_RE = re.compile(r"\b(?:deactivate|switch off|turn off)\b") + +# Magnitude presence — recovery declines when the sentence carries a number +# or a percent: those belong to the frozen value-phrase paths (§3.4), and a +# recovery layer inventing magnitudes would be a silent guess. +_HAS_NUMBER_RE = re.compile(r"\d") +_HAS_PERCENT_RE = re.compile(r"%") + + +def _mask(text: str, spans: Sequence) -> str: + chars = list(text) + for start, end in spans: + for idx in range(start, min(end, len(chars))): + chars[idx] = " " + return "".join(chars) + + +# --------------------------------------------------------------------------- +# extract() — the pure slot extractor. +# --------------------------------------------------------------------------- + + +def extract(text: str) -> Dict[str, Any]: + """Extract the four slots from normalized text (pure, total function). + + Returns ``{"intensifier": "light"|"strong"|None, + "cue": {"dimension": "size"|"anim"|"trans"|"bool", + "sign": int, "raw": str} | None, + "generic": {"sign": int, "raw": str} | None, + "trans_polarity": {"sign": int, "raw": str} | None, + "conflict": bool}``. + + ``conflict`` is True when two direction cues disagree on the same + dimension — the honest decline signal (recover() returns None). + """ + intensifier = None + masked = text + for kind, regex in (("light", _LIGHT_INTENSIFIER_RE), + ("strong", _STRONG_INTENSIFIER_RE)): + found = list(regex.finditer(masked)) + if found and intensifier is None: + intensifier = kind + masked = _mask(masked, [m.span() for m in found]) + + cue: Optional[Dict[str, Any]] = None + generic: Optional[Dict[str, Any]] = None + conflict = False + for regex, dimension, sign in _RECOVERY_DIRECTIONS: + found = list(regex.finditer(masked)) + if not found: + continue + masked = _mask(masked, [m.span() for m in found]) + if cue is None: + cue = {"dimension": dimension, "sign": sign, "raw": found[0].group(0)} + elif (cue["dimension"], cue["sign"]) != (dimension, sign): + conflict = True + + for regex, sign in ((_GENERIC_UP_RE, +1), (_GENERIC_DOWN_RE, -1)): + found = list(regex.finditer(masked)) + if not found: + continue + masked = _mask(masked, [m.span() for m in found]) + if generic is None: + generic = {"sign": sign, "raw": found[0].group(0)} + elif generic["sign"] != sign: + conflict = True + + trans_polarity: Optional[Dict[str, Any]] = None + for regex, polarity in _TRANS_NOUN_POLARITY: + found = regex.search(text) + if found: + trans_polarity = {"sign": polarity, "raw": found.group(0)} + break + + return { + "intensifier": intensifier, + "cue": cue, + "generic": generic, + "trans_polarity": trans_polarity, + "conflict": conflict, + } + + +# --------------------------------------------------------------------------- +# recover() — compose the slots into frozen-grammar-shaped ops. +# --------------------------------------------------------------------------- + + +def recover(normalized: str, noun_specs: Sequence[ToolSpec]) -> Optional[Dict[str, Any]]: + """Try to compose an INTENT result the frozen grammar could not. + + Called ONLY from parser.py on the §3.3 step-7 paths (noun matched, no + applicable cue). Returns a parser-shaped result dict, or None to keep + the frozen AMBIGUOUS verdict. Pure; never raises on odd input. + """ + if not noun_specs: + return None + if _HAS_NUMBER_RE.search(normalized) or _HAS_PERCENT_RE.search(normalized): + return None # magnitudes belong to the frozen value-phrase paths + + # Lazy import: parser imports this module at load time; the note helpers + # are only needed at recover() call time, after both modules are fully + # initialized. Keeps every §3.5/§3.4 note string single-sourced. + from .parser import _ANIM_INVERSION_NOTE, _bool_note + + slots = extract(normalized) + if slots["conflict"]: + return None + + # -- verbal bool cues: only bool tools, only with an honest note ------- + bool_ops: List[Dict[str, Any]] = [] + bool_targets = [s for s in noun_specs if s.kind == "bool"] + for regex, value in ((_BOOL_ACTIVATE_RE, True), (_BOOL_DEACTIVATE_RE, False)): + found = regex.search(normalized) + if not found or not bool_targets: + continue + raw = found.group(0) + for spec in bool_targets: + op: Dict[str, Any] = { + "tool": spec.name, "action": "set", "value": value, "raw": raw, + } + op["note"] = _bool_note(spec.name, raw, value) + bool_ops.append(op) + break # first applicable cue wins; on+off together would conflict + + cue, generic, polarity = slots["cue"], slots["generic"], slots["trans_polarity"] + if bool_ops and cue is None and generic is None: + return _recovered(bool_ops, slots) + if bool_ops: + return None # a direction cue AND an explicit on/off word: the frozen + # grammar's split-question territory, not ours to guess + + if cue is None and generic is None: + return None + + # -- compose {direction} x {dimension} x {target class} ---------------- + # One direction slot per sentence (conflicts already declined above), + # applied to EVERY fitting target — the same single-phrase pattern the + # frozen grammar uses for "make the bar and the dock icons bigger". + ops: List[Dict[str, Any]] = [] + for spec in noun_specs: + composed = _compose(cue, generic, polarity, spec) + if composed is None: + continue + dimension, sign, raw = composed + if dimension == "bool_size": + # §3.5: comparatives on bool tools map to on/off WITH the note. + value = sign > 0 + op = {"tool": spec.name, "action": "set", "value": value, "raw": raw, + "note": _bool_note(spec.name, raw, value)} + else: + note = _ANIM_INVERSION_NOTE if spec.name == "setAnimationSpeed" else None + op = {"tool": spec.name, "action": "step", "value": sign, "raw": raw} + if note: + op["note"] = note + ops.append(op) + + if not ops: + return None + return _recovered(ops, slots) + + +def _compose(cue: Optional[Dict[str, Any]], + generic: Optional[Dict[str, Any]], + polarity: Optional[Dict[str, Any]], + spec: ToolSpec) -> Optional[tuple]: + """One slot composition for one target tool. + + Returns (dimension, sign, raw) or None when the composition does not + fit the tool's class. The multiplication ``sign * polarity`` is the + trans-noun rule; the anim axis inverts bare up/down words ("speed up" + arrives pre-composed and is never inverted twice). + """ + # Pre-joined cues compose only with their own dimension's tools. + if cue is not None: + dimension, sign, raw = cue["dimension"], cue["sign"], cue["raw"] + if dimension == "size": + if spec.name == "setTransparencyBase": + # A size verb on the trans knob goes through the SAME + # polarity multiplication as generic words: "boost the + # transparency" is step DOWN, not up. + if polarity is None: + return None + return ("trans", sign * polarity["sign"], raw) + if spec.name == "setAnimationSpeed": + return None # size vocabulary never reaches the anim tool + if spec.kind in ("float", "int"): + return ("size", sign, raw) + if spec.kind == "bool": + return ("bool_size", 1 if sign > 0 else -1, raw) + return None + if dimension == "anim": + return ("anim", sign, raw) if spec.name == "setAnimationSpeed" else None + if dimension == "trans": + return ("trans", sign, raw) if spec.name == "setTransparencyBase" else None + return None + + # Generic direction words compose with the target's own dimension. + # The anim axis is deliberately NOT composed from generics: "increase + # the animations" is genuinely ambiguous between more-speed and + # more-duration, so it declines (only pre-joined cues — "speed up", + # "slow down" — or the frozen "faster/slower" words reach that tool). + if generic is not None: + sign, raw = generic["sign"], generic["raw"] + if spec.name == "setAnimationSpeed": + return None # generic words decline on the anim axis (see above) + if spec.name == "setTransparencyBase": + if polarity is None: + return None # "more" of what? the noun must say (honest decline) + return ("trans", sign * polarity["sign"], f"{raw} {polarity['raw']}") + if spec.kind in ("float", "int"): + return ("size", sign, raw) + if spec.kind == "bool": + # §3.5: comparatives on bool tools map to on/off with the note. + return ("bool_size", 1 if sign > 0 else -1, raw) + return None + + +def _recovered(ops: List[Dict[str, Any]], slots: Dict[str, Any]) -> Dict[str, Any]: + from .parser import _result + + intensifier = slots["intensifier"] + slot_bits = [] + if ops: + tools = ", ".join(sorted({op["tool"] for op in ops})) + slot_bits.append(f"target={tools}") + cue = slots["cue"] or slots["generic"] + if cue: + word_dir = "up" if cue.get("sign", 0) > 0 else "down" + polarity = slots["trans_polarity"] + if polarity is not None and any( + op["tool"] == "setTransparencyBase" for op in ops): + composed = "down" if cue.get("sign", 0) * polarity["sign"] < 0 else "up" + slot_bits.append( + f"direction={word_dir} (word) x polarity={polarity['raw']}" + f"({polarity['sign']:+d}) -> {composed} on the opacity base") + else: + slot_bits.append(f"direction={word_dir}") + if intensifier: + slot_bits.append( + f"intensifier={intensifier} (magnitude-neutral per the settings design notes (see module docstrings) §3.1)") + note = "compositional slot grammar (§3.8): " + "; ".join(slot_bits) + return _result("INTENT", ops=ops, notes=[note]) diff --git a/plugins/caelestia-assistant/assistant/capabilities/settings/ui_ranges_data.py b/plugins/caelestia-assistant/assistant/capabilities/settings/ui_ranges_data.py new file mode 100755 index 0000000..81551c1 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/capabilities/settings/ui_ranges_data.py @@ -0,0 +1,328 @@ +"""Transcribed shipped Nexus control table (a full Nexus survey: 318 rows). + +Pure data: one row per config key that a shipped Nexus control reads +or writes. min/max/step/enum are adopted EXACTLY as the QML declares +them (SliderRow values are normalized 0..1 by StyledSlider.qml:152,173). +Every row carries the file:line it was transcribed from. +""" + +UI_RANGES = { + "Colours.setIntensity (scheme intensity; stored in scheme.json via CLI, not Config)": {"control": 'SliderRow (enabled only when Colours.scheme === "dynamic")', "min": 0, "max": 1, "note": 'step: fraction of maxIntensity=2.0 (caelestia scheme set -i 0..2)', "page": 'Advanced colors', "file": 'shell/modules/nexus/pages/wallandstyle/AdvancedColorsPage.qml', "line": 140}, + "KrohnkiteConfig.screenGapBetween (kwinrc, not shell config)": {"control": 'StepperRow', "min": 0, "max": 80, "note": 'step: (default 1)', "page": 'Window Tiling', "file": 'shell/modules/nexus/pages/desktop/KrohnkitePage.qml', "line": 169}, + "KrohnkiteConfig.screenGapTop/Bottom/Left/Right (kwinrc)": {"control": 'StepperRow', "min": 0, "max": 80, "note": 'step: (default 1)', "page": 'Window Tiling', "file": 'shell/modules/nexus/pages/desktop/KrohnkitePage.qml', "line": 179}, + "ai.claudeAccountsJson / ai.activeClaudeAccount": {"control": 'account cards (JSON list)', "page": 'AI Assistant', "file": 'shell/modules/nexus/pages/AiSettingsPage.qml', "line": 323}, + "ai.enableClaude": {"control": 'ToggleRow', "page": 'AI Assistant', "file": 'shell/modules/nexus/pages/AiSettingsPage.qml', "line": 587}, + "ai.enableClaudeCode": {"control": 'ToggleRow', "page": 'AI Assistant', "file": 'shell/modules/nexus/pages/AiSettingsPage.qml', "line": 579}, + "ai.enableGemini": {"control": 'ToggleRow', "page": 'AI Assistant', "file": 'shell/modules/nexus/pages/AiSettingsPage.qml', "line": 607}, + "ai.enableOllama": {"control": 'ToggleRow', "page": 'AI Assistant', "file": 'shell/modules/nexus/pages/AiSettingsPage.qml', "line": 544}, + "ai.enableOpenai": {"control": 'ToggleRow', "page": 'AI Assistant', "file": 'shell/modules/nexus/pages/AiSettingsPage.qml', "line": 599}, + "ai.enableOpencode": {"control": 'ToggleRow', "page": 'AI Assistant', "file": 'shell/modules/nexus/pages/AiSettingsPage.qml', "line": 621}, + "ai.enableOpencodeGo": {"control": 'ToggleRow', "page": 'AI Assistant', "file": 'shell/modules/nexus/pages/AiSettingsPage.qml', "line": 628}, + "ai.enableOpenrouter": {"control": 'ToggleRow', "page": 'AI Assistant', "file": 'shell/modules/nexus/pages/AiSettingsPage.qml', "line": 614}, + "ai.showCaelestiaMode": {"control": 'ToggleRow', "page": 'Sidebar', "file": 'shell/modules/nexus/pages/panels/SidebarPanel.qml', "line": 75}, + "ai.showNews": {"control": 'ToggleRow', "page": 'Sidebar', "file": 'shell/modules/nexus/pages/panels/SidebarPanel.qml', "line": 66}, + "appearance.ambientColor": {"control": 'ToggleRow (enabled only when !Colours.light)', "page": 'Theme & Effects', "file": 'shell/modules/nexus/pages/wallandstyle/AppearancePage.qml', "line": 158}, + "appearance.ambientOpacity": {"control": 'SliderRow', "min": 0, "max": 1, "note": 'step: wheel=services.audioIncrement (enabled: ambientColor && !Colours.light)', "page": 'Theme & Effects', "file": 'shell/modules/nexus/pages/wallandstyle/AppearancePage.qml', "line": 167}, + "appearance.anim.durations.scale": {"control": 'StepperRow', "min": 0.25, "max": 4, "step": 0.05, "page": 'Theme & Effects', "file": 'shell/modules/nexus/pages/wallandstyle/AppearancePage.qml', "line": 316}, + "appearance.blur": {"control": 'ToggleRow (enabled: transparency.enabled && !better_blur_dx)', "page": 'Theme & Effects', "file": 'shell/modules/nexus/pages/wallandstyle/AppearancePage.qml', "line": 222}, + "appearance.blurMask": {"control": 'ToggleRow (enabled: transparency.enabled && blur)', "page": 'Theme & Effects', "file": 'shell/modules/nexus/pages/wallandstyle/AppearancePage.qml', "line": 246}, + "appearance.deformScale": {"control": 'StepperRow', "min": 0, "max": 1.5, "step": 0.05, "page": 'Theme & Effects', "file": 'shell/modules/nexus/pages/wallandstyle/AppearancePage.qml', "line": 357}, + "appearance.font.mono.family": {"control": 'FontCard (select-one card)', "enum": ["SF Mono", "CaskaydiaCove NF"], "page": 'Theme & Effects', "file": 'shell/modules/nexus/pages/wallandstyle/AppearancePage.qml', "line": 375}, + "appearance.font.scale": {"control": 'StepperRow', "min": 0.5, "max": 2, "step": 0.05, "page": 'Theme & Effects', "file": 'shell/modules/nexus/pages/wallandstyle/AppearancePage.qml', "line": 285}, + "appearance.font.{headline,title,body,label}.family": {"control": 'FontCard (select-one card)', "enum": ["SF Pro", "GoogleSansFlex"], "page": 'Theme & Effects', "file": 'shell/modules/nexus/pages/wallandstyle/AppearancePage.qml', "line": 370}, + "appearance.islands": {"control": 'ToggleRow ("Islands")', "page": 'Theme & Effects', "file": 'shell/modules/nexus/pages/wallandstyle/AppearancePage.qml', "line": 100}, + "appearance.padding.scale": {"control": 'StepperRow', "min": 0.5, "max": 2, "step": 0.05, "page": 'Theme & Effects', "file": 'shell/modules/nexus/pages/wallandstyle/AppearancePage.qml', "line": 306}, + "appearance.pitchBlack": {"control": 'ToggleRow ("Bezel mode (Pitch black)")', "page": 'Theme & Effects', "file": 'shell/modules/nexus/pages/wallandstyle/AppearancePage.qml', "line": 92}, + "appearance.rounding.scale": {"control": 'StepperRow', "min": 0.5, "max": 2.0, "step": 0.1, "page": 'Theme & Effects', "file": 'shell/modules/nexus/pages/wallandstyle/AppearancePage.qml', "line": 118}, + "appearance.spacing.scale": {"control": 'StepperRow', "min": 0.5, "max": 2, "step": 0.05, "page": 'Theme & Effects', "file": 'shell/modules/nexus/pages/wallandstyle/AppearancePage.qml', "line": 296}, + "appearance.transparency.base": {"control": 'SliderRow', "min": 0, "max": 1, "note": 'step: wheel=services.audioIncrement (normalized 0-1 slider)', "page": 'Theme & Effects', "file": 'shell/modules/nexus/pages/wallandstyle/AppearancePage.qml', "line": 141}, + "appearance.transparency.enabled": {"control": 'ToggleRow (off also forces appearance.blur=false)', "page": 'Theme & Effects', "file": 'shell/modules/nexus/pages/wallandstyle/AppearancePage.qml', "line": 128}, + "appearance.transparency.layers": {"control": 'SliderRow', "min": 0, "max": 1, "note": 'step: wheel=services.audioIncrement (normalized 0-1 slider)', "page": 'Theme & Effects', "file": 'shell/modules/nexus/pages/wallandstyle/AppearancePage.qml', "line": 149}, + "audio.sounds.cameraClick": {"control": 'ToggleRow (enabled: audio.sounds.enabled)', "page": 'Sound effects', "file": 'shell/modules/nexus/pages/audio/SoundEffectsPage.qml', "line": 46}, + "audio.sounds.chargingStarted": {"control": 'ToggleRow (enabled: audio.sounds.enabled)', "page": 'Sound effects', "file": 'shell/modules/nexus/pages/audio/SoundEffectsPage.qml', "line": 66}, + "audio.sounds.disabledNotifApps": {"control": 'chips list (StyledInputField add/remove)', "page": 'Muted notification apps', "file": 'shell/modules/nexus/pages/audio/NotificationSilencingPage.qml', "line": 19}, + "audio.sounds.effectTick": {"control": 'ToggleRow (enabled: audio.sounds.enabled)', "page": 'Sound effects', "file": 'shell/modules/nexus/pages/audio/SoundEffectsPage.qml', "line": 54}, + "audio.sounds.enabled": {"control": 'ToggleRow', "page": 'Sound effects', "file": 'shell/modules/nexus/pages/audio/SoundEffectsPage.qml', "line": 24}, + "audio.sounds.lock": {"control": 'ToggleRow (enabled: audio.sounds.enabled)', "page": 'Sound effects', "file": 'shell/modules/nexus/pages/audio/SoundEffectsPage.qml', "line": 74}, + "audio.sounds.lowBattery": {"control": 'ToggleRow (enabled: audio.sounds.enabled)', "page": 'Sound effects', "file": 'shell/modules/nexus/pages/audio/SoundEffectsPage.qml', "line": 88}, + "audio.sounds.notificationVolume": {"control": 'SliderRow', "min": 0, "max": 1, "note": 'step: wheel=services.audioIncrement (enabled: audio.sounds.enabled)', "page": 'Toasts', "file": 'shell/modules/nexus/pages/services/ToastPreferencesPage.qml', "line": 80}, + "audio.sounds.screenRecord": {"control": 'ToggleRow (enabled: audio.sounds.enabled)', "page": 'Sound effects', "file": 'shell/modules/nexus/pages/audio/SoundEffectsPage.qml', "line": 95}, + "audio.sounds.sfxVolume": {"control": 'SliderRow', "min": 0, "max": 1, "note": 'step: wheel=services.audioIncrement (enabled: audio.sounds.enabled)', "page": 'Sound effects', "file": 'shell/modules/nexus/pages/audio/SoundEffectsPage.qml', "line": 31}, + "audio.sounds.unlock": {"control": 'ToggleRow (enabled: audio.sounds.enabled)', "page": 'Sound effects', "file": 'shell/modules/nexus/pages/audio/SoundEffectsPage.qml', "line": 81}, + "background.desktopClock.enabled": {"control": 'ToggleRow', "page": 'Desktop Addons', "file": 'shell/modules/nexus/pages/wallandstyle/DesktopAddonsPage.qml', "line": 89}, + "background.desktopClock.invertColors": {"control": 'ToggleRow', "page": 'Desktop Addons', "file": 'shell/modules/nexus/pages/wallandstyle/DesktopAddonsPage.qml', "line": 213}, + "background.desktopClock.position": {"control": 'SelectRow', "enum": ["top-left", "top-center", "top-right", "center", "bottom-left", "bottom-center", "bottom-right"], "page": 'Desktop Addons', "file": 'shell/modules/nexus/pages/wallandstyle/DesktopAddonsPage.qml', "line": 197}, + "background.desktopClock.scale": {"control": 'StepperRow', "min": 0.5, "max": 3, "step": 0.1, "page": 'Desktop Addons', "file": 'shell/modules/nexus/pages/wallandstyle/DesktopAddonsPage.qml', "line": 186}, + "background.desktopIconsEnabled": {"control": 'ToggleRow (enabled: wallpaperEnabled; resets per-screen overrides)', "page": 'Desktop & Tiling', "file": 'shell/modules/nexus/pages/DesktopPage.qml', "line": 40}, + "background.desktopLyrics.alignment": {"control": 'SelectRow', "enum": ["0=Left", "1=Center", "2=Right"], "page": 'Desktop Addons', "file": 'shell/modules/nexus/pages/wallandstyle/DesktopAddonsPage.qml', "line": 294}, + "background.desktopLyrics.autoHide": {"control": 'ToggleRow (visible: desktopLyrics.enabled)', "page": 'Desktop Addons', "file": 'shell/modules/nexus/pages/wallandstyle/DesktopAddonsPage.qml', "line": 131}, + "background.desktopLyrics.enabled": {"control": 'ToggleRow (off also resets desktopLyrics.autoHide)', "page": 'Desktop Addons', "file": 'shell/modules/nexus/pages/wallandstyle/DesktopAddonsPage.qml', "line": 119}, + "background.desktopLyrics.invertColors": {"control": 'ToggleRow', "page": 'Desktop Addons', "file": 'shell/modules/nexus/pages/wallandstyle/DesktopAddonsPage.qml', "line": 308}, + "background.desktopLyrics.position": {"control": 'SelectRow', "enum": ["top-left", "top-center", "top-right", "center", "bottom-left", "bottom-center", "bottom-right"], "page": 'Desktop Addons', "file": 'shell/modules/nexus/pages/wallandstyle/DesktopAddonsPage.qml', "line": 278}, + "background.desktopLyrics.scale": {"control": 'StepperRow', "min": 0.5, "max": 3, "step": 0.1, "page": 'Desktop Addons', "file": 'shell/modules/nexus/pages/wallandstyle/DesktopAddonsPage.qml', "line": 267}, + "background.desktopShapes.autoHide": {"control": 'ToggleRow (visible: desktopShapes.enabled)', "page": 'Desktop Addons', "file": 'shell/modules/nexus/pages/wallandstyle/DesktopAddonsPage.qml', "line": 109}, + "background.desktopShapes.enabled": {"control": 'ToggleRow (off also resets desktopShapes.autoHide)', "page": 'Desktop Addons', "file": 'shell/modules/nexus/pages/wallandstyle/DesktopAddonsPage.qml', "line": 97}, + "background.desktopShapes.position": {"control": 'SelectRow', "enum": ["top-left", "top-center", "top-right", "center", "bottom-left", "bottom-center", "bottom-right"], "page": 'Desktop Addons', "file": 'shell/modules/nexus/pages/wallandstyle/DesktopAddonsPage.qml', "line": 241}, + "background.desktopShapes.scale": {"control": 'StepperRow', "min": 0.5, "max": 3, "step": 0.1, "page": 'Desktop Addons', "file": 'shell/modules/nexus/pages/wallandstyle/DesktopAddonsPage.qml', "line": 230}, + "background.materialYouIconsEnabled": {"control": 'ToggleRow (enabled: wallpaperEnabled && desktopIconsEnabled)', "page": 'Desktop & Tiling', "file": 'shell/modules/nexus/pages/DesktopPage.qml', "line": 57}, + "background.materialYouIconsVibrant": {"control": 'ToggleRow (enabled: wallpaperEnabled && desktopIconsEnabled && materialYouIconsEnabled)', "page": 'Desktop & Tiling', "file": 'shell/modules/nexus/pages/DesktopPage.qml', "line": 74}, + "background.slideshowEnabled": {"control": 'ToggleRow (enabled: background.wallpaperEnabled)', "page": 'Slideshow & Order', "file": 'shell/modules/nexus/pages/wallandstyle/SlideshowAndOrderPage.qml', "line": 33}, + "background.slideshowInterval": {"control": 'SliderRow', "min": 0, "max": 1, "note": 'step: wheel=services.audioIncrement (fraction of 60 min; valueLabel = max(1, round(v*60)) min)', "page": 'Slideshow & Order', "file": 'shell/modules/nexus/pages/wallandstyle/SlideshowAndOrderPage.qml', "line": 43}, + "background.slideshowRandom": {"control": 'ToggleRow (enabled: background.wallpaperEnabled)', "page": 'Slideshow & Order', "file": 'shell/modules/nexus/pages/wallandstyle/SlideshowAndOrderPage.qml', "line": 54}, + "background.videoWallpaperMuteOnMedia": {"control": 'ToggleRow', "page": 'Video wallpapers', "file": 'shell/modules/nexus/pages/wallandstyle/VideoWallpapersPage.qml', "line": 61}, + "background.videoWallpaperPauseOnAllDisplays": {"control": 'ToggleRow', "page": 'Video wallpapers', "file": 'shell/modules/nexus/pages/wallandstyle/VideoWallpapersPage.qml', "line": 55}, + "background.videoWallpaperPauseOnFullscreen": {"control": 'ToggleRow (visible only on Hyprland)', "page": 'Video wallpapers', "file": 'shell/modules/nexus/pages/wallandstyle/VideoWallpapersPage.qml', "line": 41}, + "background.videoWallpaperPauseOnTiled": {"control": 'ToggleRow (visible only on Hyprland)', "page": 'Video wallpapers', "file": 'shell/modules/nexus/pages/wallandstyle/VideoWallpapersPage.qml', "line": 48}, + "background.videoWallpaperPaused": {"control": 'ToggleRow', "page": 'Video wallpapers', "file": 'shell/modules/nexus/pages/wallandstyle/VideoWallpapersPage.qml', "line": 28}, + "background.videoWallpaperSoundEnabled": {"control": 'ToggleRow', "page": 'Video wallpapers', "file": 'shell/modules/nexus/pages/wallandstyle/VideoWallpapersPage.qml', "line": 35}, + "background.visualiser.autoHide": {"control": 'ToggleRow (visible: visualiser.enabled)', "page": 'Desktop Addons', "file": 'shell/modules/nexus/pages/wallandstyle/DesktopAddonsPage.qml', "line": 155}, + "background.visualiser.blur": {"control": 'ToggleRow', "page": 'Desktop Addons', "file": 'shell/modules/nexus/pages/wallandstyle/DesktopAddonsPage.qml', "line": 325}, + "background.visualiser.enabled": {"control": 'ToggleRow (off also resets visualiser.autoHide)', "page": 'Desktop Addons', "file": 'shell/modules/nexus/pages/wallandstyle/DesktopAddonsPage.qml', "line": 141}, + "background.visualiser.hideOnAllMonitors": {"control": 'ToggleRow (enabled: visualiser.autoHide; visible: visualiser.enabled)', "page": 'Desktop Addons', "file": 'shell/modules/nexus/pages/wallandstyle/DesktopAddonsPage.qml', "line": 165}, + "background.visualiser.rounding": {"control": 'StepperRow', "min": 0, "max": 1, "step": 0.05, "page": 'Desktop Addons', "file": 'shell/modules/nexus/pages/wallandstyle/DesktopAddonsPage.qml', "line": 333}, + "background.visualiser.spacing": {"control": 'StepperRow', "min": 0.5, "max": 3, "step": 0.1, "page": 'Desktop Addons', "file": 'shell/modules/nexus/pages/wallandstyle/DesktopAddonsPage.qml', "line": 343}, + "background.wallpaperEnabled": {"control": 'ToggleRow (inverted: "Show KDE Desktop" writes !checked; resets per-screen overrides)', "page": 'Desktop & Tiling', "file": 'shell/modules/nexus/pages/DesktopPage.qml', "line": 24}, + "background.wallpaperFillMode": {"control": 'SelectRow', "enum": ["Crop", "Fit", "Stretch (Image.PreserveAspectCrop/PreserveAspectFit/Stretch)"], "page": 'Wallpaper settings', "file": 'shell/modules/nexus/pages/wallandstyle/WallpaperSettingsPage.qml', "line": 49}, + "background.wallpaperRecolor": {"control": 'ToggleRow (enabled: background.wallpaperEnabled)', "page": 'Wallpaper settings', "file": 'shell/modules/nexus/pages/wallandstyle/WallpaperSettingsPage.qml', "line": 68}, + "background.wallpaperRecolorStrength": {"control": 'SliderRow', "min": 0, "max": 1, "note": 'step: wheel=services.audioIncrement (enabled: wallpaperRecolor && wallpaperEnabled)', "page": 'Wallpaper settings', "file": 'shell/modules/nexus/pages/wallandstyle/WallpaperSettingsPage.qml', "line": 85}, + "bar.clock.background": {"control": 'ToggleRow', "page": 'Clock', "file": 'shell/modules/nexus/pages/panels/taskbar/BarClock.qml', "line": 19}, + "bar.clock.showDate": {"control": 'ToggleRow', "page": 'Clock', "file": 'shell/modules/nexus/pages/panels/taskbar/BarClock.qml', "line": 26}, + "bar.clock.showIcon": {"control": 'ToggleRow', "page": 'Clock', "file": 'shell/modules/nexus/pages/panels/taskbar/BarClock.qml', "line": 32}, + "bar.clock.showSeconds": {"control": 'ToggleRow', "page": 'Clock', "file": 'shell/modules/nexus/pages/panels/taskbar/BarClock.qml', "line": 38}, + "bar.dock.currentDesktopOnly": {"control": 'ToggleRow', "page": 'Dock', "file": 'shell/modules/nexus/pages/panels/taskbar/BarDock.qml', "line": 83}, + "bar.dock.iconSize": {"control": 'StepperRow', "min": 20, "step": 2, "note": 'max: max(20, Tokens.sizes.bar.innerWidth)', "page": 'Dock', "file": 'shell/modules/nexus/pages/panels/taskbar/BarDock.qml', "line": 54}, + "bar.dock.previewOnDesktop": {"control": 'ToggleRow', "page": 'Dock', "file": 'shell/modules/nexus/pages/panels/taskbar/BarDock.qml', "line": 91}, + "bar.dock.recolourIcons": {"control": 'ToggleRow', "page": 'Dock', "file": 'shell/modules/nexus/pages/panels/taskbar/BarDock.qml', "line": 67}, + "bar.dock.showBadges": {"control": 'ToggleRow', "page": 'Dock', "file": 'shell/modules/nexus/pages/panels/taskbar/BarDock.qml', "line": 75}, + "bar.dodgeFocusedOnly": {"control": 'ToggleRow (enabled: bar.persistent && bar.dodgeWindows)', "page": 'Taskbar', "file": 'shell/modules/nexus/pages/panels/TaskbarPanel.qml', "line": 83}, + "bar.dodgeWindows": {"control": 'ToggleRow (enabled: bar.persistent)', "page": 'Taskbar', "file": 'shell/modules/nexus/pages/panels/TaskbarPanel.qml', "line": 75}, + "bar.dragThreshold": {"control": 'StepperRow', "min": 0, "max": 200, "step": 5, "page": 'Taskbar', "file": 'shell/modules/nexus/pages/panels/TaskbarPanel.qml', "line": 107}, + "bar.entries (dock.enabled)": {"control": 'ToggleRow', "page": 'Dock', "file": 'shell/modules/nexus/pages/panels/taskbar/BarDock.qml', "line": 20}, + "bar.entries (greeter/activeWindow.enabled)": {"control": 'ToggleRow', "page": 'Greeter', "file": 'shell/modules/nexus/pages/panels/taskbar/BarGreeter.qml', "line": 66}, + "bar.entries (updateIndicator.enabled)": {"control": 'ToggleRow', "page": 'Update indicator', "file": 'shell/modules/nexus/pages/panels/taskbar/BarUpdates.qml', "line": 28}, + "bar.fontScaleOffset": {"control": 'StepperRow', "min": -1.0, "max": 1.0, "step": 0.05, "page": 'Taskbar', "file": 'shell/modules/nexus/pages/panels/TaskbarPanel.qml', "line": 192}, + "bar.github.background": {"control": 'ToggleRow', "page": 'GitHub', "file": 'shell/modules/nexus/pages/panels/taskbar/BarGithub.qml', "line": 99}, + "bar.greeter.afternoonStart": {"control": 'StepperRow', "min": 0, "max": 23, "step": 1, "page": 'Greeter', "file": 'shell/modules/nexus/pages/panels/taskbar/BarGreeter.qml', "line": 228}, + "bar.greeter.compact": {"control": 'ToggleRow', "page": 'Greeter', "file": 'shell/modules/nexus/pages/panels/taskbar/BarGreeter.qml', "line": 97}, + "bar.greeter.eveningStart": {"control": 'StepperRow', "min": 0, "max": 23, "step": 1, "page": 'Greeter', "file": 'shell/modules/nexus/pages/panels/taskbar/BarGreeter.qml', "line": 273}, + "bar.greeter.inverted": {"control": 'ToggleRow', "page": 'Greeter', "file": 'shell/modules/nexus/pages/panels/taskbar/BarGreeter.qml', "line": 107}, + "bar.greeter.mode": {"control": 'SelectRow', "enum": ["timeOfDay", "slideshow"], "page": 'Greeter', "file": 'shell/modules/nexus/pages/panels/taskbar/BarGreeter.qml', "line": 141}, + "bar.greeter.morningStart": {"control": 'StepperRow', "min": 0, "max": 23, "step": 1, "page": 'Greeter', "file": 'shell/modules/nexus/pages/panels/taskbar/BarGreeter.qml', "line": 183}, + "bar.greeter.nightStart": {"control": 'StepperRow', "min": 0, "max": 23, "step": 1, "page": 'Greeter', "file": 'shell/modules/nexus/pages/panels/taskbar/BarGreeter.qml', "line": 318}, + "bar.greeter.showOnHover": {"control": 'ToggleRow', "page": 'Greeter', "file": 'shell/modules/nexus/pages/panels/taskbar/BarGreeter.qml', "line": 116}, + "bar.greeter.slideshowInterval": {"control": 'StepperRow', "min": 5, "max": 3600, "step": 5, "enum": [" (seconds)"], "page": 'Greeter', "file": 'shell/modules/nexus/pages/panels/taskbar/BarGreeter.qml', "line": 352}, + "bar.greeter.slideshowRandom": {"control": 'ToggleRow', "page": 'Greeter', "file": 'shell/modules/nexus/pages/panels/taskbar/BarGreeter.qml', "line": 367}, + "bar.livePreviews": {"control": 'ToggleRow', "page": 'Taskbar', "file": 'shell/modules/nexus/pages/panels/TaskbarPanel.qml', "line": 178}, + "bar.perElementPreviewScale + bar.perElementFontScale": {"control": 'ToggleRow (master; sets both)', "page": 'Per-element scaling offsets', "file": 'shell/modules/nexus/pages/panels/taskbar/BarPreviewScales.qml', "line": 24}, + "bar.persistent": {"control": 'ToggleRow', "page": 'Taskbar', "file": 'shell/modules/nexus/pages/panels/TaskbarPanel.qml', "line": 67}, + "bar.popouts.greeter": {"control": 'ToggleRow', "page": 'Greeter', "file": 'shell/modules/nexus/pages/panels/taskbar/BarGreeter.qml', "line": 126}, + "bar.popouts.statusIcons": {"control": 'ToggleRow', "page": 'Status icons', "file": 'shell/modules/nexus/pages/panels/taskbar/BarStatusIcons.qml', "line": 101}, + "bar.popouts.tray": {"control": 'ToggleRow', "page": 'Tray', "file": 'shell/modules/nexus/pages/panels/taskbar/BarTray.qml', "line": 39}, + "bar.position": {"control": 'SelectRow', "enum": ["top", "bottom", "left", "right"], "page": 'Taskbar', "file": 'shell/modules/nexus/pages/panels/TaskbarPanel.qml', "line": 91}, + "bar.previewFontScales.": {"control": 'DoubleStepperRow (font column)', "min": -1.0, "max": 1.0, "step": 0.05, "page": 'Per-element scaling offsets', "file": 'shell/modules/nexus/pages/panels/taskbar/BarPreviewScales.qml', "line": 93}, + "bar.previewScale": {"control": 'StepperRow', "min": 0.5, "max": 1.6, "step": 0.05, "page": 'Taskbar', "file": 'shell/modules/nexus/pages/panels/TaskbarPanel.qml', "line": 168}, + "bar.previewScaleWithBar": {"control": 'ToggleRow', "page": 'Taskbar', "file": 'shell/modules/nexus/pages/panels/TaskbarPanel.qml', "line": 185}, + "bar.previewScales.audio": {"control": 'DoubleStepperRow', "min": -1.0, "max": 1.0, "step": 0.05, "page": 'Per-element scaling offsets', "file": 'shell/modules/nexus/pages/panels/taskbar/BarPreviewScales.qml', "line": 100}, + "bar.previewScales.battery": {"control": 'DoubleStepperRow', "min": -1.0, "max": 1.0, "step": 0.05, "page": 'Per-element scaling offsets', "file": 'shell/modules/nexus/pages/panels/taskbar/BarPreviewScales.qml', "line": 113}, + "bar.previewScales.bluetooth": {"control": 'DoubleStepperRow', "min": -1.0, "max": 1.0, "step": 0.05, "page": 'Per-element scaling offsets', "file": 'shell/modules/nexus/pages/panels/taskbar/BarPreviewScales.qml', "line": 126}, + "bar.previewScales.dock": {"control": 'DoubleStepperRow', "min": -1.0, "max": 1.0, "step": 0.05, "page": 'Per-element scaling offsets', "file": 'shell/modules/nexus/pages/panels/taskbar/BarPreviewScales.qml', "line": 139}, + "bar.previewScales.github": {"control": 'DoubleStepperRow', "min": -1.0, "max": 1.0, "step": 0.05, "page": 'Per-element scaling offsets', "file": 'shell/modules/nexus/pages/panels/taskbar/BarPreviewScales.qml', "line": 152}, + "bar.previewScales.greeter": {"control": 'DoubleStepperRow', "min": -1.0, "max": 1.0, "step": 0.05, "enum": [" (also writes activeWindow)"], "page": 'Per-element scaling offsets', "file": 'shell/modules/nexus/pages/panels/taskbar/BarPreviewScales.qml', "line": 81}, + "bar.previewScales.lockStatus": {"control": 'DoubleStepperRow', "min": -1.0, "max": 1.0, "step": 0.05, "page": 'Per-element scaling offsets', "file": 'shell/modules/nexus/pages/panels/taskbar/BarPreviewScales.qml', "line": 165}, + "bar.previewScales.network": {"control": 'DoubleStepperRow', "min": -1.0, "max": 1.0, "step": 0.05, "page": 'Per-element scaling offsets', "file": 'shell/modules/nexus/pages/panels/taskbar/BarPreviewScales.qml', "line": 178}, + "bar.previewScales.notifications": {"control": 'DoubleStepperRow', "min": -1.0, "max": 1.0, "step": 0.05, "page": 'Per-element scaling offsets', "file": 'shell/modules/nexus/pages/panels/taskbar/BarPreviewScales.qml', "line": 191}, + "bar.previewScales.peripheralBattery": {"control": 'DoubleStepperRow', "min": -1.0, "max": 1.0, "step": 0.05, "page": 'Per-element scaling offsets', "file": 'shell/modules/nexus/pages/panels/taskbar/BarPreviewScales.qml', "line": 204}, + "bar.previewScales.trayMenu": {"control": 'DoubleStepperRow', "min": -1.0, "max": 1.0, "step": 0.05, "page": 'Per-element scaling offsets', "file": 'shell/modules/nexus/pages/panels/taskbar/BarPreviewScales.qml', "line": 217}, + "bar.previewScales.wirelessPassword": {"control": 'DoubleStepperRow', "min": -1.0, "max": 1.0, "step": 0.05, "page": 'Per-element scaling offsets', "file": 'shell/modules/nexus/pages/panels/taskbar/BarPreviewScales.qml', "line": 230}, + "bar.scale": {"control": 'StepperRow', "min": 0.6, "max": 1.6, "step": 0.05, "page": 'Taskbar', "file": 'shell/modules/nexus/pages/panels/TaskbarPanel.qml', "line": 157}, + "bar.scrollActions.brightness": {"control": 'ToggleRow', "page": 'Taskbar', "file": 'shell/modules/nexus/pages/panels/TaskbarPanel.qml', "line": 249}, + "bar.scrollActions.volume": {"control": 'ToggleRow', "page": 'Taskbar', "file": 'shell/modules/nexus/pages/panels/TaskbarPanel.qml', "line": 242}, + "bar.scrollActions.workspaces": {"control": 'ToggleRow', "page": 'Taskbar', "file": 'shell/modules/nexus/pages/panels/TaskbarPanel.qml', "line": 234}, + "bar.showOnHover": {"control": 'ToggleRow', "page": 'Taskbar', "file": 'shell/modules/nexus/pages/panels/TaskbarPanel.qml', "line": 100}, + "bar.status.showWifi": {"control": 'ToggleRow', "page": 'Status icons', "file": 'shell/modules/nexus/pages/panels/taskbar/BarStatusIcons.qml', "line": 88}, + "bar.statusIcons.values": {"control": 'ListEditor (ordered toggles)', "page": 'Status icons', "file": 'shell/modules/nexus/pages/panels/taskbar/BarStatusIcons.qml', "line": 47}, + "bar.tray.background": {"control": 'ToggleRow', "page": 'Tray', "file": 'shell/modules/nexus/pages/panels/taskbar/BarTray.qml', "line": 20}, + "bar.tray.compact": {"control": 'ToggleRow', "page": 'Tray', "file": 'shell/modules/nexus/pages/panels/taskbar/BarTray.qml', "line": 33}, + "bar.tray.recolour": {"control": 'ToggleRow', "page": 'Tray', "file": 'shell/modules/nexus/pages/panels/taskbar/BarTray.qml', "line": 27}, + "bar.workspaces.activeIndicator": {"control": 'ToggleRow', "page": 'Workspaces indicator', "file": 'shell/modules/nexus/pages/panels/taskbar/BarWorkspaces.qml', "line": 77}, + "bar.workspaces.activeTrail": {"control": 'ToggleRow', "page": 'Workspaces indicator', "file": 'shell/modules/nexus/pages/panels/taskbar/BarWorkspaces.qml', "line": 83}, + "bar.workspaces.displayType": {"control": 'SelectRow', "enum": ["Shapes", "Text (BarWorkspaceDisplay enum)"], "page": 'Workspaces indicator', "file": 'shell/modules/nexus/pages/panels/taskbar/BarWorkspaces.qml', "line": 95}, + "bar.workspaces.maxWindowIcons": {"control": 'StepperRow', "min": 0, "max": 20, "step": 1, "page": 'Workspaces indicator', "file": 'shell/modules/nexus/pages/panels/taskbar/BarWorkspaces.qml', "line": 126}, + "bar.workspaces.occupiedBg": {"control": 'ToggleRow', "page": 'Workspaces indicator', "file": 'shell/modules/nexus/pages/panels/taskbar/BarWorkspaces.qml', "line": 89}, + "bar.workspaces.perMonitor": {"control": 'ToggleRow', "page": 'Workspaces indicator', "file": 'shell/modules/nexus/pages/panels/taskbar/BarWorkspaces.qml', "line": 137}, + "bar.workspaces.showUnoccupied": {"control": 'ToggleRow', "page": 'Workspaces indicator', "file": 'shell/modules/nexus/pages/panels/taskbar/BarWorkspaces.qml', "line": 112}, + "bar.workspaces.showWindows": {"control": 'ToggleRow', "page": 'Workspaces indicator', "file": 'shell/modules/nexus/pages/panels/taskbar/BarWorkspaces.qml', "line": 104}, + "bar.workspaces.showWindowsOnSpecialWorkspaces": {"control": 'ToggleRow', "page": 'Workspaces indicator', "file": 'shell/modules/nexus/pages/panels/taskbar/BarWorkspaces.qml', "line": 120}, + "bar.workspaces.shown": {"control": 'StepperRow', "min": 1, "max": 20, "step": 1, "page": 'Workspaces indicator', "file": 'shell/modules/nexus/pages/panels/taskbar/BarWorkspaces.qml', "line": 53}, + "border.rounding": {"control": 'StepperRow', "min": 0, "max": 100, "step": 1, "page": 'Theme & Effects', "file": 'shell/modules/nexus/pages/wallandstyle/AppearancePage.qml', "line": 336}, + "border.smoothing": {"control": 'StepperRow', "min": 0, "max": 100, "step": 1, "page": 'Theme & Effects', "file": 'shell/modules/nexus/pages/wallandstyle/AppearancePage.qml', "line": 347}, + "border.thickness": {"control": 'StepperRow', "min": 0, "max": 50, "step": 1, "enum": [" (px)"], "page": 'Theme & Effects', "file": 'shell/modules/nexus/pages/wallandstyle/AppearancePage.qml', "line": 108}, + "dashboard.colorizeMediaGif": {"control": 'ToggleRow', "page": 'Dashboard', "file": 'shell/modules/nexus/pages/panels/DashboardPanel.qml', "line": 174}, + "dashboard.dragThreshold": {"control": 'StepperRow', "min": 0, "max": 200, "step": 5, "enum": [" (px)"], "page": 'Dashboard', "file": 'shell/modules/nexus/pages/panels/DashboardPanel.qml', "line": 269}, + "dashboard.enabled": {"control": 'ToggleRow', "page": 'Dashboard', "file": 'shell/modules/nexus/pages/panels/DashboardPanel.qml', "line": 94}, + "dashboard.hoverThickness": {"control": 'StepperRow', "min": 1, "max": 100, "step": 1, "enum": [" (px)"], "page": 'Dashboard', "file": 'shell/modules/nexus/pages/panels/DashboardPanel.qml', "line": 248}, + "dashboard.hoverWidth": {"control": 'StepperRow', "min": 10, "max": 100, "step": 5, "enum": [" (%)"], "page": 'Dashboard', "file": 'shell/modules/nexus/pages/panels/DashboardPanel.qml', "line": 259}, + "dashboard.mediaUpdateInterval": {"control": 'StepperRow', "min": 100, "max": 2000, "step": 50, "enum": [" (ms)"], "page": 'Services', "file": 'shell/modules/nexus/pages/ServicesPage.qml', "line": 89}, + "dashboard.performance.showBattery": {"control": 'ToggleRow', "page": 'Dashboard', "file": 'shell/modules/nexus/pages/panels/DashboardPanel.qml', "line": 205}, + "dashboard.performance.showCpu": {"control": 'ToggleRow', "page": 'Dashboard', "file": 'shell/modules/nexus/pages/panels/DashboardPanel.qml', "line": 218}, + "dashboard.performance.showGpu": {"control": 'ToggleRow', "page": 'Dashboard', "file": 'shell/modules/nexus/pages/panels/DashboardPanel.qml', "line": 212}, + "dashboard.performance.showMemory": {"control": 'ToggleRow', "page": 'Dashboard', "file": 'shell/modules/nexus/pages/panels/DashboardPanel.qml', "line": 224}, + "dashboard.performance.showNetwork": {"control": 'ToggleRow', "page": 'Dashboard', "file": 'shell/modules/nexus/pages/panels/DashboardPanel.qml', "line": 236}, + "dashboard.performance.showStorage": {"control": 'ToggleRow', "page": 'Dashboard', "file": 'shell/modules/nexus/pages/panels/DashboardPanel.qml', "line": 230}, + "dashboard.profilePicShape": {"control": 'SelectRow', "enum": ["-1 Random + Circle", "Square", "Pill", "Diamond", "ClamShell", "Pentagon", "Gem", "Cookie4/6/7/9/12Sided (MaterialShape)"], "page": 'Dashboard', "file": 'shell/modules/nexus/pages/panels/DashboardPanel.qml', "line": 109}, + "dashboard.resourceUpdateInterval": {"control": 'StepperRow', "min": 0.5, "max": 10, "step": 0.5, "enum": [" (seconds; stored in ms)"], "page": 'Services', "file": 'shell/modules/nexus/pages/ServicesPage.qml', "line": 100}, + "dashboard.showClockSeconds": {"control": 'ToggleRow', "page": 'Dashboard', "file": 'shell/modules/nexus/pages/panels/DashboardPanel.qml', "line": 128}, + "dashboard.showDashboard": {"control": 'ToggleRow', "page": 'Dashboard', "file": 'shell/modules/nexus/pages/panels/DashboardPanel.qml', "line": 141}, + "dashboard.showMedia": {"control": 'ToggleRow', "page": 'Dashboard', "file": 'shell/modules/nexus/pages/panels/DashboardPanel.qml', "line": 148}, + "dashboard.showOnHover": {"control": 'ToggleRow', "page": 'Dashboard', "file": 'shell/modules/nexus/pages/panels/DashboardPanel.qml', "line": 101}, + "dashboard.showPerformance": {"control": 'ToggleRow', "page": 'Dashboard', "file": 'shell/modules/nexus/pages/panels/DashboardPanel.qml', "line": 154}, + "dashboard.showTerminal": {"control": 'ToggleRow', "page": 'Dashboard', "file": 'shell/modules/nexus/pages/panels/DashboardPanel.qml', "line": 167}, + "dashboard.showWeather": {"control": 'ToggleRow', "page": 'Dashboard', "file": 'shell/modules/nexus/pages/panels/DashboardPanel.qml', "line": 160}, + "dashboard.useMediaShapes": {"control": 'ToggleRow', "page": 'Dashboard', "file": 'shell/modules/nexus/pages/panels/DashboardPanel.qml', "line": 182}, + "general.apps.explorer (list append)": {"control": 'TextFieldRow/other (file-explorer pinning)', "page": 'Updates', "file": 'shell/modules/nexus/pages/UpdatesPage.qml', "line": 733}, + "general.battery.criticalLevel": {"control": 'StepperRow', "min": 1, "max": 50, "step": 1, "enum": [" (%)"], "page": 'Power', "file": 'shell/modules/nexus/pages/PowerPage.qml', "line": 128}, + "general.checkUpdates": {"control": 'ToggleRow', "page": 'Update indicator', "file": 'shell/modules/nexus/pages/panels/taskbar/BarUpdates.qml', "line": 44}, + "general.idle.inhibitWhenAudio": {"control": 'ToggleRow', "page": 'Power', "file": 'shell/modules/nexus/pages/PowerPage.qml', "line": 109}, + "general.idle.inhibitWhenCharging": {"control": 'ToggleRow', "page": 'Power', "file": 'shell/modules/nexus/pages/PowerPage.qml', "line": 116}, + "general.idle.lockBeforeSleep": {"control": 'ToggleRow', "page": 'Power', "file": 'shell/modules/nexus/pages/PowerPage.qml', "line": 102}, + "general.idle.timeouts (suspend entry enabled)": {"control": 'ToggleRow (writes entry.enabled / inserts entry)', "page": 'Power', "file": 'shell/modules/nexus/pages/PowerPage.qml', "line": 78}, + "general.idle.timeouts (suspend timeout minutes)": {"control": 'StepperRow', "min": 1, "max": 180, "step": 1, "enum": [" (minutes; sanitized Math.max(1, Math.min(180)); stored in seconds)"], "page": 'Power', "file": 'shell/modules/nexus/pages/PowerPage.qml', "line": 86}, + "general.krohnkiteEnabled": {"control": 'ToggleRow (also installs/unloads Krohnkite kwin script)', "page": 'Window Tiling', "file": 'shell/modules/nexus/pages/desktop/KrohnkitePage.qml', "line": 75}, + "general.krohnkiteLastLayout": {"control": 'SelectRow', "enum": ["BTree", "Monocle", "Floating", "Quarter", "Spread", "Stacked", "Stair", "Columns", "ThreeColumn", "Spiral", "Tile"], "page": 'Window Tiling', "file": 'shell/modules/nexus/pages/desktop/KrohnkitePage.qml', "line": 115}, + "general.language": {"control": 'SelectRow', "enum": ["system + installed translation catalogues"], "page": 'Language & region', "file": 'shell/modules/nexus/pages/LanguageAndRegion.qml', "line": 132}, + "general.logo": {"control": 'ToggleRow (on when != ""; writes "" or "caelestia")', "page": 'Launcher', "file": 'shell/modules/nexus/pages/panels/LauncherPanel.qml', "line": 37}, + "general.magicLampEnabled": {"control": 'ToggleRow (also writes kwinrc magiclampEnabled/squashEnabled)', "page": 'Desktop & Tiling', "file": 'shell/modules/nexus/pages/DesktopPage.qml', "line": 91}, + "launcher.clipboardMaxEntries": {"control": 'StepperRow', "min": 1, "max": 100, "step": 1, "page": 'Launcher', "file": 'shell/modules/nexus/pages/panels/LauncherPanel.qml', "line": 193}, + "launcher.clipboardMaxEntries (utilities view)": {"control": 'StepperRow', "min": 1, "max": 2048, "step": 10, "page": 'Clipboard', "file": 'shell/modules/nexus/pages/utilities/ClipboardPage.qml', "line": 23}, + "launcher.confirmClearClipboard": {"control": 'ToggleRow', "page": 'Launcher', "file": 'shell/modules/nexus/pages/panels/LauncherPanel.qml', "line": 204}, + "launcher.dragThreshold": {"control": 'StepperRow', "min": 0, "max": 200, "step": 5, "enum": [" (px)"], "page": 'Launcher', "file": 'shell/modules/nexus/pages/panels/LauncherPanel.qml', "line": 177}, + "launcher.enableDangerousActions": {"control": 'ToggleRow', "page": 'Launcher', "file": 'shell/modules/nexus/pages/panels/LauncherPanel.qml', "line": 225}, + "launcher.enabled": {"control": 'ToggleRow', "page": 'Launcher', "file": 'shell/modules/nexus/pages/panels/LauncherPanel.qml', "line": 30}, + "launcher.hoverThickness": {"control": 'StepperRow', "min": 1, "max": 100, "step": 1, "enum": [" (px)"], "page": 'Launcher', "file": 'shell/modules/nexus/pages/panels/LauncherPanel.qml', "line": 157}, + "launcher.hoverWidth": {"control": 'StepperRow', "min": 10, "max": 100, "step": 5, "enum": [" (% of edge)"], "page": 'Launcher', "file": 'shell/modules/nexus/pages/panels/LauncherPanel.qml', "line": 167}, + "launcher.maxShown": {"control": 'StepperRow', "min": 1, "max": 20, "step": 1, "page": 'Launcher', "file": 'shell/modules/nexus/pages/panels/LauncherPanel.qml', "line": 139}, + "launcher.maxWallpapers": {"control": 'StepperRow', "min": 1, "max": 30, "step": 1, "page": 'Launcher', "file": 'shell/modules/nexus/pages/panels/LauncherPanel.qml', "line": 148}, + "launcher.showBrowseOnEmpty": {"control": 'ToggleRow', "page": 'Launcher', "file": 'shell/modules/nexus/pages/panels/LauncherPanel.qml', "line": 124}, + "launcher.showOnHover": {"control": 'ToggleRow', "page": 'Launcher', "file": 'shell/modules/nexus/pages/panels/LauncherPanel.qml', "line": 111}, + "launcher.showPowerMenu": {"control": 'ToggleRow', "page": 'Launcher', "file": 'shell/modules/nexus/pages/panels/LauncherPanel.qml', "line": 132}, + "launcher.useFuzzy.actions": {"control": 'ToggleRow', "page": 'Launcher', "file": 'shell/modules/nexus/pages/panels/LauncherPanel.qml', "line": 245}, + "launcher.useFuzzy.apps": {"control": 'ToggleRow', "page": 'Launcher', "file": 'shell/modules/nexus/pages/panels/LauncherPanel.qml', "line": 238}, + "launcher.useFuzzy.schemes": {"control": 'ToggleRow', "page": 'Launcher', "file": 'shell/modules/nexus/pages/panels/LauncherPanel.qml', "line": 251}, + "launcher.useFuzzy.variants": {"control": 'ToggleRow', "page": 'Launcher', "file": 'shell/modules/nexus/pages/panels/LauncherPanel.qml', "line": 257}, + "launcher.useFuzzy.wallpapers": {"control": 'ToggleRow', "page": 'Launcher', "file": 'shell/modules/nexus/pages/panels/LauncherPanel.qml', "line": 263}, + "launcher.vimKeybinds": {"control": 'ToggleRow', "page": 'Launcher', "file": 'shell/modules/nexus/pages/panels/LauncherPanel.qml', "line": 217}, + "lock.blurWallpaper": {"control": 'ToggleRow', "page": 'Lock Screen', "file": 'shell/modules/nexus/pages/wallandstyle/LockScreenPage.qml', "line": 184}, + "lock.enableFprint": {"control": 'ToggleRow', "page": 'Lock Screen', "file": 'shell/modules/nexus/pages/wallandstyle/LockScreenPage.qml', "line": 201}, + "lock.hideNotifs": {"control": 'ToggleRow', "page": 'Lock Screen', "file": 'shell/modules/nexus/pages/wallandstyle/LockScreenPage.qml', "line": 280}, + "lock.lockOnStartup": {"control": 'ToggleRow', "page": 'Lock Screen', "file": 'shell/modules/nexus/pages/wallandstyle/LockScreenPage.qml', "line": 269}, + "lock.maxFprintTries": {"control": 'SelectRow', "enum": ["1", "2", "3", "4", "5 attempts"], "page": 'Lock Screen', "file": 'shell/modules/nexus/pages/wallandstyle/LockScreenPage.qml', "line": 213}, + "lock.profilePicShape": {"control": 'SelectRow', "enum": ["-1 Random + Circle", "Square", "Pill", "Diamond", "ClamShell", "Pentagon", "Gem", "Cookie4/6/7/9/12Sided (MaterialShape)"], "page": 'Lock Screen', "file": 'shell/modules/nexus/pages/wallandstyle/LockScreenPage.qml', "line": 237}, + "lock.recolourLogo": {"control": 'ToggleRow', "page": 'Lock Screen', "file": 'shell/modules/nexus/pages/wallandstyle/LockScreenPage.qml', "line": 291}, + "lock.rotateProfilePic": {"control": 'ToggleRow', "page": 'Lock Screen', "file": 'shell/modules/nexus/pages/wallandstyle/LockScreenPage.qml', "line": 258}, + "lock.showHibernate": {"control": 'ToggleRow', "page": 'Lock Screen', "file": 'shell/modules/nexus/pages/wallandstyle/LockScreenPage.qml', "line": 320}, + "lock.showLogout": {"control": 'ToggleRow', "page": 'Lock Screen', "file": 'shell/modules/nexus/pages/wallandstyle/LockScreenPage.qml', "line": 342}, + "lock.showReboot": {"control": 'ToggleRow', "page": 'Lock Screen', "file": 'shell/modules/nexus/pages/wallandstyle/LockScreenPage.qml', "line": 353}, + "lock.showShutdown": {"control": 'ToggleRow', "page": 'Lock Screen', "file": 'shell/modules/nexus/pages/wallandstyle/LockScreenPage.qml', "line": 364}, + "lock.showSleep": {"control": 'ToggleRow', "page": 'Lock Screen', "file": 'shell/modules/nexus/pages/wallandstyle/LockScreenPage.qml', "line": 308}, + "lock.showSwitchUser": {"control": 'ToggleRow', "page": 'Lock Screen', "file": 'shell/modules/nexus/pages/wallandstyle/LockScreenPage.qml', "line": 331}, + "lock.syncWallpaper": {"control": 'ToggleRow', "page": 'Lock Screen', "file": 'shell/modules/nexus/pages/wallandstyle/LockScreenPage.qml', "line": 147}, + "nexus.networkRescanInterval": {"control": 'StepperRow', "min": 5, "max": 120, "step": 5, "enum": [" (seconds; stored in ms)"], "page": 'Services', "file": 'shell/modules/nexus/pages/ServicesPage.qml', "line": 110}, + "nexus.wallpapersPerRow": {"control": '(no control; read-only Repeater model)', "page": 'Wallpapers', "file": 'shell/modules/nexus/pages/wallandstyle/WallpaperSelect.qml', "line": 80}, + "notifs.actionOnClick": {"control": 'ToggleRow', "page": 'Notifications', "file": 'shell/modules/nexus/pages/services/NotificationPreferencesPage.qml', "line": 162}, + "notifs.clearThreshold": {"control": 'SliderRow', "min": 0, "max": 1, "note": 'step: wheel=services.audioIncrement (swipe fraction)', "page": 'Notifications', "file": 'shell/modules/nexus/pages/services/NotificationPreferencesPage.qml', "line": 190}, + "notifs.defaultExpireTimeout": {"control": 'StepperRow', "min": 1, "max": 60, "step": 1, "enum": [" (seconds; stored in ms)"], "page": 'Notifications', "file": 'shell/modules/nexus/pages/services/NotificationPreferencesPage.qml', "line": 117}, + "notifs.expandThreshold": {"control": 'StepperRow', "min": 5, "max": 100, "step": 5, "enum": [" (px)"], "page": 'Notifications', "file": 'shell/modules/nexus/pages/services/NotificationPreferencesPage.qml', "line": 170}, + "notifs.expire": {"control": 'ToggleRow', "page": 'Notifications', "file": 'shell/modules/nexus/pages/services/NotificationPreferencesPage.qml', "line": 103}, + "notifs.fullscreen": {"control": 'SelectRow', "enum": ["off", "on"], "page": 'Notifications', "file": 'shell/modules/nexus/pages/services/NotificationPreferencesPage.qml', "line": 78}, + "notifs.fullscreenExpireTimeout": {"control": 'StepperRow', "min": 1, "max": 30, "step": 1, "enum": [" (seconds; stored in ms)"], "page": 'Notifications', "file": 'shell/modules/nexus/pages/services/NotificationPreferencesPage.qml', "line": 180}, + "notifs.groupPreviewNum": {"control": 'StepperRow', "min": 1, "max": 10, "step": 1, "page": 'Notifications', "file": 'shell/modules/nexus/pages/services/NotificationPreferencesPage.qml', "line": 127}, + "notifs.maxNotifs": {"control": 'StepperRow', "min": 20, "max": 2000, "step": 50, "page": 'Notifications', "file": 'shell/modules/nexus/pages/services/NotificationPreferencesPage.qml', "line": 147}, + "notifs.maxPopups": {"control": 'StepperRow', "min": 0, "max": 30, "step": 1, "page": 'Notifications', "file": 'shell/modules/nexus/pages/services/NotificationPreferencesPage.qml', "line": 137}, + "notifs.monitor": {"control": 'SelectRow', "enum": ["all", "focused"], "page": 'Notifications', "file": 'shell/modules/nexus/pages/services/NotificationPreferencesPage.qml', "line": 87}, + "notifs.openExpanded": {"control": 'ToggleRow', "page": 'Notifications', "file": 'shell/modules/nexus/pages/services/NotificationPreferencesPage.qml', "line": 110}, + "notifs.position": {"control": 'SelectRow', "enum": ["auto", "top-left", "top-center", "top-right", "bottom-left", "bottom-center", "bottom-right"], "page": 'Notifications', "file": 'shell/modules/nexus/pages/services/NotificationPreferencesPage.qml', "line": 95}, + "osd.enableBrightness": {"control": 'ToggleRow', "page": 'On-screen sliders', "file": 'shell/modules/nexus/pages/utilities/OsdPage.qml', "line": 45}, + "osd.enableMicrophone": {"control": 'ToggleRow', "page": 'On-screen sliders', "file": 'shell/modules/nexus/pages/utilities/OsdPage.qml', "line": 38}, + "osd.enableVolume": {"control": 'ToggleRow', "page": 'On-screen sliders', "file": 'shell/modules/nexus/pages/utilities/OsdPage.qml', "line": 31}, + "osd.enabled": {"control": 'ToggleRow', "page": 'On-screen sliders', "file": 'shell/modules/nexus/pages/utilities/OsdPage.qml', "line": 23}, + "osd.hideDelay": {"control": 'StepperRow', "min": 1, "max": 10, "step": 1, "enum": [" (seconds; stored in ms)"], "page": 'On-screen sliders', "file": 'shell/modules/nexus/pages/utilities/OsdPage.qml', "line": 83}, + "osd.hoverThickness": {"control": 'StepperRow', "min": 1, "max": 100, "step": 1, "enum": [" (px)"], "page": 'On-screen sliders', "file": 'shell/modules/nexus/pages/utilities/OsdPage.qml', "line": 57}, + "osd.hoverWidth": {"control": 'StepperRow', "min": 10, "max": 100, "step": 5, "enum": [" (%)"], "page": 'On-screen sliders', "file": 'shell/modules/nexus/pages/utilities/OsdPage.qml', "line": 68}, + "overview.baseDuration": {"control": 'StepperRow', "min": 100, "max": 1000, "step": 50, "enum": [" (ms)"], "page": 'Overview', "file": 'shell/modules/nexus/pages/panels/OverviewPanel.qml', "line": 225}, + "overview.blobScaleSpeed": {"control": 'StepperRow', "min": 0.1, "max": 5.0, "step": 0.1, "page": 'Overview', "file": 'shell/modules/nexus/pages/panels/OverviewPanel.qml', "line": 234}, + "overview.disableWallpaperBlur": {"control": 'ToggleRow', "page": 'Overview', "file": 'shell/modules/nexus/pages/panels/OverviewPanel.qml', "line": 191}, + "overview.dragThreshold": {"control": 'StepperRow', "min": 10, "max": 200, "step": 5, "enum": [" (visible only when !showOnHover)"], "page": 'Overview', "file": 'shell/modules/nexus/pages/panels/OverviewPanel.qml', "line": 131}, + "overview.easingType": {"control": 'SelectRow', "enum": ["0 Linear", "2 QuadraticOut", "3 QuadraticInOut", "6 CubicOut", "10 QuarticOut", "14 QuinticOut", "18 SineOut", "22 ExponentialOut", "26 CircularOut", "30 ElasticOut", "33 BackIn", "34 BackOut", "38 BounceOut"], "page": 'Overview', "file": 'shell/modules/nexus/pages/panels/OverviewPanel.qml', "line": 207}, + "overview.enableOverviewBlur": {"control": 'ToggleRow', "page": 'Overview', "file": 'shell/modules/nexus/pages/panels/OverviewPanel.qml', "line": 197}, + "overview.enabled": {"control": 'ToggleRow', "page": 'Overview', "file": 'shell/modules/nexus/pages/panels/OverviewPanel.qml', "line": 108}, + "overview.gridFadeSpeed": {"control": 'StepperRow', "min": 0.1, "max": 5.0, "step": 0.1, "page": 'Overview', "file": 'shell/modules/nexus/pages/panels/OverviewPanel.qml', "line": 252}, + "overview.hoverBottomLeft": {"control": 'ToggleRow', "page": 'Overview', "file": 'shell/modules/nexus/pages/panels/OverviewPanel.qml', "line": 159}, + "overview.hoverBottomRight": {"control": 'ToggleRow', "page": 'Overview', "file": 'shell/modules/nexus/pages/panels/OverviewPanel.qml', "line": 164}, + "overview.hoverThickness": {"control": 'StepperRow', "min": 1, "max": 100, "step": 1, "enum": [" (visible only when showOnHover)"], "page": 'Overview', "file": 'shell/modules/nexus/pages/panels/OverviewPanel.qml', "line": 120}, + "overview.hoverTopLeft": {"control": 'ToggleRow', "page": 'Overview', "file": 'shell/modules/nexus/pages/panels/OverviewPanel.qml', "line": 148}, + "overview.hoverTopRight": {"control": 'ToggleRow', "page": 'Overview', "file": 'shell/modules/nexus/pages/panels/OverviewPanel.qml', "line": 154}, + "overview.layoutType": {"control": 'SelectRow', "enum": ["0=KDE Grid", "1=GNOME Grid"], "page": 'Overview', "file": 'shell/modules/nexus/pages/panels/OverviewPanel.qml', "line": 173}, + "overview.showOnHover": {"control": 'ToggleRow', "page": 'Overview', "file": 'shell/modules/nexus/pages/panels/OverviewPanel.qml', "line": 114}, + "overview.wallpaperFadeSpeed": {"control": 'StepperRow', "min": 0.1, "max": 5.0, "step": 0.1, "page": 'Overview', "file": 'shell/modules/nexus/pages/panels/OverviewPanel.qml', "line": 243}, + "services.arpcCaelestiaInfo": {"control": 'ToggleRow', "page": 'Discord Rich Presence', "file": 'shell/modules/nexus/pages/services/ArpcPage.qml', "line": 74}, + "services.arpcEnabled": {"control": 'ToggleRow', "page": 'Discord Rich Presence', "file": 'shell/modules/nexus/pages/services/ArpcPage.qml', "line": 56}, + "services.arpcIdleTimeout": {"control": 'StepperRow', "min": 0, "max": 60, "step": 1, "enum": [" (minutes; stored in seconds)"], "page": 'Discord Rich Presence', "file": 'shell/modules/nexus/pages/services/ArpcPage.qml', "line": 83}, + "services.arpcManualOverride": {"control": 'ToggleRow', "page": 'Discord Rich Presence', "file": 'shell/modules/nexus/pages/services/ArpcPage.qml', "line": 439}, + "services.arpcSteamAutoDetect": {"control": 'ToggleRow', "page": 'Discord Rich Presence', "file": 'shell/modules/nexus/pages/services/ArpcPage.qml', "line": 65}, + "services.audioIncrement": {"control": 'StepperRow', "min": 1, "max": 50, "step": 1, "enum": [" (% shown; stored as fraction v/100)"], "page": 'Services', "file": 'shell/modules/nexus/pages/ServicesPage.qml', "line": 151}, + "services.autoSchemeDarkTime": {"control": 'StepperRow (visible: autoSchemeEnabled && mode=="fixed")', "min": 0, "max": 23, "note": 'step: (hour; stored as "HH:MM" string)', "page": 'Advanced colors', "file": 'shell/modules/nexus/pages/wallandstyle/AdvancedColorsPage.qml', "line": 120}, + "services.autoSchemeEnabled": {"control": 'ToggleRow ("Automatic light and dark")', "page": 'Advanced colors', "file": 'shell/modules/nexus/pages/wallandstyle/AdvancedColorsPage.qml', "line": 89}, + "services.autoSchemeLightTime": {"control": 'StepperRow (visible: autoSchemeEnabled && mode=="fixed")', "min": 0, "max": 23, "note": 'step: (hour; stored as "HH:MM" string)', "page": 'Advanced colors', "file": 'shell/modules/nexus/pages/wallandstyle/AdvancedColorsPage.qml', "line": 109}, + "services.autoSchemeMode": {"control": 'SelectRow (visible: autoSchemeEnabled)', "enum": ["solar", "fixed"], "page": 'Advanced colors', "file": 'shell/modules/nexus/pages/wallandstyle/AdvancedColorsPage.qml', "line": 98}, + "services.brightnessIncrement": {"control": 'StepperRow', "min": 1, "max": 50, "step": 1, "enum": [" (% shown; stored as fraction v/100)"], "page": 'Services', "file": 'shell/modules/nexus/pages/ServicesPage.qml', "line": 162}, + "services.clockFormat": {"control": 'SelectRow', "enum": ["Auto", "12-hour", "24-hour (ClockFormat enum)"], "page": 'Language & region', "file": 'shell/modules/nexus/pages/LanguageAndRegion.qml', "line": 419}, + "services.dataUnits": {"control": 'SelectRow', "enum": ["Binary (KiB MiB)", "Decimal (KB MB) (DataUnit enum)"], "page": 'Language & region', "file": 'shell/modules/nexus/pages/LanguageAndRegion.qml', "line": 405}, + "services.defaultPlayer": {"control": 'SelectRow', "enum": ["(dynamic list of running players + Auto)"], "page": 'Services', "file": 'shell/modules/nexus/pages/ServicesPage.qml', "line": 135}, + "services.gpuType": {"control": 'SelectRow', "enum": ["(dynamic gpuValues list)"], "page": 'Services', "file": 'shell/modules/nexus/pages/ServicesPage.qml', "line": 206}, + "services.maxVolume": {"control": 'StepperRow', "min": 50, "max": 200, "step": 5, "enum": [" (% shown; stored as fraction v/100)"], "page": 'Services', "file": 'shell/modules/nexus/pages/ServicesPage.qml', "line": 172}, + "services.sensorUnits": {"control": 'SelectRow', "enum": ["Auto", "Celsius", "Fahrenheit", "Kelvin (TemperatureUnit enum)"], "page": 'Language & region', "file": 'shell/modules/nexus/pages/LanguageAndRegion.qml', "line": 397}, + "services.smartScheme": {"control": 'ToggleRow ("Smart color scheme")', "page": 'Advanced colors', "file": 'shell/modules/nexus/pages/wallandstyle/AdvancedColorsPage.qml', "line": 81}, + "services.visualiserBars": {"control": 'StepperRow', "min": 10, "max": 120, "step": 2, "page": 'Services', "file": 'shell/modules/nexus/pages/ServicesPage.qml', "line": 196}, + "services.weatherUnits": {"control": 'SelectRow', "enum": ["Auto", "Celsius", "Fahrenheit", "Kelvin (TemperatureUnit enum)"], "page": 'Language & region', "file": 'shell/modules/nexus/pages/LanguageAndRegion.qml', "line": 388}, + "session.commands.{logout,shutdown,hibernate,reboot}": {"control": 'LabeledField (free text command string; stored as list)', "page": 'Session', "file": 'shell/modules/nexus/pages/SessionPage.qml', "line": 100}, + "session.dragThreshold": {"control": 'StepperRow', "min": 10, "max": 200, "step": 5, "enum": [" (px)"], "page": 'Session', "file": 'shell/modules/nexus/pages/SessionPage.qml', "line": 53}, + "session.enabled": {"control": 'ToggleRow', "page": 'Session', "file": 'shell/modules/nexus/pages/SessionPage.qml', "line": 36}, + "session.icons.{logout,shutdown,hibernate,reboot}": {"control": 'LabeledField (free text Material icon name)', "page": 'Session', "file": 'shell/modules/nexus/pages/SessionPage.qml', "line": 69}, + "session.vimKeybinds": {"control": 'ToggleRow', "page": 'Session', "file": 'shell/modules/nexus/pages/SessionPage.qml', "line": 45}, + "sidebar.dragThreshold": {"control": 'StepperRow', "min": 0, "max": 200, "step": 5, "enum": [" (px)"], "page": 'Sidebar', "file": 'shell/modules/nexus/pages/panels/SidebarPanel.qml', "line": 36}, + "sidebar.enabled": {"control": 'ToggleRow', "page": 'Sidebar', "file": 'shell/modules/nexus/pages/panels/SidebarPanel.qml', "line": 29}, + "sidebar.grabWidth": {"control": 'StepperRow', "min": 1, "max": 100, "step": 1, "enum": [" (px)"], "page": 'Sidebar', "file": 'shell/modules/nexus/pages/panels/SidebarPanel.qml', "line": 48}, + "tabSwitch.allScreens": {"control": 'ToggleRow (also writes kwinrc TabBox MultiScreenMode)', "page": 'Window Switcher', "file": 'shell/modules/nexus/pages/panels/TabSwitcherPanel.qml', "line": 164}, + "tabSwitch.currentDesktopOnly": {"control": 'ToggleRow (also writes kwinrc TabBox DesktopMode)', "page": 'Window Switcher', "file": 'shell/modules/nexus/pages/panels/TabSwitcherPanel.qml', "line": 114}, + "tabSwitch.enabled": {"control": 'ToggleRow', "page": 'Window Switcher', "file": 'shell/modules/nexus/pages/panels/TabSwitcherPanel.qml', "line": 72}, + "tabSwitch.previewOnDesktop": {"control": 'ToggleRow (also writes kwinrc TabBox HighlightWindows)', "page": 'Window Switcher', "file": 'shell/modules/nexus/pages/panels/TabSwitcherPanel.qml', "line": 129}, + "tabSwitch.showMinimized": {"control": 'ToggleRow (also writes kwinrc TabBox MinMode)', "page": 'Window Switcher', "file": 'shell/modules/nexus/pages/panels/TabSwitcherPanel.qml', "line": 149}, + "utilities.dragThreshold": {"control": 'StepperRow', "min": 0, "max": 200, "step": 5, "enum": [" (px)"], "page": 'Quick toggle (panel)', "file": 'shell/modules/nexus/pages/panels/UtilitiesPanel.qml', "line": 68}, + "utilities.enabled": {"control": 'ToggleRow', "page": 'Quick toggle (panel)', "file": 'shell/modules/nexus/pages/panels/UtilitiesPanel.qml', "line": 29}, + "utilities.gameMode.autoEnable": {"control": 'ToggleRow', "page": 'Game mode', "file": 'shell/modules/nexus/pages/services/GameModePage.qml', "line": 35}, + "utilities.gameMode.disableDesktopLyrics": {"control": 'ToggleRow', "page": 'Game mode', "file": 'shell/modules/nexus/pages/services/GameModePage.qml', "line": 109}, + "utilities.gameMode.disableHyprlandAnimations": {"control": 'ToggleRow (visible only on Hyprland)', "page": 'Game mode', "file": 'shell/modules/nexus/pages/services/GameModePage.qml', "line": 60}, + "utilities.gameMode.disableHyprlandBlur": {"control": 'ToggleRow (visible only on Hyprland)', "page": 'Game mode', "file": 'shell/modules/nexus/pages/services/GameModePage.qml', "line": 67}, + "utilities.gameMode.disableHyprlandGaps": {"control": 'ToggleRow (visible only on Hyprland)', "page": 'Game mode', "file": 'shell/modules/nexus/pages/services/GameModePage.qml', "line": 73}, + "utilities.gameMode.disableHyprlandShadows": {"control": 'ToggleRow (visible only on Hyprland)', "page": 'Game mode', "file": 'shell/modules/nexus/pages/services/GameModePage.qml', "line": 79}, + "utilities.gameMode.disableShellTransparency": {"control": 'ToggleRow', "page": 'Game mode', "file": 'shell/modules/nexus/pages/services/GameModePage.qml', "line": 98}, + "utilities.gameMode.disableToastTransparency": {"control": 'ToggleRow', "page": 'Game mode', "file": 'shell/modules/nexus/pages/services/GameModePage.qml', "line": 104}, + "utilities.gameMode.disableVisualizer": {"control": 'ToggleRow', "page": 'Game mode', "file": 'shell/modules/nexus/pages/services/GameModePage.qml', "line": 114}, + "utilities.gameMode.disableWindowTransparency": {"control": 'ToggleRow (visible only on Hyprland)', "page": 'Game mode', "file": 'shell/modules/nexus/pages/services/GameModePage.qml', "line": 85}, + "utilities.hoverThickness": {"control": 'StepperRow', "min": 1, "max": 100, "step": 1, "enum": [" (px)"], "page": 'Quick toggle (panel)', "file": 'shell/modules/nexus/pages/panels/UtilitiesPanel.qml', "line": 44}, + "utilities.hoverWidth": {"control": 'StepperRow', "min": 10, "max": 100, "step": 5, "enum": [" (%)"], "page": 'Quick toggle (panel)', "file": 'shell/modules/nexus/pages/panels/UtilitiesPanel.qml', "line": 56}, + "utilities.maxToasts": {"control": 'StepperRow', "min": 1, "max": 10, "step": 1, "page": 'Toasts', "file": 'shell/modules/nexus/pages/services/ToastPreferencesPage.qml', "line": 50}, + "utilities.quickToggles[id].enabled": {"control": 'ToggleRow (per id: wifi|bluetooth|vpn|settings|colorpicker|wallpaper|badapple|mic|dnd|gameMode|pauseWallpaper|nightlight|easyeffects|restartShell)', "page": 'Quick toggles', "file": 'shell/modules/nexus/pages/utilities/QuickTogglesPage.qml', "line": 89}, + "utilities.showGifRecorder": {"control": 'ToggleRow', "page": 'Utilities panel', "file": 'shell/modules/nexus/pages/utilities/UtilitiesPanelPage.qml', "line": 38}, + "utilities.showKeepAwake": {"control": 'ToggleRow', "page": 'Utilities panel', "file": 'shell/modules/nexus/pages/utilities/UtilitiesPanelPage.qml', "line": 23}, + "utilities.showOnHover": {"control": 'ToggleRow', "page": 'Quick toggle (panel)', "file": 'shell/modules/nexus/pages/panels/UtilitiesPanel.qml', "line": 36}, + "utilities.showQuickToggles": {"control": 'ToggleRow', "page": 'Utilities panel', "file": 'shell/modules/nexus/pages/utilities/UtilitiesPanelPage.qml', "line": 45}, + "utilities.showScreenRecorder": {"control": 'ToggleRow', "page": 'Utilities panel', "file": 'shell/modules/nexus/pages/utilities/UtilitiesPanelPage.qml', "line": 31}, + "utilities.toasts.chargingChanged": {"control": 'ToggleRow', "page": 'Toast events', "file": 'shell/modules/nexus/pages/services/ToastEventsPage.qml', "line": 26}, + "utilities.toasts.configLoaded": {"control": 'ToggleRow', "page": 'Toast events', "file": 'shell/modules/nexus/pages/services/ToastEventsPage.qml', "line": 45}, + "utilities.toasts.fullscreen": {"control": 'SelectRow', "enum": ["off", "important", "all"], "page": 'Toasts', "file": 'shell/modules/nexus/pages/services/ToastPreferencesPage.qml', "line": 41}, + "utilities.toasts.gameModeChanged": {"control": 'ToggleRow', "page": 'Toast events', "file": 'shell/modules/nexus/pages/services/ToastEventsPage.qml', "line": 32}, + "utilities.toasts.nightLightChanged": {"control": 'ToggleRow', "page": 'Toast events', "file": 'shell/modules/nexus/pages/services/ToastEventsPage.qml', "line": 38}, + "utilities.toasts.transparency": {"control": 'ToggleRow', "page": 'Toasts', "file": 'shell/modules/nexus/pages/services/ToastPreferencesPage.qml', "line": 60}, + "utilities.toasts.transparencyBase": {"control": 'SliderRow', "min": 0, "max": 1, "note": 'step: wheel=services.audioIncrement (enabled: toasts.transparency)', "page": 'Toasts', "file": 'shell/modules/nexus/pages/services/ToastPreferencesPage.qml', "line": 67}, +} diff --git a/plugins/caelestia-assistant/assistant/capabilities/settings/wizard.py b/plugins/caelestia-assistant/assistant/capabilities/settings/wizard.py new file mode 100644 index 0000000..ccb1b71 --- /dev/null +++ b/plugins/caelestia-assistant/assistant/capabilities/settings/wizard.py @@ -0,0 +1,193 @@ +"""First-run setup wizard (issue #120 Phase 3 roadmap: "setup wizards"). + +A handful of pairwise tradeoff questions over FOUR criteria — visual +fidelity, battery, minimalism, performance — are turned into AHP weights +(genius/decision.py::ahp, Saaty's pairwise method with the consistency +ratio), and the five shipped presets are scored against those criteria +with TOPSIS (genius/decision.py::topsis) to recommend a starting preset. + +Everything reuses code that already exists and is already tested: + +- the criterion scores come from `optimize.score_plan(profile, ops)` — + the same scored objective profiles the #120 phase-3 optimizer ships; + the four wizard criteria map onto them directly: + visual fidelity -> comfort, battery -> battery, + minimalism -> minimal, performance -> gaming; +- the preset candidates are the registry's own five preset bundles + (compact, minimal, gaming, battery-saver, macos-like) through + presets.preset_ops — the same validated bundles the --preset flag + applies; + +and nothing here writes: the recommendation is returned (and rendered) +with its bundled ops for the caller to apply through the EXISTING +--preset/--apply/--confirm gates or the ledger. A recommendation the +user ignores costs nothing. + +Note on question count: four criteria give C(4,2) = 6 pairwise questions. +decision.ahp validates full-matrix reciprocity, so a spanning subset of +questions would need invented cells; six is the honest minimum. The +answer scale is deliberately coarse (5 options per question) so the +wizard stays a few seconds long. +""" + +from __future__ import annotations + +from typing import Any, Dict, List, Optional, Sequence + +from assistant.capabilities.genius import decision +from .optimize import score_plan +from .presets import PresetError, preset_ops, presets + +CRITERIA = ("visual fidelity", "battery", "minimalism", "performance") +_CRITERION_PROFILE = { + "visual fidelity": "comfort", + "battery": "battery", + "minimalism": "minimal", + "performance": "gaming", +} + +# The six criterion pairs, in fixed question order: (first, second). +QUESTION_PAIRS = ( + ("visual fidelity", "battery"), + ("visual fidelity", "performance"), + ("visual fidelity", "minimalism"), + ("battery", "performance"), + ("battery", "minimalism"), + ("performance", "minimalism"), +) + +# Answer 1..5 maps to the Saaty intensity for the FIRST criterion over the +# second: strongly (5), moderately (3), equally (1), and the reciprocals. +ANSWER_SCALE = { + 1: 5.0, # first strongly more important + 2: 3.0, # first moderately more important + 3: 1.0, # equally important + 4: 1.0 / 3.0, # second moderately more important + 5: 1.0 / 5.0, # second strongly more important +} + +ANSWER_HINTS = ( + "1 = first strongly, 2 = first moderately, 3 = equally, " + "4 = second moderately, 5 = second strongly", +) + + +def question_lines() -> List[str]: + """The exact questions, for the CLI to render verbatim.""" + lines = [f"Which matters more, and how strongly? ({ANSWER_HINTS[0]})"] + for i, (a, b) in enumerate(QUESTION_PAIRS, start=1): + lines.append(f" {i}. {a} vs {b}") + return lines + + +def _pairwise_matrix(answers: Sequence[int]) -> List[List[float]]: + if len(answers) != len(QUESTION_PAIRS): + raise ValueError( + f"expected {len(QUESTION_PAIRS)} answers, got {len(answers)}") + n = len(CRITERIA) + matrix = [[1.0] * n for _ in range(n)] + index = {name: i for i, name in enumerate(CRITERIA)} + for answer, (a, b) in zip(answers, QUESTION_PAIRS): + key = int(answer) + if key not in ANSWER_SCALE: + raise ValueError(f"answer {answer!r} is not on the 1-5 scale") + intensity = ANSWER_SCALE[key] + i, j = index[a], index[b] + matrix[i][j] = intensity + matrix[j][i] = 1.0 / intensity # Saaty reciprocity, checked by ahp() + return matrix + + +def _preset_scores() -> List[Dict[str, Any]]: + """Every preset scored against every criterion via optimize.score_plan. + Deterministic: the presets and their ops are frozen registry data.""" + rows: List[Dict[str, Any]] = [] + for preset in presets(): + ops = preset_ops(preset["name"]) + scores = [score_plan(_CRITERION_PROFILE[c], ops)["score"] + for c in CRITERIA] + rows.append({"preset": preset["name"], "scores": scores, + "ops": ops}) + return rows + + +def run(answers: Sequence[int]) -> Dict[str, Any]: + """Fixed answers -> deterministic preset recommendation. Pure. + + Returns {"winner", "closeness", "ranking", "weights", + "consistent", "consistency_ratio", "criteria_scores", "ops"}. + """ + matrix = _pairwise_matrix(answers) + ahp = decision.ahp(matrix, list(CRITERIA)) + # ahp() returns priorities as {name: weight}; topsis() wants them + # column-ordered, so project onto the fixed CRITERIA order. + weights = [float(ahp["priorities"][c]) for c in CRITERIA] + + scored = _preset_scores() + topsis_matrix = [row["scores"] for row in scored] + labels = [row["preset"] for row in scored] + topsis = decision.topsis(topsis_matrix, labels, weights, + list(CRITERIA), benefits=[True] * len(CRITERIA)) + + winner = topsis["winner"] + winner_row = next(row for row in scored if row["preset"] == winner) + return { + "winner": winner, + "closeness": topsis["closeness"], + "ranking": topsis["ranking"], + "weights": weights, + "consistent": ahp["consistent"], + "consistency_ratio": ahp["consistency_ratio"], + "criteria_scores": {row["preset"]: dict(zip(CRITERIA, row["scores"])) + for row in scored}, + "ops": winner_row["ops"], + } + + +def render(result: Dict[str, Any]) -> List[str]: + """Plain-text rendering for the CLI (read-only; the ops shown ride the + ordinary --preset path if the user wants them applied).""" + lines = ["Setup wizard — starting-preset recommendation", + ""] + lines.append(f"recommended preset: {result['winner']} " + f"(TOPSIS closeness {result['closeness'][result['winner']]:.3f})") + lines.append(f"criterion weights (AHP, consistency ratio " + f"{result['consistency_ratio']:.3f}, " + f"{'consistent' if result['consistent'] else 'INCONSISTENT — answers contradict each other; treat the ranking as rough'}):") + for name, weight in zip(CRITERIA, result["weights"]): + lines.append(f" {name:<16} {weight:.3f}") + lines.append("") + lines.append("full ranking:") + for name in result["ranking"]: + closeness = result["closeness"][name] + lines.append(f" {name:<15} {closeness:.3f}") + lines.append("") + lines.append("the bundled calls (applied only through the ordinary " + "--preset gate — this wizard writes nothing):") + for op in result["ops"]: + lines.append(f" {op['tool']} = {op['value']!r}") + return lines + + +def mainish(answers: Optional[Sequence[int]] = None) -> int: # pragma: no cover + """Interactive entry used by settings --wizard; split from cli.py for + testability of the non-interactive path.""" + import sys + if answers is None: + print("\n".join(question_lines())) + try: + raw = input("your six answers, comma separated (e.g. 2,3,1,4,2,3): ") + except EOFError: + return 2 + try: + answers = [int(x) for x in raw.split(",")] + except ValueError: + print("answers must be integers 1-5", file=sys.stderr) + return 2 + try: + result = run(answers) + except (ValueError, PresetError) as exc: + print(f"error: {exc}", file=sys.stderr) + return 1 + print("\n".join(render(result))) + return 0 From bf716d01d09967c55149e7a6107ae54152d19268 Mon Sep 17 00:00:00 2001 From: ladybug-me <165172025+ladybug-me@users.noreply.github.com> Date: Sat, 24 Oct 2026 15:32:18 +0530 Subject: [PATCH 09/10] refactor: update assistant tools and settings registry definitions --- .../assistant/adapters/caelestia/tools.json | 1106 ++++++++--------- .../capabilities/settings/build_registry.py | 2 +- .../capabilities/settings/curations.py | 17 +- .../capabilities/settings/ui_ranges_data.py | 6 +- 4 files changed, 528 insertions(+), 603 deletions(-) diff --git a/plugins/caelestia-assistant/assistant/adapters/caelestia/tools.json b/plugins/caelestia-assistant/assistant/adapters/caelestia/tools.json index e702214..a08764b 100644 --- a/plugins/caelestia-assistant/assistant/adapters/caelestia/tools.json +++ b/plugins/caelestia-assistant/assistant/adapters/caelestia/tools.json @@ -1,22 +1,22 @@ { "meta": { "generator": "assistant.capabilities.settings.build_registry", - "repo_commit": "70ee7da115fde9012e28e393c73d274f55bd2dd7", + "repo_commit": "c72ef2ee3e3bb2efe265b7040e3efa89aeefc757", "notes": "Validation ranges/enums adopted exactly from the shipped Nexus controls (ui_ranges_data.py) and the C++ enum declarations; upstream declares no numeric bounds in the settings schema (type-only hook). not_exposed records every scalar leaf without a tool, with its reason.", - "tool_count": 272, + "tool_count": 261, "group_counts": { - "bar": 58, + "bar": 57, "dock": 5, "appearance": 5, - "effects": 9, + "effects": 7, "animations": 1, "notifications": 13, "launcher": 18, "lockscreen": 14, - "wallpaper-scheme": 36, - "overview": 16, + "wallpaper-scheme": 24, + "overview": 18, "osd": 7, - "dashboard": 21, + "dashboard": 23, "sidebar": 3, "nexus": 1, "border": 3, @@ -25,20 +25,20 @@ "utilities": 27, "audio": 10 }, - "not_exposed_count": 339, + "not_exposed_count": 387, "excluded_by_rule": { "ai-provider-selfconfig": 30, "ai-credentials": 5, "ai-endpoints": 7, "ai-internal-state": 2, "ai-executables": 2, - "no-shipped-control": 264, + "no-shipped-control": 310, "complex-control": 2, "dynamic-enum": 4, "master-switch": 1, "kwinrc-companion-writes": 4, "free-string": 1, - "filesystem-paths": 7, + "filesystem-paths": 9, "string-stepper": 2, "session-commands": 4, "session-icons": 4 @@ -60,7 +60,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/barconfig.hpp:224", + "shell/plugin/src/Caelestia/Config/barconfig.hpp:263", "CONFIG declaration: int dragThreshold = 20" ], [ @@ -87,7 +87,7 @@ ], "citations": [ [ - "shell/plugin/src/Caelestia/Config/barconfig.hpp:220", + "shell/plugin/src/Caelestia/Config/barconfig.hpp:259", "CONFIG declaration: bool persistent = true" ], [ @@ -122,7 +122,7 @@ ], "citations": [ [ - "shell/plugin/src/Caelestia/Config/barconfig.hpp:225", + "shell/plugin/src/Caelestia/Config/barconfig.hpp:264", "CONFIG declaration: QString position = u\"bottom\"_s" ], [ @@ -152,7 +152,7 @@ ], "citations": [ [ - "shell/plugin/src/Caelestia/Config/barconfig.hpp:211", + "shell/plugin/src/Caelestia/Config/barconfig.hpp:250", "CONFIG declaration: qreal scale = 1.0" ], [ @@ -180,7 +180,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/barconfig.hpp:223", + "shell/plugin/src/Caelestia/Config/barconfig.hpp:262", "CONFIG declaration: bool showOnHover = true" ], [ @@ -204,7 +204,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/barconfig.hpp:139", + "shell/plugin/src/Caelestia/Config/barconfig.hpp:142", "CONFIG declaration: bool background = false" ], [ @@ -228,7 +228,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/barconfig.hpp:140", + "shell/plugin/src/Caelestia/Config/barconfig.hpp:143", "CONFIG declaration: bool showDate = false" ], [ @@ -252,7 +252,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/barconfig.hpp:141", + "shell/plugin/src/Caelestia/Config/barconfig.hpp:144", "CONFIG declaration: bool showIcon = true" ], [ @@ -276,7 +276,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/barconfig.hpp:143", + "shell/plugin/src/Caelestia/Config/barconfig.hpp:146", "CONFIG declaration: bool showSeconds = false" ], [ @@ -300,7 +300,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/barconfig.hpp:222", + "shell/plugin/src/Caelestia/Config/barconfig.hpp:261", "CONFIG declaration: bool dodgeFocusedOnly = false" ], [ @@ -324,7 +324,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/barconfig.hpp:221", + "shell/plugin/src/Caelestia/Config/barconfig.hpp:260", "CONFIG declaration: bool dodgeWindows = false" ], [ @@ -348,7 +348,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/barconfig.hpp:216", + "shell/plugin/src/Caelestia/Config/barconfig.hpp:255", "CONFIG declaration: qreal fontScaleOffset = 0.0" ], [ @@ -372,7 +372,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/barconfig.hpp:161", + "shell/plugin/src/Caelestia/Config/barconfig.hpp:165", "CONFIG declaration: bool background = false" ], [ @@ -396,7 +396,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/barconfig.hpp:83", + "shell/plugin/src/Caelestia/Config/barconfig.hpp:84", "CONFIG declaration: int afternoonStart = 12" ], [ @@ -405,30 +405,6 @@ ] ] }, - { - "name": "setGreeterCompact", - "path": "bar.greeter.compact", - "group": "bar", - "kind": "bool", - "default": false, - "minimum": null, - "maximum": null, - "step": null, - "enum": null, - "string_max_len": null, - "global_only": false, - "nouns": [], - "citations": [ - [ - "shell/plugin/src/Caelestia/Config/barconfig.hpp:71", - "CONFIG declaration: bool compact = false" - ], - [ - "shell/modules/nexus/pages/panels/taskbar/BarGreeter.qml:97", - "shipped Nexus control (ToggleRow)" - ] - ] - }, { "name": "setGreeterEveningStart", "path": "bar.greeter.eveningStart", @@ -444,7 +420,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/barconfig.hpp:84", + "shell/plugin/src/Caelestia/Config/barconfig.hpp:85", "CONFIG declaration: int eveningStart = 17" ], [ @@ -468,7 +444,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/barconfig.hpp:72", + "shell/plugin/src/Caelestia/Config/barconfig.hpp:73", "CONFIG declaration: bool inverted = false" ], [ @@ -495,7 +471,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/barconfig.hpp:75", + "shell/plugin/src/Caelestia/Config/barconfig.hpp:76", "CONFIG declaration: QString mode = u\"timeOfDay\"_s" ], [ @@ -519,7 +495,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/barconfig.hpp:82", + "shell/plugin/src/Caelestia/Config/barconfig.hpp:83", "CONFIG declaration: int morningStart = 5" ], [ @@ -543,7 +519,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/barconfig.hpp:85", + "shell/plugin/src/Caelestia/Config/barconfig.hpp:86", "CONFIG declaration: int nightStart = 20" ], [ @@ -567,7 +543,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/barconfig.hpp:73", + "shell/plugin/src/Caelestia/Config/barconfig.hpp:74", "CONFIG declaration: bool showOnHover = true" ], [ @@ -591,7 +567,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/barconfig.hpp:96", + "shell/plugin/src/Caelestia/Config/barconfig.hpp:97", "CONFIG declaration: qreal slideshowInterval = 60.0" ], [ @@ -615,7 +591,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/barconfig.hpp:97", + "shell/plugin/src/Caelestia/Config/barconfig.hpp:98", "CONFIG declaration: bool slideshowRandom = false" ], [ @@ -641,7 +617,7 @@ ], "citations": [ [ - "shell/plugin/src/Caelestia/Config/barconfig.hpp:217", + "shell/plugin/src/Caelestia/Config/barconfig.hpp:256", "CONFIG declaration: bool livePreviews = true" ], [ @@ -741,7 +717,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/barconfig.hpp:212", + "shell/plugin/src/Caelestia/Config/barconfig.hpp:251", "CONFIG declaration: qreal previewScale = 1.0" ], [ @@ -765,7 +741,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/barconfig.hpp:213", + "shell/plugin/src/Caelestia/Config/barconfig.hpp:252", "CONFIG declaration: bool previewScaleWithBar = false" ], [ @@ -789,7 +765,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/barconfig.hpp:174", + "shell/plugin/src/Caelestia/Config/barconfig.hpp:211", "CONFIG declaration: qreal audio = 0.0" ], [ @@ -813,7 +789,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/barconfig.hpp:175", + "shell/plugin/src/Caelestia/Config/barconfig.hpp:212", "CONFIG declaration: qreal battery = 0.0" ], [ @@ -837,7 +813,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/barconfig.hpp:176", + "shell/plugin/src/Caelestia/Config/barconfig.hpp:213", "CONFIG declaration: qreal bluetooth = 0.0" ], [ @@ -861,7 +837,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/barconfig.hpp:178", + "shell/plugin/src/Caelestia/Config/barconfig.hpp:215", "CONFIG declaration: qreal dock = 0.0" ], [ @@ -885,7 +861,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/barconfig.hpp:179", + "shell/plugin/src/Caelestia/Config/barconfig.hpp:216", "CONFIG declaration: qreal github = 0.0" ], [ @@ -909,7 +885,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/barconfig.hpp:173", + "shell/plugin/src/Caelestia/Config/barconfig.hpp:210", "CONFIG declaration: qreal greeter = 0.0" ], [ @@ -933,7 +909,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/barconfig.hpp:181", + "shell/plugin/src/Caelestia/Config/barconfig.hpp:219", "CONFIG declaration: qreal lockStatus = 0.0" ], [ @@ -957,7 +933,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/barconfig.hpp:182", + "shell/plugin/src/Caelestia/Config/barconfig.hpp:220", "CONFIG declaration: qreal network = 0.0" ], [ @@ -981,7 +957,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/barconfig.hpp:183", + "shell/plugin/src/Caelestia/Config/barconfig.hpp:221", "CONFIG declaration: qreal notifications = 0.0" ], [ @@ -1005,7 +981,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/barconfig.hpp:184", + "shell/plugin/src/Caelestia/Config/barconfig.hpp:222", "CONFIG declaration: qreal peripheralBattery = 0.0" ], [ @@ -1029,7 +1005,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/barconfig.hpp:185", + "shell/plugin/src/Caelestia/Config/barconfig.hpp:223", "CONFIG declaration: qreal trayMenu = 0.0" ], [ @@ -1053,7 +1029,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/barconfig.hpp:186", + "shell/plugin/src/Caelestia/Config/barconfig.hpp:224", "CONFIG declaration: qreal wirelessPassword = 0.0" ], [ @@ -1149,7 +1125,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/barconfig.hpp:126", + "shell/plugin/src/Caelestia/Config/barconfig.hpp:129", "CONFIG declaration: bool showWifi = true" ], [ @@ -1173,7 +1149,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/barconfig.hpp:112", + "shell/plugin/src/Caelestia/Config/barconfig.hpp:113", "CONFIG declaration: bool background = false" ], [ @@ -1197,7 +1173,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/barconfig.hpp:114", + "shell/plugin/src/Caelestia/Config/barconfig.hpp:115", "CONFIG declaration: bool compact = true" ], [ @@ -1221,7 +1197,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/barconfig.hpp:113", + "shell/plugin/src/Caelestia/Config/barconfig.hpp:114", "CONFIG declaration: bool recolour = false" ], [ @@ -1245,7 +1221,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/barconfig.hpp:37", + "shell/plugin/src/Caelestia/Config/barconfig.hpp:39", "CONFIG declaration: bool activeIndicator = true" ], [ @@ -1259,7 +1235,7 @@ "path": "bar.workspaces.activeTrail", "group": "bar", "kind": "bool", - "default": false, + "default": true, "minimum": null, "maximum": null, "step": null, @@ -1269,8 +1245,8 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/barconfig.hpp:43", - "CONFIG declaration: bool activeTrail = false" + "shell/plugin/src/Caelestia/Config/barconfig.hpp:45", + "CONFIG declaration: bool activeTrail = true" ], [ "shell/modules/nexus/pages/panels/taskbar/BarWorkspaces.qml:83", @@ -1296,7 +1272,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/barconfig.hpp:49", + "shell/plugin/src/Caelestia/Config/barconfig.hpp:51", "CONFIG declaration: caelestia::config::BarWorkspaceDisplay::Enum displayType = BarWorkspaceDisplay::Shapes" ], [ @@ -1320,7 +1296,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/barconfig.hpp:42", + "shell/plugin/src/Caelestia/Config/barconfig.hpp:44", "CONFIG declaration: int maxWindowIcons = 5" ], [ @@ -1344,7 +1320,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/barconfig.hpp:38", + "shell/plugin/src/Caelestia/Config/barconfig.hpp:40", "CONFIG declaration: bool occupiedBg = false" ], [ @@ -1368,7 +1344,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/barconfig.hpp:45", + "shell/plugin/src/Caelestia/Config/barconfig.hpp:47", "CONFIG declaration: bool perMonitor = true" ], [ @@ -1392,7 +1368,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/barconfig.hpp:39", + "shell/plugin/src/Caelestia/Config/barconfig.hpp:41", "CONFIG declaration: bool showUnoccupied = true" ], [ @@ -1416,7 +1392,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/barconfig.hpp:40", + "shell/plugin/src/Caelestia/Config/barconfig.hpp:42", "CONFIG declaration: bool showWindows = true" ], [ @@ -1440,7 +1416,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/barconfig.hpp:41", + "shell/plugin/src/Caelestia/Config/barconfig.hpp:43", "CONFIG declaration: bool showWindowsOnSpecialWorkspaces = true" ], [ @@ -1464,7 +1440,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/barconfig.hpp:36", + "shell/plugin/src/Caelestia/Config/barconfig.hpp:38", "CONFIG declaration: int shown = 5" ], [ @@ -1490,7 +1466,7 @@ ], "citations": [ [ - "shell/plugin/src/Caelestia/Config/barconfig.hpp:151", + "shell/plugin/src/Caelestia/Config/barconfig.hpp:154", "CONFIG declaration: bool showBadges = true" ], [ @@ -1518,7 +1494,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/barconfig.hpp:153", + "shell/plugin/src/Caelestia/Config/barconfig.hpp:156", "CONFIG declaration: bool currentDesktopOnly = false" ], [ @@ -1544,7 +1520,7 @@ ], "citations": [ [ - "shell/plugin/src/Caelestia/Config/barconfig.hpp:152", + "shell/plugin/src/Caelestia/Config/barconfig.hpp:155", "CONFIG declaration: int iconSize = 32" ], [ @@ -1572,7 +1548,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/barconfig.hpp:154", + "shell/plugin/src/Caelestia/Config/barconfig.hpp:158", "CONFIG declaration: bool previewOnDesktop = true" ], [ @@ -1596,7 +1572,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/barconfig.hpp:150", + "shell/plugin/src/Caelestia/Config/barconfig.hpp:153", "CONFIG declaration: bool recolourIcons = false" ], [ @@ -1620,7 +1596,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/appearanceconfig.hpp:314", + "shell/plugin/src/Caelestia/Config/appearanceconfig.hpp:333", "CONFIG declaration: qreal deformScale = 1" ], [ @@ -1646,7 +1622,7 @@ ], "citations": [ [ - "shell/plugin/src/Caelestia/Config/appearanceconfig.hpp:249", + "shell/plugin/src/Caelestia/Config/appearanceconfig.hpp:252", "CONFIG declaration: qreal scale = 1" ], [ @@ -1672,7 +1648,7 @@ ], "citations": [ [ - "shell/plugin/src/Caelestia/Config/appearanceconfig.hpp:90", + "shell/plugin/src/Caelestia/Config/appearanceconfig.hpp:91", "CONFIG declaration: qreal scale = 1" ], [ @@ -1698,7 +1674,7 @@ ], "citations": [ [ - "shell/plugin/src/Caelestia/Config/appearanceconfig.hpp:22", + "shell/plugin/src/Caelestia/Config/appearanceconfig.hpp:23", "CONFIG declaration: qreal scale = 1" ], [ @@ -1724,7 +1700,7 @@ ], "citations": [ [ - "shell/plugin/src/Caelestia/Config/appearanceconfig.hpp:57", + "shell/plugin/src/Caelestia/Config/appearanceconfig.hpp:58", "CONFIG declaration: qreal scale = 1" ], [ @@ -1733,54 +1709,6 @@ ] ] }, - { - "name": "setAmbientColor", - "path": "appearance.ambientColor", - "group": "effects", - "kind": "bool", - "default": true, - "minimum": null, - "maximum": null, - "step": null, - "enum": null, - "string_max_len": null, - "global_only": true, - "nouns": [], - "citations": [ - [ - "shell/plugin/src/Caelestia/Config/appearanceconfig.hpp:326", - "CONFIG declaration: bool ambientColor = true" - ], - [ - "shell/modules/nexus/pages/wallandstyle/AppearancePage.qml:158", - "shipped Nexus control (ToggleRow)" - ] - ] - }, - { - "name": "setAmbientOpacity", - "path": "appearance.ambientOpacity", - "group": "effects", - "kind": "float", - "default": 0.45, - "minimum": 0, - "maximum": 1, - "step": null, - "enum": null, - "string_max_len": null, - "global_only": true, - "nouns": [], - "citations": [ - [ - "shell/plugin/src/Caelestia/Config/appearanceconfig.hpp:327", - "CONFIG declaration: qreal ambientOpacity = 0.45" - ], - [ - "shell/modules/nexus/pages/wallandstyle/AppearancePage.qml:167", - "shipped Nexus control (SliderRow)" - ] - ] - }, { "name": "setBlurEnabled", "path": "appearance.blur", @@ -1798,7 +1726,7 @@ ], "citations": [ [ - "shell/plugin/src/Caelestia/Config/appearanceconfig.hpp:324", + "shell/plugin/src/Caelestia/Config/appearanceconfig.hpp:343", "CONFIG declaration: bool blur = true" ], [ @@ -1826,7 +1754,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/appearanceconfig.hpp:325", + "shell/plugin/src/Caelestia/Config/appearanceconfig.hpp:344", "CONFIG declaration: bool blurMask = true" ], [ @@ -1850,7 +1778,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/appearanceconfig.hpp:323", + "shell/plugin/src/Caelestia/Config/appearanceconfig.hpp:342", "CONFIG declaration: bool islands = false" ], [ @@ -1876,7 +1804,7 @@ ], "citations": [ [ - "shell/plugin/src/Caelestia/Config/appearanceconfig.hpp:322", + "shell/plugin/src/Caelestia/Config/appearanceconfig.hpp:341", "CONFIG declaration: bool pitchBlack = false" ], [ @@ -1906,7 +1834,7 @@ ], "citations": [ [ - "shell/plugin/src/Caelestia/Config/appearanceconfig.hpp:307", + "shell/plugin/src/Caelestia/Config/appearanceconfig.hpp:326", "CONFIG declaration: qreal base = 0.85" ], [ @@ -1934,7 +1862,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/appearanceconfig.hpp:306", + "shell/plugin/src/Caelestia/Config/appearanceconfig.hpp:325", "CONFIG declaration: bool enabled = true" ], [ @@ -1958,7 +1886,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/appearanceconfig.hpp:308", + "shell/plugin/src/Caelestia/Config/appearanceconfig.hpp:327", "CONFIG declaration: qreal layers = 0.4" ], [ @@ -1984,7 +1912,7 @@ ], "citations": [ [ - "shell/plugin/src/Caelestia/Config/appearanceconfig.hpp:263", + "shell/plugin/src/Caelestia/Config/appearanceconfig.hpp:269", "CONFIG declaration: qreal scale = 1" ], [ @@ -2012,7 +1940,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/notifsconfig.hpp:20", + "shell/plugin/src/Caelestia/Config/notifsconfig.hpp:33", "CONFIG declaration: bool actionOnClick = false" ], [ @@ -2036,7 +1964,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/notifsconfig.hpp:18", + "shell/plugin/src/Caelestia/Config/notifsconfig.hpp:31", "CONFIG declaration: qreal clearThreshold = 0.3" ], [ @@ -2060,7 +1988,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/notifsconfig.hpp:16", + "shell/plugin/src/Caelestia/Config/notifsconfig.hpp:29", "CONFIG declaration: int defaultExpireTimeout = 5000" ], [ @@ -2088,7 +2016,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/notifsconfig.hpp:19", + "shell/plugin/src/Caelestia/Config/notifsconfig.hpp:32", "CONFIG declaration: int expandThreshold = 20" ], [ @@ -2112,7 +2040,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/notifsconfig.hpp:13", + "shell/plugin/src/Caelestia/Config/notifsconfig.hpp:26", "CONFIG declaration: bool expire = true" ], [ @@ -2139,7 +2067,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/notifsconfig.hpp:14", + "shell/plugin/src/Caelestia/Config/notifsconfig.hpp:27", "CONFIG declaration: QString fullscreen = QStringLiteral(\"off\")" ], [ @@ -2163,7 +2091,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/notifsconfig.hpp:17", + "shell/plugin/src/Caelestia/Config/notifsconfig.hpp:30", "CONFIG declaration: int fullscreenExpireTimeout = 2000" ], [ @@ -2191,7 +2119,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/notifsconfig.hpp:21", + "shell/plugin/src/Caelestia/Config/notifsconfig.hpp:34", "CONFIG declaration: int groupPreviewNum = 3" ], [ @@ -2218,7 +2146,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/notifsconfig.hpp:15", + "shell/plugin/src/Caelestia/Config/notifsconfig.hpp:28", "CONFIG declaration: QString monitor = QStringLiteral(\"all\")" ], [ @@ -2244,7 +2172,7 @@ ], "citations": [ [ - "shell/plugin/src/Caelestia/Config/notifsconfig.hpp:25", + "shell/plugin/src/Caelestia/Config/notifsconfig.hpp:38", "CONFIG declaration: int maxNotifs = 50" ], [ @@ -2270,7 +2198,7 @@ ], "citations": [ [ - "shell/plugin/src/Caelestia/Config/notifsconfig.hpp:24", + "shell/plugin/src/Caelestia/Config/notifsconfig.hpp:37", "CONFIG declaration: int maxPopups = 8" ], [ @@ -2294,7 +2222,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/notifsconfig.hpp:22", + "shell/plugin/src/Caelestia/Config/notifsconfig.hpp:35", "CONFIG declaration: bool openExpanded = false" ], [ @@ -2326,7 +2254,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/notifsconfig.hpp:23", + "shell/plugin/src/Caelestia/Config/notifsconfig.hpp:36", "CONFIG declaration: QString position = QStringLiteral(\"auto\")" ], [ @@ -2350,7 +2278,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/launcherconfig.hpp:46", + "shell/plugin/src/Caelestia/Config/launcherconfig.hpp:47", "CONFIG declaration: int clipboardMaxEntries = 20" ], [ @@ -2374,7 +2302,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/launcherconfig.hpp:56", + "shell/plugin/src/Caelestia/Config/launcherconfig.hpp:59", "CONFIG declaration: bool confirmClearClipboard = true" ], [ @@ -2398,7 +2326,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/launcherconfig.hpp:49", + "shell/plugin/src/Caelestia/Config/launcherconfig.hpp:50", "CONFIG declaration: bool enableDangerousActions = false" ], [ @@ -2422,7 +2350,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/launcherconfig.hpp:50", + "shell/plugin/src/Caelestia/Config/launcherconfig.hpp:51", "CONFIG declaration: int dragThreshold = 50" ], [ @@ -2446,7 +2374,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/launcherconfig.hpp:42", + "shell/plugin/src/Caelestia/Config/launcherconfig.hpp:43", "CONFIG declaration: bool enabled = true" ], [ @@ -2470,7 +2398,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/launcherconfig.hpp:53", + "shell/plugin/src/Caelestia/Config/launcherconfig.hpp:56", "CONFIG declaration: int hoverThickness = 10" ], [ @@ -2494,7 +2422,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/launcherconfig.hpp:54", + "shell/plugin/src/Caelestia/Config/launcherconfig.hpp:57", "CONFIG declaration: int hoverWidth = 50" ], [ @@ -2520,7 +2448,7 @@ ], "citations": [ [ - "shell/plugin/src/Caelestia/Config/launcherconfig.hpp:44", + "shell/plugin/src/Caelestia/Config/launcherconfig.hpp:45", "CONFIG declaration: int maxShown = 7" ], [ @@ -2544,7 +2472,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/launcherconfig.hpp:43", + "shell/plugin/src/Caelestia/Config/launcherconfig.hpp:44", "CONFIG declaration: bool showOnHover = false" ], [ @@ -2568,7 +2496,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/launcherconfig.hpp:55", + "shell/plugin/src/Caelestia/Config/launcherconfig.hpp:58", "CONFIG declaration: bool vimKeybinds = false" ], [ @@ -2592,7 +2520,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/launcherconfig.hpp:45", + "shell/plugin/src/Caelestia/Config/launcherconfig.hpp:46", "CONFIG declaration: int maxWallpapers = 9" ], [ @@ -2616,7 +2544,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/launcherconfig.hpp:52", + "shell/plugin/src/Caelestia/Config/launcherconfig.hpp:53", "CONFIG declaration: bool showBrowseOnEmpty = true" ], [ @@ -2640,7 +2568,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/launcherconfig.hpp:51", + "shell/plugin/src/Caelestia/Config/launcherconfig.hpp:52", "CONFIG declaration: bool showPowerMenu = true" ], [ @@ -2664,7 +2592,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/launcherconfig.hpp:19", + "shell/plugin/src/Caelestia/Config/launcherconfig.hpp:20", "CONFIG declaration: bool actions = false" ], [ @@ -2688,7 +2616,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/launcherconfig.hpp:18", + "shell/plugin/src/Caelestia/Config/launcherconfig.hpp:19", "CONFIG declaration: bool apps = false" ], [ @@ -2712,7 +2640,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/launcherconfig.hpp:20", + "shell/plugin/src/Caelestia/Config/launcherconfig.hpp:21", "CONFIG declaration: bool schemes = false" ], [ @@ -2736,7 +2664,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/launcherconfig.hpp:21", + "shell/plugin/src/Caelestia/Config/launcherconfig.hpp:22", "CONFIG declaration: bool variants = false" ], [ @@ -2760,7 +2688,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/launcherconfig.hpp:22", + "shell/plugin/src/Caelestia/Config/launcherconfig.hpp:23", "CONFIG declaration: bool wallpapers = false" ], [ @@ -3105,30 +3033,6 @@ ] ] }, - { - "name": "setDesktopClockEnabled", - "path": "background.desktopClock.enabled", - "group": "wallpaper-scheme", - "kind": "bool", - "default": true, - "minimum": null, - "maximum": null, - "step": null, - "enum": null, - "string_max_len": null, - "global_only": false, - "nouns": [], - "citations": [ - [ - "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:29", - "CONFIG declaration: bool enabled = true" - ], - [ - "shell/modules/nexus/pages/wallandstyle/DesktopAddonsPage.qml:89", - "shipped Nexus control (ToggleRow)" - ] - ] - }, { "name": "setDesktopClockInvertColors", "path": "background.desktopClock.invertColors", @@ -3144,7 +3048,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:32", + "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:29", "CONFIG declaration: bool invertColors = false" ], [ @@ -3153,62 +3057,6 @@ ] ] }, - { - "name": "setDesktopClockPosition", - "path": "background.desktopClock.position", - "group": "wallpaper-scheme", - "kind": "enum", - "default": "bottom-right", - "minimum": null, - "maximum": null, - "step": null, - "enum": [ - "top-left", - "top-center", - "top-right", - "center", - "bottom-left", - "bottom-center", - "bottom-right" - ], - "string_max_len": null, - "global_only": false, - "nouns": [], - "citations": [ - [ - "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:31", - "CONFIG declaration: QString position = QStringLiteral(\"bottom-right\")" - ], - [ - "shell/modules/nexus/pages/wallandstyle/DesktopAddonsPage.qml:197", - "shipped Nexus control (SelectRow)" - ] - ] - }, - { - "name": "setDesktopClockScale", - "path": "background.desktopClock.scale", - "group": "wallpaper-scheme", - "kind": "float", - "default": 1.0, - "minimum": 0.5, - "maximum": 3, - "step": 0.1, - "enum": null, - "string_max_len": null, - "global_only": false, - "nouns": [], - "citations": [ - [ - "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:30", - "CONFIG declaration: qreal scale = 1.0" - ], - [ - "shell/modules/nexus/pages/wallandstyle/DesktopAddonsPage.qml:186", - "shipped Nexus control (StepperRow)" - ] - ] - }, { "name": "setDesktopIconsEnabled", "path": "background.desktopIconsEnabled", @@ -3224,7 +3072,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:103", + "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:92", "CONFIG declaration: bool desktopIconsEnabled = true" ], [ @@ -3238,7 +3086,7 @@ "path": "background.desktopLyrics.alignment", "group": "wallpaper-scheme", "kind": "int", - "default": 1, + "default": 0, "minimum": 0, "maximum": 2, "step": 1, @@ -3248,8 +3096,8 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:71", - "CONFIG declaration: int alignment = 1" + "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:63", + "CONFIG declaration: int alignment = 0" ], [ "shell/modules/nexus/pages/wallandstyle/DesktopAddonsPage.qml:294", @@ -3272,7 +3120,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:68", + "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:62", "CONFIG declaration: bool autoHide = true" ], [ @@ -3281,30 +3129,6 @@ ] ] }, - { - "name": "setDesktopLyricsEnabled", - "path": "background.desktopLyrics.enabled", - "group": "wallpaper-scheme", - "kind": "bool", - "default": false, - "minimum": null, - "maximum": null, - "step": null, - "enum": null, - "string_max_len": null, - "global_only": false, - "nouns": [], - "citations": [ - [ - "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:67", - "CONFIG declaration: bool enabled = false" - ], - [ - "shell/modules/nexus/pages/wallandstyle/DesktopAddonsPage.qml:119", - "shipped Nexus control (ToggleRow)" - ] - ] - }, { "name": "setDesktopLyricsInvertColors", "path": "background.desktopLyrics.invertColors", @@ -3320,7 +3144,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:72", + "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:64", "CONFIG declaration: bool invertColors = false" ], [ @@ -3329,62 +3153,6 @@ ] ] }, - { - "name": "setDesktopLyricsPosition", - "path": "background.desktopLyrics.position", - "group": "wallpaper-scheme", - "kind": "enum", - "default": "bottom-center", - "minimum": null, - "maximum": null, - "step": null, - "enum": [ - "top-left", - "top-center", - "top-right", - "center", - "bottom-left", - "bottom-center", - "bottom-right" - ], - "string_max_len": null, - "global_only": false, - "nouns": [], - "citations": [ - [ - "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:70", - "CONFIG declaration: QString position = QStringLiteral(\"bottom-center\")" - ], - [ - "shell/modules/nexus/pages/wallandstyle/DesktopAddonsPage.qml:278", - "shipped Nexus control (SelectRow)" - ] - ] - }, - { - "name": "setDesktopLyricsScale", - "path": "background.desktopLyrics.scale", - "group": "wallpaper-scheme", - "kind": "float", - "default": 1.0, - "minimum": 0.5, - "maximum": 3, - "step": 0.1, - "enum": null, - "string_max_len": null, - "global_only": false, - "nouns": [], - "citations": [ - [ - "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:69", - "CONFIG declaration: qreal scale = 1.0" - ], - [ - "shell/modules/nexus/pages/wallandstyle/DesktopAddonsPage.qml:267", - "shipped Nexus control (StepperRow)" - ] - ] - }, { "name": "setDesktopShapesAutoHide", "path": "background.desktopShapes.autoHide", @@ -3400,7 +3168,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:81", + "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:72", "CONFIG declaration: bool autoHide = true" ], [ @@ -3409,86 +3177,6 @@ ] ] }, - { - "name": "setDesktopShapesEnabled", - "path": "background.desktopShapes.enabled", - "group": "wallpaper-scheme", - "kind": "bool", - "default": true, - "minimum": null, - "maximum": null, - "step": null, - "enum": null, - "string_max_len": null, - "global_only": false, - "nouns": [], - "citations": [ - [ - "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:80", - "CONFIG declaration: bool enabled = true" - ], - [ - "shell/modules/nexus/pages/wallandstyle/DesktopAddonsPage.qml:97", - "shipped Nexus control (ToggleRow)" - ] - ] - }, - { - "name": "setDesktopShapesPosition", - "path": "background.desktopShapes.position", - "group": "wallpaper-scheme", - "kind": "enum", - "default": "bottom-center", - "minimum": null, - "maximum": null, - "step": null, - "enum": [ - "top-left", - "top-center", - "top-right", - "center", - "bottom-left", - "bottom-center", - "bottom-right" - ], - "string_max_len": null, - "global_only": false, - "nouns": [], - "citations": [ - [ - "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:83", - "CONFIG declaration: QString position = QStringLiteral(\"bottom-center\")" - ], - [ - "shell/modules/nexus/pages/wallandstyle/DesktopAddonsPage.qml:241", - "shipped Nexus control (SelectRow)" - ] - ] - }, - { - "name": "setDesktopShapesScale", - "path": "background.desktopShapes.scale", - "group": "wallpaper-scheme", - "kind": "float", - "default": 1.0, - "minimum": 0.5, - "maximum": 3, - "step": 0.1, - "enum": null, - "string_max_len": null, - "global_only": false, - "nouns": [], - "citations": [ - [ - "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:82", - "CONFIG declaration: qreal scale = 1.0" - ], - [ - "shell/modules/nexus/pages/wallandstyle/DesktopAddonsPage.qml:230", - "shipped Nexus control (StepperRow)" - ] - ] - }, { "name": "setMaterialYouIconsEnabled", "path": "background.materialYouIconsEnabled", @@ -3504,7 +3192,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:104", + "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:93", "CONFIG declaration: bool materialYouIconsEnabled = true" ], [ @@ -3528,7 +3216,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:105", + "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:94", "CONFIG declaration: bool materialYouIconsVibrant = true" ], [ @@ -3552,7 +3240,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:94", + "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:83", "CONFIG declaration: bool slideshowEnabled = false" ], [ @@ -3576,7 +3264,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:95", + "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:84", "CONFIG declaration: qreal slideshowInterval = 0.16" ], [ @@ -3600,7 +3288,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:96", + "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:85", "CONFIG declaration: bool slideshowRandom = true" ], [ @@ -3624,7 +3312,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:102", + "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:91", "CONFIG declaration: bool videoWallpaperMuteOnMedia = false" ], [ @@ -3648,7 +3336,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:101", + "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:90", "CONFIG declaration: bool videoWallpaperPauseOnAllDisplays = false" ], [ @@ -3672,7 +3360,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:99", + "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:88", "CONFIG declaration: bool videoWallpaperPauseOnFullscreen = false" ], [ @@ -3696,7 +3384,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:100", + "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:89", "CONFIG declaration: bool videoWallpaperPauseOnTiled = false" ], [ @@ -3720,7 +3408,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:97", + "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:86", "CONFIG declaration: bool videoWallpaperPaused = false" ], [ @@ -3744,7 +3432,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:98", + "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:87", "CONFIG declaration: bool videoWallpaperSoundEnabled = false" ], [ @@ -3768,7 +3456,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:41", + "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:39", "CONFIG declaration: bool autoHide = true" ], [ @@ -3777,30 +3465,6 @@ ] ] }, - { - "name": "setVisualiserBlur", - "path": "background.visualiser.blur", - "group": "wallpaper-scheme", - "kind": "bool", - "default": false, - "minimum": null, - "maximum": null, - "step": null, - "enum": null, - "string_max_len": null, - "global_only": false, - "nouns": [], - "citations": [ - [ - "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:43", - "CONFIG declaration: bool blur = false" - ], - [ - "shell/modules/nexus/pages/wallandstyle/DesktopAddonsPage.qml:325", - "shipped Nexus control (ToggleRow)" - ] - ] - }, { "name": "setVisualiserEnabled", "path": "background.visualiser.enabled", @@ -3816,7 +3480,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:40", + "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:37", "CONFIG declaration: bool enabled = true" ], [ @@ -3840,7 +3504,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:42", + "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:40", "CONFIG declaration: bool hideOnAllMonitors = false" ], [ @@ -3849,60 +3513,12 @@ ] ] }, - { - "name": "setVisualiserRounding", - "path": "background.visualiser.rounding", - "group": "wallpaper-scheme", - "kind": "float", - "default": 1.0, - "minimum": 0, - "maximum": 1, - "step": 0.05, - "enum": null, - "string_max_len": null, - "global_only": false, - "nouns": [], - "citations": [ - [ - "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:44", - "CONFIG declaration: qreal rounding = 1" - ], - [ - "shell/modules/nexus/pages/wallandstyle/DesktopAddonsPage.qml:333", - "shipped Nexus control (StepperRow)" - ] - ] - }, - { - "name": "setVisualiserSpacing", - "path": "background.visualiser.spacing", - "group": "wallpaper-scheme", - "kind": "float", - "default": 1.0, - "minimum": 0.5, - "maximum": 3, - "step": 0.1, - "enum": null, - "string_max_len": null, - "global_only": false, - "nouns": [], - "citations": [ - [ - "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:45", - "CONFIG declaration: qreal spacing = 1" - ], - [ - "shell/modules/nexus/pages/wallandstyle/DesktopAddonsPage.qml:343", - "shipped Nexus control (StepperRow)" - ] - ] - }, { "name": "setWallpaperEnabled", "path": "background.wallpaperEnabled", "group": "wallpaper-scheme", "kind": "bool", - "default": true, + "default": false, "minimum": null, "maximum": null, "step": null, @@ -3912,8 +3528,8 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:90", - "CONFIG declaration: bool wallpaperEnabled = true" + "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:79", + "CONFIG declaration: bool wallpaperEnabled = false" ], [ "shell/modules/nexus/pages/DesktopPage.qml:24", @@ -3940,7 +3556,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:91", + "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:80", "CONFIG declaration: int wallpaperFillMode = 2" ], [ @@ -3968,7 +3584,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:92", + "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:81", "CONFIG declaration: bool wallpaperRecolor = false" ], [ @@ -3992,7 +3608,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:93", + "shell/plugin/src/Caelestia/Config/backgroundconfig.hpp:82", "CONFIG declaration: qreal wallpaperRecolorStrength = 0.5" ], [ @@ -4016,7 +3632,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/overviewconfig.hpp:22", + "shell/plugin/src/Caelestia/Config/overviewconfig.hpp:24", "CONFIG declaration: int baseDuration = 300" ], [ @@ -4040,7 +3656,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/overviewconfig.hpp:23", + "shell/plugin/src/Caelestia/Config/overviewconfig.hpp:25", "CONFIG declaration: qreal blobScaleSpeed = 1.0" ], [ @@ -4102,7 +3718,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/overviewconfig.hpp:26", + "shell/plugin/src/Caelestia/Config/overviewconfig.hpp:28", "CONFIG declaration: int easingType = 2" ], [ @@ -4150,7 +3766,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/overviewconfig.hpp:25", + "shell/plugin/src/Caelestia/Config/overviewconfig.hpp:27", "CONFIG declaration: qreal gridFadeSpeed = 1.0" ], [ @@ -4174,7 +3790,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/overviewconfig.hpp:19", + "shell/plugin/src/Caelestia/Config/overviewconfig.hpp:21", "CONFIG declaration: bool hoverBottomLeft = false" ], [ @@ -4198,7 +3814,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/overviewconfig.hpp:20", + "shell/plugin/src/Caelestia/Config/overviewconfig.hpp:22", "CONFIG declaration: bool hoverBottomRight = false" ], [ @@ -4222,7 +3838,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/overviewconfig.hpp:17", + "shell/plugin/src/Caelestia/Config/overviewconfig.hpp:19", "CONFIG declaration: bool hoverTopLeft = true" ], [ @@ -4246,7 +3862,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/overviewconfig.hpp:18", + "shell/plugin/src/Caelestia/Config/overviewconfig.hpp:20", "CONFIG declaration: bool hoverTopRight = false" ], [ @@ -4270,7 +3886,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/overviewconfig.hpp:27", + "shell/plugin/src/Caelestia/Config/overviewconfig.hpp:29", "CONFIG declaration: int layoutType = 1" ], [ @@ -4279,6 +3895,54 @@ ] ] }, + { + "name": "setOverviewAmbientColor", + "path": "overview.ambientColor", + "group": "overview", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/overviewconfig.hpp:14", + "CONFIG declaration: bool ambientColor = true" + ], + [ + "shell/modules/nexus/pages/panels/OverviewPanel.qml:214", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setOverviewAmbientOpacity", + "path": "overview.ambientOpacity", + "group": "overview", + "kind": "float", + "default": 0.45, + "minimum": 0, + "maximum": 1, + "step": 0.05, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/overviewconfig.hpp:15", + "CONFIG declaration: qreal ambientOpacity = 0.45" + ], + [ + "shell/modules/nexus/pages/panels/OverviewPanel.qml:221", + "shipped Nexus control (StepperRow)" + ] + ] + }, { "name": "setOverviewDragThreshold", "path": "overview.dragThreshold", @@ -4294,7 +3958,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/overviewconfig.hpp:15", + "shell/plugin/src/Caelestia/Config/overviewconfig.hpp:17", "CONFIG declaration: int dragThreshold = 30" ], [ @@ -4342,7 +4006,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/overviewconfig.hpp:16", + "shell/plugin/src/Caelestia/Config/overviewconfig.hpp:18", "CONFIG declaration: int hoverThickness = 20" ], [ @@ -4366,7 +4030,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/overviewconfig.hpp:14", + "shell/plugin/src/Caelestia/Config/overviewconfig.hpp:16", "CONFIG declaration: bool showOnHover = true" ], [ @@ -4390,7 +4054,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/overviewconfig.hpp:24", + "shell/plugin/src/Caelestia/Config/overviewconfig.hpp:26", "CONFIG declaration: qreal wallpaperFadeSpeed = 1.0" ], [ @@ -4586,7 +4250,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/dashboardconfig.hpp:30", + "shell/plugin/src/Caelestia/Config/dashboardconfig.hpp:31", "CONFIG declaration: bool colorizeMediaGif = true" ], [ @@ -4595,6 +4259,54 @@ ] ] }, + { + "name": "setDashboardAmbientColor", + "path": "dashboard.ambientColor", + "group": "dashboard", + "kind": "bool", + "default": true, + "minimum": null, + "maximum": null, + "step": null, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/dashboardconfig.hpp:34", + "CONFIG declaration: bool ambientColor = true" + ], + [ + "shell/modules/nexus/pages/panels/DashboardPanel.qml:206", + "shipped Nexus control (ToggleRow)" + ] + ] + }, + { + "name": "setDashboardAmbientOpacity", + "path": "dashboard.ambientOpacity", + "group": "dashboard", + "kind": "float", + "default": 0.3, + "minimum": 0, + "maximum": 1, + "step": 0.05, + "enum": null, + "string_max_len": null, + "global_only": false, + "nouns": [], + "citations": [ + [ + "shell/plugin/src/Caelestia/Config/dashboardconfig.hpp:35", + "CONFIG declaration: qreal ambientOpacity = 0.30" + ], + [ + "shell/modules/nexus/pages/panels/DashboardPanel.qml:216", + "shipped Nexus control (StepperRow)" + ] + ] + }, { "name": "setDashboardDragThreshold", "path": "dashboard.dragThreshold", @@ -4610,7 +4322,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/dashboardconfig.hpp:36", + "shell/plugin/src/Caelestia/Config/dashboardconfig.hpp:39", "CONFIG declaration: int dragThreshold = 50" ], [ @@ -4658,7 +4370,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/dashboardconfig.hpp:37", + "shell/plugin/src/Caelestia/Config/dashboardconfig.hpp:40", "CONFIG declaration: int hoverThickness = 10" ], [ @@ -4682,7 +4394,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/dashboardconfig.hpp:38", + "shell/plugin/src/Caelestia/Config/dashboardconfig.hpp:41", "CONFIG declaration: int hoverWidth = 50" ], [ @@ -4730,7 +4442,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/dashboardconfig.hpp:34", + "shell/plugin/src/Caelestia/Config/dashboardconfig.hpp:37", "CONFIG declaration: int mediaUpdateInterval = 500" ], [ @@ -4898,7 +4610,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/dashboardconfig.hpp:35", + "shell/plugin/src/Caelestia/Config/dashboardconfig.hpp:38", "CONFIG declaration: int resourceUpdateInterval = 1000" ], [ @@ -4926,7 +4638,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/dashboardconfig.hpp:32", + "shell/plugin/src/Caelestia/Config/dashboardconfig.hpp:33", "CONFIG declaration: bool showClockSeconds = false" ], [ @@ -5012,7 +4724,7 @@ "path": "dashboard.showTerminal", "group": "dashboard", "kind": "bool", - "default": true, + "default": false, "minimum": null, "maximum": null, "step": null, @@ -5022,8 +4734,8 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/dashboardconfig.hpp:28", - "CONFIG declaration: bool showTerminal = true" + "shell/plugin/src/Caelestia/Config/dashboardconfig.hpp:29", + "CONFIG declaration: bool showTerminal = false" ], [ "shell/modules/nexus/pages/panels/DashboardPanel.qml:167", @@ -5070,7 +4782,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/dashboardconfig.hpp:31", + "shell/plugin/src/Caelestia/Config/dashboardconfig.hpp:32", "CONFIG declaration: bool useMediaShapes = false" ], [ @@ -5094,7 +4806,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/sidebarconfig.hpp:13", + "shell/plugin/src/Caelestia/Config/sidebarconfig.hpp:17", "CONFIG declaration: int grabWidth = 12" ], [ @@ -5118,7 +4830,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/sidebarconfig.hpp:12", + "shell/plugin/src/Caelestia/Config/sidebarconfig.hpp:16", "CONFIG declaration: int dragThreshold = 50" ], [ @@ -5142,7 +4854,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/sidebarconfig.hpp:11", + "shell/plugin/src/Caelestia/Config/sidebarconfig.hpp:15", "CONFIG declaration: bool enabled = true" ], [ @@ -5292,7 +5004,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/generalconfig.hpp:70", + "shell/plugin/src/Caelestia/Config/generalconfig.hpp:72", "CONFIG declaration: bool checkUpdates = true" ], [ @@ -5460,7 +5172,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/serviceconfig.hpp:82", + "shell/plugin/src/Caelestia/Config/serviceconfig.hpp:105", "CONFIG declaration: bool arpcCaelestiaInfo = false" ], [ @@ -5484,7 +5196,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/serviceconfig.hpp:71", + "shell/plugin/src/Caelestia/Config/serviceconfig.hpp:94", "CONFIG declaration: bool arpcEnabled = false" ], [ @@ -5508,7 +5220,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/serviceconfig.hpp:84", + "shell/plugin/src/Caelestia/Config/serviceconfig.hpp:107", "CONFIG declaration: int arpcIdleTimeout = 0" ], [ @@ -5536,7 +5248,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/serviceconfig.hpp:83", + "shell/plugin/src/Caelestia/Config/serviceconfig.hpp:106", "CONFIG declaration: bool arpcManualOverride = false" ], [ @@ -5560,7 +5272,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/serviceconfig.hpp:78", + "shell/plugin/src/Caelestia/Config/serviceconfig.hpp:101", "CONFIG declaration: bool arpcSteamAutoDetect = false" ], [ @@ -5584,7 +5296,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/serviceconfig.hpp:51", + "shell/plugin/src/Caelestia/Config/serviceconfig.hpp:65", "CONFIG declaration: qreal audioIncrement = 0.1" ], [ @@ -5612,7 +5324,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/serviceconfig.hpp:59", + "shell/plugin/src/Caelestia/Config/serviceconfig.hpp:77", "CONFIG declaration: bool autoSchemeEnabled = false" ], [ @@ -5639,7 +5351,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/serviceconfig.hpp:60", + "shell/plugin/src/Caelestia/Config/serviceconfig.hpp:78", "CONFIG declaration: QString autoSchemeMode = u\"solar\"_s" ], [ @@ -5663,7 +5375,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/serviceconfig.hpp:52", + "shell/plugin/src/Caelestia/Config/serviceconfig.hpp:66", "CONFIG declaration: qreal brightnessIncrement = 0.1" ], [ @@ -5695,7 +5407,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/serviceconfig.hpp:37", + "shell/plugin/src/Caelestia/Config/serviceconfig.hpp:48", "CONFIG declaration: caelestia::config::ClockFormat::Enum clockFormat = ClockFormat::Auto" ], [ @@ -5722,7 +5434,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/serviceconfig.hpp:31", + "shell/plugin/src/Caelestia/Config/serviceconfig.hpp:42", "CONFIG declaration: caelestia::config::DataUnit::Enum dataUnits = DataUnit::Binary" ], [ @@ -5751,7 +5463,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/serviceconfig.hpp:49", + "shell/plugin/src/Caelestia/Config/serviceconfig.hpp:60", "CONFIG declaration: QString gpuType = QString()" ], [ @@ -5779,7 +5491,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/serviceconfig.hpp:53", + "shell/plugin/src/Caelestia/Config/serviceconfig.hpp:67", "CONFIG declaration: qreal maxVolume = 1.0" ], [ @@ -5812,7 +5524,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/serviceconfig.hpp:30", + "shell/plugin/src/Caelestia/Config/serviceconfig.hpp:41", "CONFIG declaration: caelestia::config::TemperatureUnit::Enum sensorUnits = TemperatureUnit::Celsius" ], [ @@ -5836,7 +5548,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/serviceconfig.hpp:54", + "shell/plugin/src/Caelestia/Config/serviceconfig.hpp:68", "CONFIG declaration: bool smartScheme = true" ], [ @@ -5860,7 +5572,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/serviceconfig.hpp:50", + "shell/plugin/src/Caelestia/Config/serviceconfig.hpp:61", "CONFIG declaration: int visualiserBars = 60" ], [ @@ -5889,7 +5601,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/serviceconfig.hpp:29", + "shell/plugin/src/Caelestia/Config/serviceconfig.hpp:40", "CONFIG declaration: caelestia::config::TemperatureUnit::Enum weatherUnits = TemperatureUnit::Auto" ], [ @@ -5913,7 +5625,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:69", + "shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:70", "CONFIG declaration: bool autoEnable = true" ], [ @@ -5937,7 +5649,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:66", + "shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:67", "CONFIG declaration: bool disableDesktopLyrics = true" ], [ @@ -5961,7 +5673,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:59", + "shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:60", "CONFIG declaration: bool disableHyprlandAnimations = true" ], [ @@ -5985,7 +5697,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:60", + "shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:61", "CONFIG declaration: bool disableHyprlandBlur = true" ], [ @@ -6009,7 +5721,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:61", + "shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:62", "CONFIG declaration: bool disableHyprlandGaps = true" ], [ @@ -6033,7 +5745,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:62", + "shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:63", "CONFIG declaration: bool disableHyprlandShadows = true" ], [ @@ -6057,7 +5769,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:63", + "shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:64", "CONFIG declaration: bool disableShellTransparency = true" ], [ @@ -6081,7 +5793,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:65", + "shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:66", "CONFIG declaration: bool disableToastTransparency = true" ], [ @@ -6105,7 +5817,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:67", + "shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:68", "CONFIG declaration: bool disableVisualizer = true" ], [ @@ -6129,7 +5841,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:64", + "shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:65", "CONFIG declaration: bool disableWindowTransparency = true" ], [ @@ -6153,7 +5865,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:81", + "shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:82", "CONFIG declaration: int maxToasts = 4" ], [ @@ -6177,7 +5889,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:87", + "shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:88", "CONFIG declaration: bool showGifRecorder = true" ], [ @@ -6201,7 +5913,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:85", + "shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:86", "CONFIG declaration: bool showKeepAwake = true" ], [ @@ -6225,7 +5937,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:88", + "shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:90", "CONFIG declaration: bool showQuickToggles = true" ], [ @@ -6249,7 +5961,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:86", + "shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:87", "CONFIG declaration: bool showScreenRecorder = true" ], [ @@ -6373,7 +6085,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:31", + "shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:32", "CONFIG declaration: bool nightLightChanged = true" ], [ @@ -6397,7 +6109,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:32", + "shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:33", "CONFIG declaration: bool transparency = false" ], [ @@ -6421,7 +6133,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:33", + "shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:34", "CONFIG declaration: qreal transparencyBase = 0.85" ], [ @@ -6445,7 +6157,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:78", + "shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:79", "CONFIG declaration: int dragThreshold = 50" ], [ @@ -6469,7 +6181,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:76", + "shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:77", "CONFIG declaration: bool enabled = true" ], [ @@ -6493,7 +6205,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:79", + "shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:80", "CONFIG declaration: int hoverThickness = 10" ], [ @@ -6517,7 +6229,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:80", + "shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:81", "CONFIG declaration: int hoverWidth = 50" ], [ @@ -6541,7 +6253,7 @@ "nouns": [], "citations": [ [ - "shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:77", + "shell/plugin/src/Caelestia/Config/utilitiesconfig.hpp:78", "CONFIG declaration: bool showOnHover = true" ], [ @@ -6976,6 +6688,10 @@ "path": "ai.snapToDefaultOllama", "reason": "[ai-provider-selfconfig] AI-provider self-configuration (models/providers/accounts): the assistant must not reconfigure its own plumbing; the Nexus AiSettingsPage owns these" }, + { + "path": "appearance.anim.enabled", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, { "path": "appearance.animDurations.expressiveDefaultEffects", "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" @@ -7068,6 +6784,10 @@ "path": "appearance.font.clock", "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" }, + { + "path": "appearance.font.followSystemScale", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, { "path": "appearance.font.icon.family", "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" @@ -7268,10 +6988,22 @@ "path": "background.desktopLyrics.shadow.opacity", "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" }, + { + "path": "background.disableQuickshellDesktop", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, { "path": "background.enabled", "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" }, + { + "path": "background.materialYouIconsVibrancy", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "background.visualiser.profile", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, { "path": "bar.clock.centerClock", "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" @@ -7284,6 +7016,10 @@ "path": "bar.dock.pinnedApps", "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" }, + { + "path": "bar.dock.windowGrouping", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, { "path": "bar.entries", "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" @@ -7340,6 +7076,42 @@ "path": "bar.greeter.slideshowText", "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" }, + { + "path": "bar.keepawake.autoHide", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "bar.keepawake.showActiveChip", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "bar.media.autoHide", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "bar.media.background", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "bar.media.excludedSources", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "bar.media.inverted", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "bar.media.maxTitleLength", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "bar.media.showTitle", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "bar.media.showVisualiser", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, { "path": "bar.perElementFontScale", "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" @@ -7348,10 +7120,26 @@ "path": "bar.perElementPreviewScale", "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" }, + { + "path": "bar.performance.pill", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "bar.performance.pillStyle", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, { "path": "bar.performance.showText", "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" }, + { + "path": "bar.performance.widgetShowText", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "bar.performance.widgetStyle", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, { "path": "bar.popouts.clock", "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" @@ -7392,6 +7180,10 @@ "path": "bar.previewFontScales.lockStatus", "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" }, + { + "path": "bar.previewFontScales.media", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, { "path": "bar.previewFontScales.network", "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" @@ -7420,6 +7212,22 @@ "path": "bar.previewScales.kblayout", "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" }, + { + "path": "bar.previewScales.media", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "bar.screencapture.showFolders", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "bar.screencapture.showRecord", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "bar.screencapture.showShots", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, { "path": "bar.status.peripheralBatteryExcluded", "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" @@ -7464,10 +7272,18 @@ "path": "bar.status.showPeripheralBattery", "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" }, + { + "path": "bar.tray.alwaysVisible", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, { "path": "bar.tray.hiddenIcons", "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" }, + { + "path": "bar.tray.order", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, { "path": "bar.workspaces.activeLabel", "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" @@ -7508,6 +7324,10 @@ "path": "dashboard.showHyprlandSplash", "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" }, + { + "path": "dashboard.showNotes", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, { "path": "enabled", "reason": "[master-switch] ConfigRoot master switch — a bad write disables the entire shell" @@ -7516,6 +7336,14 @@ "path": "general.apps.audio", "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" }, + { + "path": "general.apps.browser", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "general.apps.editor", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, { "path": "general.apps.explorer", "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" @@ -7572,6 +7400,10 @@ "path": "launcher.actionPrefix", "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" }, + { + "path": "launcher.browseLayout", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, { "path": "launcher.favouriteApps", "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" @@ -7588,6 +7420,10 @@ "path": "launcher.hiddenApps", "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" }, + { + "path": "launcher.nameOverflow", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, { "path": "launcher.specialPrefix", "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" @@ -7624,6 +7460,14 @@ "path": "nexus.wallpapersPerRow", "reason": "[complex-control] the shipped control is '(no control; read-only Repeater model)', not a scalar setter" }, + { + "path": "notifs.focusAllowlist", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "notifs.focusEnabled", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, { "path": "paths.cacheDir", "reason": "[filesystem-paths] filesystem path redirection; the wallpaper/CLI surface owns this" @@ -7644,6 +7488,14 @@ "path": "paths.noNotifsPic", "reason": "[filesystem-paths] filesystem path redirection; the wallpaper/CLI surface owns this" }, + { + "path": "paths.recordingsDir", + "reason": "[filesystem-paths] filesystem path redirection; the wallpaper/CLI surface owns this" + }, + { + "path": "paths.screenshotsDir", + "reason": "[filesystem-paths] filesystem path redirection; the wallpaper/CLI surface owns this" + }, { "path": "paths.sessionGif", "reason": "[filesystem-paths] filesystem path redirection; the wallpaper/CLI surface owns this" @@ -7700,14 +7552,30 @@ "path": "services.bluetoothAutoReconnectDevices", "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" }, + { + "path": "services.calendarDays", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, { "path": "services.defaultPlayer", "reason": "[dynamic-enum] the SelectRow's value list is dynamic, numeric-coded without per-value ids, or not a frozen enumeration" }, + { + "path": "services.hotspotPassword", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "services.hotspotSsid", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, { "path": "services.lyricsBackend", "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" }, + { + "path": "services.quickShareAutoStart", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, { "path": "services.useFahrenheit", "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" @@ -7724,6 +7592,10 @@ "path": "services.useTwelveHourClock", "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" }, + { + "path": "services.visualiserInput", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, { "path": "services.wallhavenApiKey", "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" @@ -7764,6 +7636,18 @@ "path": "session.icons.shutdown", "reason": "[session-icons] icon-name strings with no shipped range/format control" }, + { + "path": "sidebar.defaultTab", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "sidebar.pinned", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "sidebar.width", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, { "path": "sizes.bar.audioWidth", "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" @@ -7780,6 +7664,10 @@ "path": "sizes.bar.kbLayoutWidth", "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" }, + { + "path": "sizes.bar.networkVpnListMaxHeight", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, { "path": "sizes.bar.networkWidth", "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" @@ -8100,6 +7988,18 @@ "path": "utilities.quickToggles", "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" }, + { + "path": "utilities.quickTogglesCustomOrder", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "utilities.quickTogglesPerPage", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, + { + "path": "utilities.showQuickShare", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, { "path": "utilities.toasts.audioInputChanged", "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" @@ -8120,6 +8020,10 @@ "path": "utilities.toasts.dndChanged", "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" }, + { + "path": "utilities.toasts.dndWhileStreaming", + "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" + }, { "path": "utilities.toasts.kbLayoutChanged", "reason": "[no-shipped-control] no Nexus control touches this leaf; not exposed without a UI-grounded citation" @@ -8245,7 +8149,11 @@ "value": 0.25 }, { - "tool": "setAmbientColor", + "tool": "setOverviewAmbientColor", + "value": false + }, + { + "tool": "setDashboardAmbientColor", "value": false }, { @@ -8353,8 +8261,16 @@ ] }, { - "path": "appearance.ambientColor", - "when": "appearance.ambientColor == true and _light == true", + "path": "overview.ambientColor", + "when": "overview.ambientColor == true and _light == true", + "answer": "The ambient glow is configured ON but is currently hidden, because ambient glow only renders in dark mode — it gates on ambientColor && !light ({cite}).", + "cites": [ + "shell/components/effects/AmbientGlow.qml:34" + ] + }, + { + "path": "dashboard.ambientColor", + "when": "dashboard.ambientColor == true and _light == true", "answer": "The ambient glow is configured ON but is currently hidden, because ambient glow only renders in dark mode — it gates on ambientColor && !light ({cite}).", "cites": [ "shell/components/effects/AmbientGlow.qml:34" diff --git a/plugins/caelestia-assistant/assistant/capabilities/settings/build_registry.py b/plugins/caelestia-assistant/assistant/capabilities/settings/build_registry.py index 1c184e1..7ef9599 100755 --- a/plugins/caelestia-assistant/assistant/capabilities/settings/build_registry.py +++ b/plugins/caelestia-assistant/assistant/capabilities/settings/build_registry.py @@ -22,7 +22,7 @@ from .enumerate import enumerate_leaves from .ui_ranges_data import UI_RANGES -REPO_COMMIT = "70ee7da115fde9012e28e393c73d274f55bd2dd7" +REPO_COMMIT = "c72ef2ee3e3bb2efe265b7040e3efa89aeefc757" _ENUM_NOTE = re.compile(r"enum ([A-Za-z0-9_]+)\s*:\s*([A-Za-z0-9_|]+)") diff --git a/plugins/caelestia-assistant/assistant/capabilities/settings/curations.py b/plugins/caelestia-assistant/assistant/capabilities/settings/curations.py index f1cff54..174551a 100755 --- a/plugins/caelestia-assistant/assistant/capabilities/settings/curations.py +++ b/plugins/caelestia-assistant/assistant/capabilities/settings/curations.py @@ -72,8 +72,6 @@ "appearance.blurMask", "appearance.pitchBlack", "appearance.islands", - "appearance.ambientColor", - "appearance.ambientOpacity", "appearance.transparency.enabled", "appearance.transparency.base", "appearance.transparency.layers", @@ -561,8 +559,16 @@ def extra_citations_for(path: str) -> List[Tuple[str, str]]: "cites": ["shell/plugin/src/Caelestia/Config/appearanceconfig.cpp:209"], }, { - "path": "appearance.ambientColor", - "when": "appearance.ambientColor == true and _light == true", + "path": "overview.ambientColor", + "when": "overview.ambientColor == true and _light == true", + "answer": "The ambient glow is configured ON but is currently hidden, " + "because ambient glow only renders in dark mode — it gates " + "on ambientColor && !light ({cite}).", + "cites": ["shell/components/effects/AmbientGlow.qml:34"], + }, + { + "path": "dashboard.ambientColor", + "when": "dashboard.ambientColor == true and _light == true", "answer": "The ambient glow is configured ON but is currently hidden, " "because ambient glow only renders in dark mode — it gates " "on ambientColor && !light ({cite}).", @@ -651,7 +657,8 @@ def extra_citations_for(path: str) -> List[Tuple[str, str]]: "calls": [ ["setBlurEnabled", False], ["setAnimationSpeed", 0.25], - ["setAmbientColor", False], + ["setOverviewAmbientColor", False], + ["setDashboardAmbientColor", False], ["setWallpaperRecolor", False], ], }, diff --git a/plugins/caelestia-assistant/assistant/capabilities/settings/ui_ranges_data.py b/plugins/caelestia-assistant/assistant/capabilities/settings/ui_ranges_data.py index 81551c1..0ce85a1 100755 --- a/plugins/caelestia-assistant/assistant/capabilities/settings/ui_ranges_data.py +++ b/plugins/caelestia-assistant/assistant/capabilities/settings/ui_ranges_data.py @@ -21,8 +21,10 @@ "ai.enableOpenrouter": {"control": 'ToggleRow', "page": 'AI Assistant', "file": 'shell/modules/nexus/pages/AiSettingsPage.qml', "line": 614}, "ai.showCaelestiaMode": {"control": 'ToggleRow', "page": 'Sidebar', "file": 'shell/modules/nexus/pages/panels/SidebarPanel.qml', "line": 75}, "ai.showNews": {"control": 'ToggleRow', "page": 'Sidebar', "file": 'shell/modules/nexus/pages/panels/SidebarPanel.qml', "line": 66}, - "appearance.ambientColor": {"control": 'ToggleRow (enabled only when !Colours.light)', "page": 'Theme & Effects', "file": 'shell/modules/nexus/pages/wallandstyle/AppearancePage.qml', "line": 158}, - "appearance.ambientOpacity": {"control": 'SliderRow', "min": 0, "max": 1, "note": 'step: wheel=services.audioIncrement (enabled: ambientColor && !Colours.light)', "page": 'Theme & Effects', "file": 'shell/modules/nexus/pages/wallandstyle/AppearancePage.qml', "line": 167}, + "dashboard.ambientColor": {"control": 'ToggleRow (enabled only when !Colours.light)', "page": 'Dashboard', "file": 'shell/modules/nexus/pages/panels/DashboardPanel.qml', "line": 206}, + "dashboard.ambientOpacity": {"control": 'StepperRow', "min": 0, "max": 1, "step": 0.05, "page": 'Dashboard', "file": 'shell/modules/nexus/pages/panels/DashboardPanel.qml', "line": 216}, + "overview.ambientColor": {"control": 'ToggleRow (enabled only when !Colours.light)', "page": 'Overview', "file": 'shell/modules/nexus/pages/panels/OverviewPanel.qml', "line": 214}, + "overview.ambientOpacity": {"control": 'StepperRow', "min": 0, "max": 1, "step": 0.05, "page": 'Overview', "file": 'shell/modules/nexus/pages/panels/OverviewPanel.qml', "line": 221}, "appearance.anim.durations.scale": {"control": 'StepperRow', "min": 0.25, "max": 4, "step": 0.05, "page": 'Theme & Effects', "file": 'shell/modules/nexus/pages/wallandstyle/AppearancePage.qml', "line": 316}, "appearance.blur": {"control": 'ToggleRow (enabled: transparency.enabled && !better_blur_dx)', "page": 'Theme & Effects', "file": 'shell/modules/nexus/pages/wallandstyle/AppearancePage.qml', "line": 222}, "appearance.blurMask": {"control": 'ToggleRow (enabled: transparency.enabled && blur)', "page": 'Theme & Effects', "file": 'shell/modules/nexus/pages/wallandstyle/AppearancePage.qml', "line": 246}, From 241f2ab29a67a152a2416a9b844ee0f436164290 Mon Sep 17 00:00:00 2001 From: ladybug-me <165172025+ladybug-me@users.noreply.github.com> Date: Sat, 24 Oct 2026 15:41:36 +0530 Subject: [PATCH 10/10] chore: update repository commit reference in settings registry and tools definition --- .../caelestia-assistant/assistant/adapters/caelestia/tools.json | 2 +- .../assistant/capabilities/settings/build_registry.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/plugins/caelestia-assistant/assistant/adapters/caelestia/tools.json b/plugins/caelestia-assistant/assistant/adapters/caelestia/tools.json index a08764b..32bdc05 100644 --- a/plugins/caelestia-assistant/assistant/adapters/caelestia/tools.json +++ b/plugins/caelestia-assistant/assistant/adapters/caelestia/tools.json @@ -1,7 +1,7 @@ { "meta": { "generator": "assistant.capabilities.settings.build_registry", - "repo_commit": "c72ef2ee3e3bb2efe265b7040e3efa89aeefc757", + "repo_commit": "9496cc3aab39296ed19c76c9e3931f63caa45e2e", "notes": "Validation ranges/enums adopted exactly from the shipped Nexus controls (ui_ranges_data.py) and the C++ enum declarations; upstream declares no numeric bounds in the settings schema (type-only hook). not_exposed records every scalar leaf without a tool, with its reason.", "tool_count": 261, "group_counts": { diff --git a/plugins/caelestia-assistant/assistant/capabilities/settings/build_registry.py b/plugins/caelestia-assistant/assistant/capabilities/settings/build_registry.py index 7ef9599..da38155 100755 --- a/plugins/caelestia-assistant/assistant/capabilities/settings/build_registry.py +++ b/plugins/caelestia-assistant/assistant/capabilities/settings/build_registry.py @@ -22,7 +22,7 @@ from .enumerate import enumerate_leaves from .ui_ranges_data import UI_RANGES -REPO_COMMIT = "c72ef2ee3e3bb2efe265b7040e3efa89aeefc757" +REPO_COMMIT = "9496cc3aab39296ed19c76c9e3931f63caa45e2e" _ENUM_NOTE = re.compile(r"enum ([A-Za-z0-9_]+)\s*:\s*([A-Za-z0-9_|]+)")