refactor(afk-sleep-work): compact skill while preserving all directives and tables

This commit is contained in:
Bluscream committed 2026-10-02 00:41:18 +02:00
1 parent 87a456cd31
commit 289db75cb6
1 file changed
+69 -241
+69 -241
View File
@@ -1,41 +1,30 @@
--- ---
name: afk-sleep-work name: afk-sleep-work
description: >- description: >-
Use this skill when the user indicates they will be away, AFK, or sleeping, grants broad autonomous Use this skill when the user is away, AFK, or sleeping, grants broad autonomous execution authority,
execution authority, asks the agent to work continuously until tokens or objectives are exhausted, asks the agent to work continuously until tokens or objectives are exhausted, or delegates multi-phase
or delegates multi-phase tasks requiring unattended orchestration, safe tool provisioning, avoiding tasks requiring unattended orchestration, safe tool provisioning, avoiding polling traps, respecting
polling traps, respecting token/subscription margins (the "last breath" rule), and bypassing or driving GUI launchers. budget margins (the "last breath" rule), and bypassing or driving GUI launchers.
--- ---
# Unattended & Autonomous Execution (AFK / Sleep Work) # Unattended & Autonomous Execution (AFK / Sleep Work)
How to operate safely, productively, and continuously when the user steps away and delegates When working unattended, the interactive loop is gone. Every decision, recovery, tool provisioning,
broad execution authority to the agent. and verification step must proceed autonomously without risking host stability or leaving broken state.
When a user says they will be AFK or going to sleep, they are relinquishing the interactive
feedback loop. Every decision, recovery, tool installation, and verification gate must be
orchestrated autonomously until the goal is achieved or budget limits are reached.
--- ---
## 1. The Autonomous Execution Contract ## 1. Autonomous Execution Contract
When working unattended, the agent assumes full responsibility for forward momentum and system 1. **Keep Moving Forward:** Do not stop for minor ambiguities. Investigate, formulate hypotheses, test, and pivot independently.
preservation. Three primary rules govern this mode: 2. **First, Do No Harm:** Broad authority is never permission to fill disks, clobber system packages, reboot, or risk data loss.
3. **Leave a Transparent Audit Trail:** Maintain an orderly checkpoint detailing completed work, failures, state, and exact next steps.
1. **Keep Moving Forward:** Do not stop to ask clarifying questions about minor ambiguities or
blockers that can be resolved through investigation, trial hypotheses, or alternative strategies.
2. **First, Do No Harm:** Broad authority is **not** permission to degrade the host, saturate
resources, clobber system packages, or risk data loss.
3. **Leave a Transparent Audit Trail:** When the user returns, they must be able to inspect an
orderly checkpoint detailing what was done, what succeeded, what failed, and where state currently sits.
--- ---
## 2. Trap Avoidance: Loops, Timeouts & Interactive Prompts ## 2. Trap Avoidance: Loops, Timeouts & Interactive Prompts
The most common failure mode during unattended execution is getting wedged in a blocking state, The primary failure mode of unattended runs is wedging on a blocking command.
consuming time or tokens without making progress.
### Never write polling wait loops ### Never write polling wait loops
@@ -44,255 +33,94 @@ consuming time or tokens without making progress.
> (see [`code-languages/bash.md` §3](skills-public/code-languages/bash.md)). > (see [`code-languages/bash.md` §3](skills-public/code-languages/bash.md)).
> An unattended loop that never satisfies its exit condition hangs the session indefinitely. > An unattended loop that never satisfies its exit condition hangs the session indefinitely.
- **Use built-in blocking or notification mechanisms:** Prefer CLI flags like `--wait`, - **Use tool-native blocking:** Flags like `--wait`, `--no-detach`, or task completion events over polling.
`--no-detach`, or dedicated background task status notifications over manual polling. - **Enforce hard timeouts:** Wrap uncertain or long-running commands: `timeout 300s <command>`.
- **Enforce hard timeouts:** Every long-running, external, or uncertain command must be wrapped - **Mandatory non-interactive flags:** Supply `-y`, `--yes`, `--batch`, `--headless`, `CI=1`, or
in a timeout: `DEBIAN_FRONTEND=noninteractive`. Never let a tool prompt `[y/N]` (see [`cli-tooling.md` §2](skills-public/cli-tooling.md)).
```bash - **Bounded retries with hypothesis variation:** Never rerun the same failing command unchanged. Cap retries
timeout 300s my-command --batch at 3 attempts; each must test a distinct hypothesis (flags, config, path, or alternative strategy).
``` If all fail, record diagnostics and pivot.
If a process exceeds its expected runtime, terminate it, record the timeout, and inspect logs.
### Non-interactive flags are mandatory
Commands that pause for user confirmation (`[y/N]`) will stall indefinitely when the user is away:
- Always supply non-interactive switches: `-y`, `--yes`, `--non-interactive`, `--batch`,
`--headless`, or environment flags like `CI=1` and `DEBIAN_FRONTEND=noninteractive`.
- Consult [`cli-tooling.md` §2](skills-public/cli-tooling.md) before invoking unfamiliar tools to ensure
targets and arguments are explicitly declared rather than prompted.
### Bounded retries with hypothesis variation
If an automated build, test, or patch fails:
- **Do not retry the exact same failing command** hoping for a different outcome.
- Limit automated retries on any single problem to a fixed ceiling (e.g. 3 attempts).
- Each retry **must test a distinct hypothesis** (different compiler flag, altered configuration,
corrected dependency path, or alternative implementation strategy).
- If 3 successive attempts fail, abandon that branch, record the detailed diagnostic log, and
pivot to an alternative route or proceed to the next independent task.
--- ---
## 3. Host Safety & Resource Budgets ("Do No Harm") ## 3. Host Safety & Resource Budgets ("Do No Harm")
Unattended access requires strict operational discipline to ensure the machine remains stable, - **Storage & Disk:** Check `df -h <path>` before large fetches or builds. Keep ≥15–20% disk headroom. Clean up
responsive, and intact. downloaded archives (`.tar.gz`, `.zip`, `.iso`), temp build trees, and intermediate dumps.
- **OS & Package Integrity:** Never run blanket host package upgrades or installs (`sudo dnf`, `sudo apt`,
### Storage & disk preservation `pacman -Syu`). Isolate toolchains inside containers (e.g. [`distrobox-buildbox-dev.md`](skills-private/distrobox-buildbox-dev.md),
Docker) or user-space paths (`~/.local/bin/`, venvs).
Running out of disk space can corrupt databases, break desktop sessions, and crash background daemons. - **Process Safety:** Never execute `shutdown`, `reboot`, or kill display servers (`wayland`, `xorg`). Never
issue broad `pkill python` or `killall node` that can kill the agent or IDE. Target specific PIDs or match full paths.
- **Check free space first:** Run `df -h <target_path>` before downloading large archives, - **CPU & Memory:** Cap multi-threaded jobs (`-j$(nproc --ignore=2)`), `nice -n 10` heavy builds, and monitor
compiling large codebases, or unpacking toolchains. `free -m` to prevent kernel OOM panics.
- **Never saturate drives:** Ensure at least 15–20% of disk space remains free on the root and
working filesystems.
- **Clean intermediate artifacts:** Delete downloaded archive files (`.tar.gz`, `.zip`, `.iso`),
temporary unpack directories, and oversized intermediate build caches once installation or
verification is complete.
- **Log rotation and dump bounds:** Prevent automated runs from generating unbounded log files or
gigabyte-scale core dumps.
### OS and system package integrity
- **Never mutate or override host system packages:** Do not execute blanket system package manager
upgrades or installs (`sudo dnf install`, `sudo apt-get upgrade`, `pacman -Syu`) that replace
host libraries, alter desktop drivers, or conflict with system-level package trees.
- **Isolate in containers or user space:**
- Prefer dedicated build containers, chroots, or isolated environments (such as
[`distrobox-buildbox-dev.md`](skills-private/distrobox-buildbox-dev.md), Docker, or Podman) for
compilers, toolchains, and experimental packages.
- For user-level binaries, install into user-scoped paths (`~/.local/bin/`, `~/.local/share/`,
or project-local virtual environments).
- Never run arbitrary third-party build scripts with elevated root privileges unless explicitly
demanded by the architecture and verified safe.
### Process and lifecycle safety
- **Strictly prohibited operations:**
- Never invoke `shutdown`, `reboot`, `systemctl poweroff`, or `init 0/6`.
- Never kill the host desktop session, display server (`wayland`, `xorg`), or user window manager.
- Never issue broad `pkill` or `killall` commands with generic names (e.g. `pkill python` or
`killall node`) that might terminate the agent itself, IDE sidecars, or unrelated user processes.
- Always target specific PIDs or match full command lines (`pkill -f ...`).
### CPU, memory, and bandwidth etiquette
- **Do not saturate all CPU cores:** When invoking multi-threaded builds (`make`, `ninja`, `cargo`),
cap jobs to `$(nproc --ignore=2)` or use `nice -n 10` to avoid starving interactive desktop
responsiveness or audio subsystems.
- **Monitor memory footprints:** For heavy memory operations (e.g. large reverse engineering suites,
AST parsing, heavy link steps), monitor RAM with `free -m` and kill runaway tasks before triggering
the kernel OOM killer.
--- ---
## 4. Tool & Dependency Provisioning in Isolation ## 4. Tool Provisioning: Containerized & Headless First
Autonomous work often demands tools not yet present on the system (e.g. decompilers, disassemblers, 1. **Verify existence first:** Run `command -v <tool>` before downloading.
symbol analyzers, cross-compilers, or profiling utilities). 2. **Provision in isolation:** Prefer existing repo toolchains > build containers (Distrobox/Docker) >
standalone binaries (`~/.local/bin/`) > user-scoped package managers (`cargo install`, `pip install --user`).
### Check existence before fetching 3. **Headless / CLI over GUI:** Never launch heavy graphical interfaces when headless/batch modes exist:
- *Ghidra:* `analyzeHeadless <proj_dir> <proj_name> -import <bin> -postScript <script.py>`
Always verify if a tool or functional equivalent is already available in `$PATH`, in an existing - *Packets:* `tshark` / `tcpdump` instead of GUI Wireshark
container, or in user directories before attempting to download: - *Debuggers:* `gdb -batch -ex ...` or `lldb --batch -o ...`
```bash
command -v <tool> || which <tool>
```
### Preferred provisioning hierarchy
When a missing utility or dependency is required:
1. **Local Project / Toolchains:** Look for existing scripts or submodule toolchains inside the repo.
2. **Isolated Build Containers:** Run or install the tool within a development container or
Distrobox instance, keeping the host clean.
3. **Self-Contained User-Space Binaries:** Download official prebuilt standalone binaries, AppImages,
or portable zip releases into `~/.local/bin/` or a project scratch folder.
4. **Isolated Package Managers:** Use language-specific or user-space package managers (`cargo install`,
`pip install --user`, `npm install --no-save`, `go install`) scoped to non-root directories.
### Headless & scriptable mode over GUI
When using heavyweight tools that typically feature GUIs (such as Ghidra, IDA, Wireshark, or
debuggers):
- **Always prioritize headless/CLI mode:** Use headless batch scripts, CLI entrypoints, or
Python/Java/Lua automation APIs rather than starting graphical interfaces.
- *Example (Ghidra):* Run `analyzeHeadless <project_dir> <project_name> -import <binary> -postScript <script.py>`
rather than launching the Swing GUI.
- *Example (Network/Packets):* Use `tshark` or `tcpdump` instead of launching GUI Wireshark.
- *Example (Debugging):* Run `gdb -batch -ex ...` or `lldb --batch -o ...`.
--- ---
## 5. Launchers & GUI Automation: Bypassing vs. Driving ## 5. Launchers & GUI Automation: Bypass vs. Drive
Complex applications, game engines, and test suites often wrap their executables behind splash When targets are shielded by splash launchers, web wrappers, or login dialogs:
launchers, web views, or login modals. When running unattended, handle them systematically.
``` | Priority | Strategy | Action |
┌────────────────────────────────────────────────────────┐ | :--- | :--- | :--- |
│ 1. Direct Executable Bypass (Preferred) │ | **1. Direct Bypass (Best)** | Run child binary directly | Inspect `ps aux` or wrapper configs while the launcher runs to extract child binary path and arguments, then execute it directly. |
│ Inspect process args, run child binary directly │ | **2. CLI / Config Flags** | Suppress launcher UI | Pass switches like `-nosplash`, `-nolauncher`, `-batch`, `--skip-intro`, or set `SkipLauncher=true` in `.ini`/`.json` configs. |
└───────────────────────────┬────────────────────────────┘ | **3. GUI Automation (Fallback)** | Drive the window | Identify window (`xdotool`, `ydotool`, or desktop MCP), capture screenshot/dump, send keys/clicks, and verify state change with a timeout guard. |
│ (if blocked by DRM / IPC)
┌───────────────────────────▼────────────────────────────┐
│ 2. Command-Line Arguments & Flags │
│ Search for -nosplash, -nolauncher, --skip-intro │
└───────────────────────────┬────────────────────────────┘
│ (if GUI invocation mandatory)
┌───────────────────────────▼────────────────────────────┐
│ 3. Autonomous GUI Driving │
│ Locate window, simulate inputs, verify state change │
└────────────────────────────────────────────────────────┘
```
### Hierarchy of execution
1. **Direct Executable Bypass (Highest Priority):**
Launchers are usually thin wrappers around the real core engine or binary.
- Run the launcher once or inspect its script / configuration files to identify the real child
binary and its working directory.
- Inspect active processes (`ps aux | grep -i <app>` or `wmic process` under Wine/Windows) to
extract the exact command line and parameters passed from the launcher to the target process.
- Execute the target binary directly with those extracted parameters, bypassing the launcher UI
completely.
2. **Command-Line & Config Flags:**
If the launcher must be invoked, look for flags that suppress interactive prompts:
- Common bypass switches: `-nosplash`, `-nolauncher`, `-autostart`, `-batch`, `-silent`, `--skip-login`.
- Configuration files: Check configuration `.ini`, `.json`, or `.xml` files to toggle
`SkipLauncher=true` or set auto-connect / auto-load options.
3. **Driving the GUI (Fallback):**
If the launcher cannot be bypassed and requires a click or keyboard event to proceed:
- Identify the window using available window management or GUI automation tools
(e.g. `xdotool`, `ydotool`, or desktop MCP tools).
- Capture a screenshot or window dump to verify geometry and interactive button states.
- Dispatch the required input sequence (e.g. Enter, Space, or target coordinate click).
- **Immediately verify state transition:** Confirm the launcher window closes or the child
process spawns. Never assume input succeeded without checking process lists or window titles.
- Protect with a hard timeout so that an unexpected modal dialog does not block execution forever.
--- ---
## 6. Token & Subscription Exhaustion (The "Last Breath" Rule) ## 6. Budget Exhaustion, Runaway Logs & The "Last Breath" Rule
In unattended sessions, the execution lifecycle is bounded by context window size, agent token In unattended sessions, context window, token budgets, or subscription quotas will eventually exhaust.
budgets, subscription quotas, or harness timeouts. How the session winds down determines whether
the run is a success or leaves a broken system.
### Watch for approaching limits
Track execution consumption and context density where possible:
- If context length grows high or the harness signals approaching token/turn caps, prioritize
winding down over starting new initiatives.
- If rate limits, credit caps, or subscription tier resets are anticipated, prepare state so that
execution can pause cleanly and recover without corruption.
### Never start fragile tasks in your "last breath"
> [!CAUTION] > [!CAUTION]
> **The "Last Breath" Trap:** Never initiate an open-ended, non-atomic, or high-risk mutating > **The "Last Breath" Trap:** Never initiate an open-ended, non-atomic, or high-risk mutating operation
> operation when token budget, context window, or subscription quota are nearly exhausted. > when tokens, context, or quota are nearly depleted.
Rushing into a complex task with only a few turns or tokens remaining guarantees failure. If the Rushing into a complex task on a thin margin guarantees failure if the harness terminates or pauses
harness cuts execution off mid-flight — or freezes the agent until quota resets hours later — execution mid-flight:
unfinished work leaves the environment in a broken, unusable state: - **Corrupted source trees:** Half-applied multi-file refactors leaving syntax errors and broken builds.
- **Corrupted source trees:** Half-applied multi-file refactors that leave syntax errors and broken builds. - **Dangling locks:** Incomplete package or git locks (`.git/index.lock`, `/var/lib/dpkg/lock`).
- **Dangling locks:** Incomplete package installs holding `/var/lib/dpkg/lock`, active git index - **Uncommitted state:** Half-finished rebases, stashes, or uncommitted edits.
locks (`.git/index.lock`), or held database transactions. - **Zombie processes & runaway logs:** Background daemons, watchers, or detached tasks spewing debug output
- **Uncommitted state:** Unfinished rebases, stashes, or uncommitted modifications that confuse into unrotated log files, silently filling the disk while the agent is paused or waiting for quota.
subsequent runs or the user.
- **Zombie processes & runaway logs:** Orphaned background build daemons, file watchers, or detached
processes spewing infinite debug output into unrotated log files, silently exhausting disk space
while the agent is frozen or waiting for quota.
### The Controlled Landing protocol ### The Controlled Landing protocol
When budget, tokens, or turns drop below a comfortable margin (or when an operation cannot be When remaining budget or context drops below a safe margin:
guaranteed to finish and verify within the remaining budget): 1. **Halt scope expansion:** Do not start new goals or dependencies.
2. **Finish or roll back atomic edits:** Leave the repo in a compiling, testable state (`git checkout -- <file>` if incomplete).
1. **Stop scope expansion:** Refuse new goals, refactors, or dependency upgrades. 3. **Kill ephemeral processes & log streams:** Terminate background test runners, servers, watchers, and tasks redirecting output to unrotated files.
2. **Finish or roll back atomic units:** Complete the immediate atomic file edit or roll it back 4. **Run verification gates:** Verify `git status` and run quick build/lint checks.
cleanly (`git checkout -- <file>`) so the repository remains in a compiling, testable state. 5. **Commit atomic progress:** Save clean progress with conventional commits.
3. **Terminate ephemeral processes & log streams:** Kill all background test runners, scratch 6. **Write the recovery checkpoint:** Update the status log before the session halts.
servers, watcher daemons, temporary debuggers, and detached tasks redirecting stdout/stderr
to unrotated files.
4. **Run verification gates:** Confirm `git status` is clean or staged cleanly, and the build passes.
5. **Commit atomic progress:** Commit completed, verified units with conventional commit messages so
progress is never lost if the session terminates abruptly.
6. **Write the recovery checkpoint:** Explicitly document the exact resume instructions, active
hypotheses, and next planned action in the status artifact so either the user or the next agent
turn can resume seamlessly.
--- ---
## 7. Checkpointing & The "Wake-Up" Audit Trail ## 7. Checkpointing & The "Wake-Up" Audit Trail
Because the user is not present to monitor intermediate chatter, keep a consolidated record of Maintain a persistent status file (`PROGRESS.md` or session artifact) updated at each milestone:
progress.
### Write a live status checkpoint
Maintain a dedicated status file (e.g. `PROGRESS.md`, `AFK_WORK_LOG.md`, or a persistent artifact)
updated after every major milestone. The document should contain:
| Section | Contents | | Section | Contents |
| :--- | :--- | | :--- | :--- |
| **Objective** | The original task and current operational phase. | | **Objective** | Target goal and current operational phase. |
| **Completed Work** | Bulleted list of concrete accomplishments (code written, tests passing, tools configured). | | **Completed Work** | Bulleted list of verified accomplishments (code, passing tests, tools configured). |
| **Current State** | Active branch, git commit hash, build status, running daemons or services. | | **Current State** | Branch, commit hash, build status, active containers or services. |
| **Findings & Discoveries** | Key technical observations, reversed structs, discovered bugs, or API quirks. | | **Findings & Discoveries** | Key technical observations, reversed structs, or API quirks. |
| **Obstacles & Fallbacks** | Blockers encountered, strategies that failed (with brief reasons), and how the agent pivoted. | | **Obstacles & Fallbacks** | Failed attempts with concise explanations and how you pivoted. |
| **Harness / Budget State** | Token/quota state, whether work halted due to task completion or approaching budget limits. | | **Budget / Harness State** | Token/quota status; whether stopped by task completion or budget limits. |
| **Immediate Next Steps** | Exact command line or file target where the next session should pick up. | | **Immediate Next Steps** | Exact command line or target file for the next session to resume seamlessly. |
### Clean exit on budget exhaustion Conclude with a single clear summary pointing the returning user directly to this checkpoint.
When tokens, context, or scheduled runtime run out:
- Ensure the controlled landing steps above have been executed.
- Output a concise, unambiguous final summary pointing directly to the written checkpoint so the
user has immediate clarity upon waking up or returning.