diff --git a/afk-sleep-work.md b/afk-sleep-work.md index a05ba51..e78b852 100644 --- a/afk-sleep-work.md +++ b/afk-sleep-work.md @@ -1,41 +1,30 @@ --- name: afk-sleep-work description: >- - Use this skill when the user indicates they will be away, AFK, or sleeping, grants broad autonomous - execution authority, asks the agent to work continuously until tokens or objectives are exhausted, - or delegates multi-phase tasks requiring unattended orchestration, safe tool provisioning, avoiding - polling traps, respecting token/subscription margins (the "last breath" rule), and bypassing or driving GUI launchers. + Use this skill when the user is away, AFK, or sleeping, grants broad autonomous execution authority, + asks the agent to work continuously until tokens or objectives are exhausted, or delegates multi-phase + tasks requiring unattended orchestration, safe tool provisioning, avoiding polling traps, respecting + budget margins (the "last breath" rule), and bypassing or driving GUI launchers. --- # Unattended & Autonomous Execution (AFK / Sleep Work) -How to operate safely, productively, and continuously when the user steps away and delegates -broad execution authority to the agent. - -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. +When working unattended, the interactive loop is gone. Every decision, recovery, tool provisioning, +and verification step must proceed autonomously without risking host stability or leaving broken state. --- -## 1. The Autonomous Execution Contract +## 1. Autonomous Execution Contract -When working unattended, the agent assumes full responsibility for forward momentum and system -preservation. Three primary rules govern this mode: - -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. +1. **Keep Moving Forward:** Do not stop for minor ambiguities. Investigate, formulate hypotheses, test, and pivot independently. +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. --- ## 2. Trap Avoidance: Loops, Timeouts & Interactive Prompts -The most common failure mode during unattended execution is getting wedged in a blocking state, -consuming time or tokens without making progress. +The primary failure mode of unattended runs is wedging on a blocking command. ### 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)). > 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`, - `--no-detach`, or dedicated background task status notifications over manual polling. -- **Enforce hard timeouts:** Every long-running, external, or uncertain command must be wrapped - in a timeout: - ```bash - timeout 300s my-command --batch - ``` - 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. +- **Use tool-native blocking:** Flags like `--wait`, `--no-detach`, or task completion events over polling. +- **Enforce hard timeouts:** Wrap uncertain or long-running commands: `timeout 300s `. +- **Mandatory non-interactive flags:** Supply `-y`, `--yes`, `--batch`, `--headless`, `CI=1`, or + `DEBIAN_FRONTEND=noninteractive`. Never let a tool prompt `[y/N]` (see [`cli-tooling.md` §2](skills-public/cli-tooling.md)). +- **Bounded retries with hypothesis variation:** Never rerun the same failing command unchanged. Cap retries + at 3 attempts; each must test a distinct hypothesis (flags, config, path, or alternative strategy). + If all fail, record diagnostics and pivot. --- ## 3. Host Safety & Resource Budgets ("Do No Harm") -Unattended access requires strict operational discipline to ensure the machine remains stable, -responsive, and intact. - -### Storage & disk preservation - -Running out of disk space can corrupt databases, break desktop sessions, and crash background daemons. - -- **Check free space first:** Run `df -h ` before downloading large archives, - compiling large codebases, or unpacking toolchains. -- **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. +- **Storage & Disk:** Check `df -h ` before large fetches or builds. Keep ≥15–20% disk headroom. Clean up + 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`, + `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). +- **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. +- **CPU & Memory:** Cap multi-threaded jobs (`-j$(nproc --ignore=2)`), `nice -n 10` heavy builds, and monitor + `free -m` to prevent kernel OOM panics. --- -## 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, -symbol analyzers, cross-compilers, or profiling utilities). - -### Check existence before fetching - -Always verify if a tool or functional equivalent is already available in `$PATH`, in an existing -container, or in user directories before attempting to download: - -```bash -command -v || which -``` - -### 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 -import -postScript ` - 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 ...`. +1. **Verify existence first:** Run `command -v ` before downloading. +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`). +3. **Headless / CLI over GUI:** Never launch heavy graphical interfaces when headless/batch modes exist: + - *Ghidra:* `analyzeHeadless -import -postScript ` + - *Packets:* `tshark` / `tcpdump` instead of GUI Wireshark + - *Debuggers:* `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 -launchers, web views, or login modals. When running unattended, handle them systematically. +When targets are shielded by splash launchers, web wrappers, or login dialogs: -``` -┌────────────────────────────────────────────────────────┐ -│ 1. Direct Executable Bypass (Preferred) │ -│ Inspect process args, run child binary directly │ -└───────────────────────────┬────────────────────────────┘ - │ (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 ` 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. +| Priority | Strategy | Action | +| :--- | :--- | :--- | +| **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. | +| **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. | --- -## 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 -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" +In unattended sessions, context window, token budgets, or subscription quotas will eventually exhaust. > [!CAUTION] -> **The "Last Breath" Trap:** Never initiate an open-ended, non-atomic, or high-risk mutating -> operation when token budget, context window, or subscription quota are nearly exhausted. +> **The "Last Breath" Trap:** Never initiate an open-ended, non-atomic, or high-risk mutating operation +> 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 -harness cuts execution off mid-flight — or freezes the agent until quota resets hours later — -unfinished work leaves the environment in a broken, unusable state: -- **Corrupted source trees:** Half-applied multi-file refactors that leave syntax errors and broken builds. -- **Dangling locks:** Incomplete package installs holding `/var/lib/dpkg/lock`, active git index - locks (`.git/index.lock`), or held database transactions. -- **Uncommitted state:** Unfinished rebases, stashes, or uncommitted modifications that confuse - 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. +Rushing into a complex task on a thin margin guarantees failure if the harness terminates or pauses +execution mid-flight: +- **Corrupted source trees:** Half-applied multi-file refactors leaving syntax errors and broken builds. +- **Dangling locks:** Incomplete package or git locks (`.git/index.lock`, `/var/lib/dpkg/lock`). +- **Uncommitted state:** Half-finished rebases, stashes, or uncommitted edits. +- **Zombie processes & runaway logs:** Background daemons, watchers, or detached tasks spewing debug output + into unrotated log files, silently filling the disk while the agent is paused or waiting for quota. ### The Controlled Landing protocol -When budget, tokens, or turns drop below a comfortable margin (or when an operation cannot be -guaranteed to finish and verify within the remaining budget): - -1. **Stop scope expansion:** Refuse new goals, refactors, or dependency upgrades. -2. **Finish or roll back atomic units:** Complete the immediate atomic file edit or roll it back - cleanly (`git checkout -- `) so the repository remains in a compiling, testable state. -3. **Terminate ephemeral processes & log streams:** Kill all background test runners, scratch - 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. +When remaining budget or context drops below a safe margin: +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 -- ` if incomplete). +3. **Kill ephemeral processes & log streams:** Terminate background test runners, servers, watchers, and tasks redirecting output to unrotated files. +4. **Run verification gates:** Verify `git status` and run quick build/lint checks. +5. **Commit atomic progress:** Save clean progress with conventional commits. +6. **Write the recovery checkpoint:** Update the status log before the session halts. --- ## 7. Checkpointing & The "Wake-Up" Audit Trail -Because the user is not present to monitor intermediate chatter, keep a consolidated record of -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: +Maintain a persistent status file (`PROGRESS.md` or session artifact) updated at each milestone: | Section | Contents | | :--- | :--- | -| **Objective** | The original task and current operational phase. | -| **Completed Work** | Bulleted list of concrete accomplishments (code written, tests passing, tools configured). | -| **Current State** | Active branch, git commit hash, build status, running daemons or services. | -| **Findings & Discoveries** | Key technical observations, reversed structs, discovered bugs, or API quirks. | -| **Obstacles & Fallbacks** | Blockers encountered, strategies that failed (with brief reasons), and how the agent pivoted. | -| **Harness / Budget State** | Token/quota state, whether work halted due to task completion or approaching budget limits. | -| **Immediate Next Steps** | Exact command line or file target where the next session should pick up. | +| **Objective** | Target goal and current operational phase. | +| **Completed Work** | Bulleted list of verified accomplishments (code, passing tests, tools configured). | +| **Current State** | Branch, commit hash, build status, active containers or services. | +| **Findings & Discoveries** | Key technical observations, reversed structs, or API quirks. | +| **Obstacles & Fallbacks** | Failed attempts with concise explanations and how you pivoted. | +| **Budget / Harness State** | Token/quota status; whether stopped by task completion or budget limits. | +| **Immediate Next Steps** | Exact command line or target file for the next session to resume seamlessly. | -### Clean exit on budget exhaustion - -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. +Conclude with a single clear summary pointing the returning user directly to this checkpoint.