Stop pi from blowing its own context: disclosure by default, guard on reads
Always-on instructions were ~11 KB in every request (two near-duplicate AGENTS.md files); pi loads both from $HOME and ~/.pi/agent. That is the monolithic-instruction pattern progressive context disclosure argues against, and it sat on top of a 33k window. - config/pi/AGENTS.md: 1.8 KB index of the rules that cannot be delegated plus a task -> skill table. ~/AGENTS.md and ~/.pi/agent/AGENTS.md both point at it (11 KB -> 3.7 KB of duplicates, one source). - config/pi/skills/homelab-policies: the merged detail (memory, secrets handling, host safety, Proxmox access, forges, codemode sandbox rules, docs conventions, stack defaults), loaded only when a task needs it. - config/pi/skills/context-discipline: locate -> outline -> window -> aggregate, with per-call budgets and an anti-pattern table. - config/pi/extensions/context-guard.ts: pi.on(tool_call). Blocks an unbounded read of a file over 300 lines / 16 KB and answers with the file outline plus the exact windowed call to make instead; blocks cat of such a file; blocks limit > 300. Treats limit 0 and offset-without-limit as unbounded, because the model sends those. Thresholds are overridable (PI_GUARD_MAX_LINES/_BYTES/_WINDOW) so the block path can be tested. Verified on arceus: guard handler fires on real read calls; with a deliberately tiny window it refused a 601-line read and the model reported the constraint and switched to sed/codemode. Skills appear in the prompt: homelab-policies, context-discipline.
This commit is contained in:
1 parent
93e8119eb7
commit
a0c4c8204a
7 files changed
+313
-11
No files matched your search
+11
-11
@@ -1,21 +1,21 @@
|
||||
# Standing instructions
|
||||
|
||||
Keep this file short. Detail lives in skills, which load only when the task calls for them.
|
||||
|
||||
## Progressive context disclosure
|
||||
|
||||
Locate, outline, then read a window — never paste a file body you have not narrowed.
|
||||
|
||||
- `grep -n`/`find`/`ls` before `read`; read with `offset` + `limit` (≤ 200 lines).
|
||||
- Aggregate with `codemode` when a script can return only the conclusion.
|
||||
- `context-guard` blocks unbounded large reads; follow its hint rather than retrying.
|
||||
- Full playbook: `/skill:context-discipline`. Policies: `/skill:homelab-policies`.
|
||||
|
||||
## Document every change in the Wiki.js homelab docs
|
||||
|
||||
After any infrastructure, service, application or configuration change, write it up in the wiki — every time, without being asked again.
|
||||
Documentation never hurts; missing notes cost hours.
|
||||
|
||||
- Target: <https://wiki.godemperordoge.org>, human pages under `homelab/` (`pokedex/hosts|vms|containers|devices`, `reference/*`, `runbooks/*`).
|
||||
- Search first (`search_pages`) and edit the existing page before creating a new one; new pages go under `homelab/reference/clients/`, `homelab/reference/services/`, `homelab/reference/core/`, or `homelab/runbooks/` as fits.
|
||||
- Prefer surgical `edits` on the live source over rewriting the page; the pages are dated operational notes, so record what changed, why, the host, and the exact non-obvious commands or limits.
|
||||
- Record the traps, not just the happy path: error messages, what was tried, the workaround, and any trade-off accepted.
|
||||
- Keep secrets out of the wiki. Names of secrets and where they live are fine; values never.
|
||||
- New pages must also be linked from the parent index page (e.g. `homelab/reference`).
|
||||
|
||||
## Wiki access
|
||||
|
||||
`secretctl get WIKI_BEARER_TOKEN -- …` holds the Wiki.js MCP bearer token; call the MCP endpoint at `https://wiki.godemperordoge.org/_mcp` with JSON-RPC (`tools/call`), or use the `mcp__wiki` server when it is loaded. Never print the token.
|
||||
|
||||
## Track agent configuration in the dotfiles repo
|
||||
|
||||
Agent configuration is managed by `~/.dotfiles` (repo `ziadarafat/dotfiles`, profiles `full` / `headless`; never `full-work`).
|
||||
|
||||
@@ -10,6 +10,14 @@
|
||||
"toolExposure": {
|
||||
"get_page": "direct"
|
||||
}
|
||||
},
|
||||
"lapis": {
|
||||
"command": "node",
|
||||
"args": [
|
||||
"/home/ziadarafat/.pi/agent/git/github.com/GeneGulanesJr/LaPis/memory-store.js",
|
||||
"mcp"
|
||||
],
|
||||
"description": "LaPis local persistent memory (SQLite ~/.pi/memory/memory.db): memory-save, memory-search, memory-get, memory-code and memory-doc for the current project."
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
# Working rules
|
||||
|
||||
Keep this file short. Detail lives in skills, which load only when relevant.
|
||||
|
||||
## Find before you read
|
||||
|
||||
Progressive context disclosure: locate, outline, then read a window — never paste a file body you have not narrowed.
|
||||
|
||||
- `grep -n`, `find`, `ls` first; they are cheaper than reading.
|
||||
- `read` with `offset` + `limit` (≤ 200 lines). A whole large file is a 10k-token mistake.
|
||||
- Aggregate with `codemode` when a script can answer the question and return only the conclusion.
|
||||
- `~/.pi/agent/extensions/context-guard.ts` blocks unbounded large reads and caps tool output. If it blocks you, follow its hint — do not retry the same call.
|
||||
|
||||
Full playbook: `/skill:context-discipline`.
|
||||
|
||||
## Rules that cannot be delegated
|
||||
|
||||
- Docs: after any infrastructure, service or config change, write it up in the Wiki.js homelab docs (`/skill:wiki-update`). Every time.
|
||||
- Secrets: never print, paste or read secret values; inject with `secretctl get KEY -- <cmd>` (`/skill:secrets_man`).
|
||||
- Config: agent config is tracked in `~/.dotfiles`; commit changes there in the same session.
|
||||
- Hosts: check `hostname` before changing anything; arceus runs infrastructure, the Deck keeps `/` read-only.
|
||||
- Verify: run it, open it, or test it before saying it works. Say what you did not check.
|
||||
- Ask before destructive or out-of-project actions.
|
||||
|
||||
## Where the detail lives
|
||||
|
||||
Load the skill that matches the task instead of asking for it up front:
|
||||
|
||||
| Task | Skill |
|
||||
|---|---|
|
||||
| hosts, packages, systemd, storage, DNS, Proxmox | `/skill:infra-change` |
|
||||
| credentials | `/skill:secrets_man` |
|
||||
| wiki pages | `/skill:wiki-update`, `/skill:wiki-view` |
|
||||
| Gitea, issues, PRs, releases | `/skill:gt` |
|
||||
| memory, secrets, host safety, forges, codemode, stack defaults | `/skill:homelab-policies` |
|
||||
| runtimes and project tools | `/skill:mise-cli` |
|
||||
@@ -0,0 +1,124 @@
|
||||
/**
|
||||
* Context guard — progressive context disclosure for reads.
|
||||
*
|
||||
* Pi truncates a read at 2000 lines / 50 KB, which is already ~12k tokens of
|
||||
* context. This extension refuses the *unbounded* read of a large file and
|
||||
* answers with the file's shape plus the exact call to make instead, so the
|
||||
* model spends a few hundred tokens to decide where to look rather than
|
||||
* thousands finding out.
|
||||
*
|
||||
* Blocked: read with no window on a file > MAX_LINES / MAX_BYTES,
|
||||
* read with limit > MAX_WINDOW, `cat` of such a file.
|
||||
*/
|
||||
import { existsSync, readFileSync, statSync } from "node:fs";
|
||||
import { isAbsolute, resolve } from "node:path";
|
||||
import { homedir } from "node:os";
|
||||
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
||||
|
||||
const MAX_LINES = Number(process.env.PI_GUARD_MAX_LINES ?? 300);
|
||||
const MAX_BYTES = Number(process.env.PI_GUARD_MAX_BYTES ?? 16 * 1024);
|
||||
const MAX_WINDOW = Number(process.env.PI_GUARD_MAX_WINDOW ?? 300);
|
||||
const OUTLINE_LIMIT = 18;
|
||||
|
||||
const STRUCTURE =
|
||||
/^(?:#{1,4} |(?:export )?(?:async )?(?:def|class|func|function|type|interface|struct|impl|fn|sub|void|static)\b|[\w.<>\[\]]+\s+\w+\([^)]*\)\s*\{|-- |CREATE |module |describe\()/;
|
||||
|
||||
function toPath(raw: unknown): string | undefined {
|
||||
if (typeof raw !== "string" || raw.length === 0) return undefined;
|
||||
let p = raw;
|
||||
if (p.startsWith("~/")) p = homedir() + p.slice(1);
|
||||
return isAbsolute(p) ? p : resolve(process.cwd(), p);
|
||||
}
|
||||
|
||||
function outline(p: string): string {
|
||||
let text: string;
|
||||
try {
|
||||
const size = statSync(p).size;
|
||||
text = readFileSync(p, "utf8").slice(0, Math.min(size, 1_500_000));
|
||||
} catch {
|
||||
return "";
|
||||
}
|
||||
const hits: string[] = [];
|
||||
const lines = text.split("\n");
|
||||
for (let i = 0; i < lines.length && hits.length < OUTLINE_LIMIT; i++) {
|
||||
const line = lines[i];
|
||||
if (line.length === 0 || line.length > 200) continue;
|
||||
if (STRUCTURE.test(line.trim())) hits.push(`${i + 1}: ${line.trim().slice(0, 110)}`);
|
||||
}
|
||||
return hits.length > 0 ? `\n\nIts shape (line: text):\n${hits.join("\n")}` : "";
|
||||
}
|
||||
|
||||
function describe(p: string): { lines: number; kb: number } {
|
||||
const text = readFileSync(p, "utf8");
|
||||
return { lines: text.split("\n").length, kb: Math.round(Buffer.byteLength(text) / 1024) };
|
||||
}
|
||||
|
||||
function hint(p: string, lines: number, kb: number): string {
|
||||
const pretty = p.startsWith(homedir()) ? "~" + p.slice(homedir().length) : p;
|
||||
return (
|
||||
`Reading ${pretty} whole would add ~${Math.round(kb / 4)}k tokens to the context ` +
|
||||
`(${lines} lines, ${kb} KB). Narrow it first — progressive context disclosure:\n\n` +
|
||||
`- shape: grep -nE '^(class |def |export |func |#{1,3} )' ${pretty}\n` +
|
||||
`- window: read ${pretty} offset=<line> limit=120\n` +
|
||||
`- answer with a script instead: codemode returning only the conclusion\n\n` +
|
||||
`Call read again with offset and limit (<= ${MAX_WINDOW} lines).` +
|
||||
outline(p)
|
||||
);
|
||||
}
|
||||
|
||||
export default function (pi: ExtensionAPI) {
|
||||
pi.on("tool_call", async (event, ctx) => {
|
||||
const input = (event.input ?? {}) as Record<string, unknown>;
|
||||
|
||||
if (event.toolName === "read") {
|
||||
const p = toPath(input.path ?? input.file_path);
|
||||
if (!p || !existsSync(p)) return;
|
||||
let info: { lines: number; kb: number };
|
||||
try {
|
||||
const st = statSync(p);
|
||||
if (st.isDirectory()) return;
|
||||
if (st.size > 4 * 1024 * 1024) return; // do not scan huge binaries
|
||||
info = describe(p);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
const limit = typeof input.limit === "number" ? input.limit : undefined;
|
||||
|
||||
if (limit !== undefined && limit > MAX_WINDOW) {
|
||||
await ctx.ui.notify(`context-guard: read limit ${limit} exceeds the window`, "info");
|
||||
return { block: true, reason: `limit ${limit} is more than a window. Use limit <= ${MAX_WINDOW} with an offset.` + outline(p) };
|
||||
}
|
||||
// limit 0 (and no limit at all) reads to end of file — treat both as unbounded work.
|
||||
const unbounded = limit === undefined || limit <= 0;
|
||||
if (unbounded && (info.lines > MAX_LINES || info.kb > MAX_BYTES / 1024)) {
|
||||
await ctx.ui.notify(`context-guard: blocked an unbounded read of ${info.lines} lines`, "info");
|
||||
return { block: true, reason: hint(p, info.lines, info.kb) };
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.toolName === "bash") {
|
||||
const cmd = typeof input.command === "string" ? input.command.trim() : "";
|
||||
if (cmd.length === 0 || /[|<>]/.test(cmd)) return;
|
||||
const m = /^(?:cat|less|more)\s+(?:-\S+\s+)*([^&\s;]+)$/.exec(cmd);
|
||||
if (!m) return;
|
||||
const p = toPath(m[1]);
|
||||
if (!p || !existsSync(p)) return;
|
||||
try {
|
||||
const st = statSync(p);
|
||||
if (st.isDirectory() || st.size <= MAX_BYTES) return;
|
||||
const info = describe(p);
|
||||
await ctx.ui.notify(`context-guard: blocked cat of ${info.lines} lines`, "info");
|
||||
return {
|
||||
block: true,
|
||||
reason:
|
||||
`\`${cmd}\` would dump ${info.lines} lines (${info.kb} KB, ~${Math.round(info.kb / 4)}k tokens). ` +
|
||||
`Use grep -n, head -n 40, or a codemode script that returns only what you need.` +
|
||||
outline(p),
|
||||
};
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
---
|
||||
name: context-discipline
|
||||
description: Keep the context window lean when exploring code, logs or documentation. Use when searching a repo, reading large files, investigating unfamiliar code, or when context use is high or a tool result was truncated.
|
||||
---
|
||||
|
||||
# Context discipline (progressive context disclosure)
|
||||
|
||||
Load only what answers the question. Every kilobyte you paste costs attention on every later turn.
|
||||
|
||||
## Order of operations
|
||||
|
||||
1. **Check context first.** Is the answer already in the transcript? Do not re-read what you have.
|
||||
2. **Locate.** `grep -n "<symbol>" -r <dir>`, `find -name`, `ls`. Cheap and precise.
|
||||
3. **Outline.** Before reading a file, get its shape: `grep -nE "^(class |def |func |async def |export |function |## )" file` and `wc -l file`.
|
||||
4. **Read a window.** `read path offset=<line> limit=<≤200>`. Expand only around the part that matters.
|
||||
5. **Aggregate.** If a script can answer it, run it in `codemode` and return the conclusion, not the raw rows. Filter with `head`, `jq`, `sort -u`, counts.
|
||||
6. **Report concisely.** Quote the 3 lines that matter, not the function.
|
||||
|
||||
## Budgets
|
||||
|
||||
| Item | Ceiling |
|
||||
|---|---|
|
||||
| lines per `read` | 200 |
|
||||
| calls per file before switching to `grep` | 3 |
|
||||
| tool output you paste onward | ~8 KB |
|
||||
| files read in full per task | 1 (and only if < 200 lines) |
|
||||
|
||||
`context-guard` enforces the first two mechanically: an unbounded read of a large file is blocked, and oversized tool results arrive truncated with the exact `offset` to continue from.
|
||||
|
||||
## When the answer needs the whole thing
|
||||
|
||||
- **Whole-repo question** (how does X work end to end): `grep` for the entry point, outline it, read two windows, then summarise. Do not walk the tree.
|
||||
- **Large logs or JSON**: never `cat`. `jq`/`awk`/`grep -c` to counts and samples.
|
||||
- **Long documents**: read headings, then the section that answers the question.
|
||||
- **Repetitive reading** (many files, same question): delegate — `pi-background-tasks`, or one `codemode` script that loops and returns a table.
|
||||
|
||||
## Anti-patterns
|
||||
|
||||
| Instead of | Do |
|
||||
|---|---|
|
||||
| `read big.py` | `grep -n "def " big.py` then `read big.py offset=120 limit=80` |
|
||||
| `cat app.log` | `tail -50 app.log`, or `grep -c ERROR app.log` |
|
||||
| pasting a full file to explain it | paste the signature and the 5 relevant lines |
|
||||
| re-reading after an edit | trust the edit result; verify with `grep -n` |
|
||||
| "let me look at everything first" | answer the narrow question, expand only if wrong |
|
||||
|
||||
## If you are running out of room
|
||||
|
||||
Compaction summarises old turns and keeps the recent tail. Before that happens: finish the current step, save a short plan (what is done, what is next, file:line anchors) so the summary has something precise to keep.
|
||||
@@ -0,0 +1,74 @@
|
||||
---
|
||||
name: homelab-policies
|
||||
description: Detailed standing policies for this homelab — memory and secrets handling, host safety for arceus and the Steam Deck, Proxmox access, forge accounts, codemode sandbox rules, documentation conventions and default stack. Load before changing hosts, handling credentials, or choosing a stack.
|
||||
---
|
||||
|
||||
# Homelab policies
|
||||
|
||||
The full text of what used to sit in `~/AGENTS.md` and `~/.pi/agent/AGENTS.md`. The always-on file keeps only
|
||||
the invariants and a pointer here; load this when the task touches infrastructure, secrets, forges or stack choice.
|
||||
|
||||
Check `hostname` first. Current user instructions override historical context and memory.
|
||||
|
||||
## Memory (LaPis)
|
||||
|
||||
- LaPis is the primary cross-session, cross-agent memory store shared by pi, Claude Code, Codex and Cursor. Prefer it over per-tool notes.
|
||||
- Recall at the start of non-trivial tasks, before modifying existing configuration or architecture, and when troubleshooting a recurring error.
|
||||
- Save concise, high-signal entries after meaningful work: architectural decisions, root causes and fixes, verified workflows, host constraints.
|
||||
- Never store raw logs, large command output, scratch notes, unverified guesses, or secrets.
|
||||
- Current user instructions, live files and verified command output beat older memories. Supersede stale notes rather than contradicting them.
|
||||
|
||||
## Secrets
|
||||
|
||||
- Secrets live in `~/secrets.txt` (mode 600), read through `secretctl`. Never print the file, environment dumps, raw MCP configs, credentials, auth headers, or unfiltered process args and logs. Never enable shell tracing around credentials.
|
||||
- Load only the variables a command needs into a short-lived child process and parse assignments; do not source the whole file, because values can contain shell metacharacters.
|
||||
- Pass credentials in environment variables or request headers — never in command-line arguments or committed files. Report status codes and redacted summaries.
|
||||
- Workflow and examples: `/skill:secrets_man`.
|
||||
|
||||
## Host safety
|
||||
|
||||
- **`ziadpve` (a.k.a. `arceus`)**: Proxmox VE on Debian 13, `headless` profile, user `ziadarafat`. `/` is writable and `sudo` is passwordless, but this host runs homelab infrastructure: change packages, units, network or storage deliberately, put timeouts on storage commands, and never reboot unexpectedly. Tooling comes from `mise` and Nix; heavy or custom workloads belong in a VM, LXC or container.
|
||||
- **Steam Deck**: SteamOS (immutable Arch base, user `deck`). Keep `/` read-only — no `pacman`, no direct writes to host system paths. GUI apps via Flatpak, development in Distrobox, user services via systemd or containers.
|
||||
- Host work has its own procedure: `/skill:infra-change`.
|
||||
|
||||
## Remote access
|
||||
|
||||
- Primary access is native `ssh` with aliases from `~/.ssh/config`.
|
||||
- XPipe only for key transfer, credential management and access bootstrap on GUI machines — never routine execution, never on `ziadpve`.
|
||||
- Proxmox, VMs and containers are managed with `ssh`, `qm`, `pct`, `pvesm`, `pvecm` and `podman`. Lifecycle changes require root.
|
||||
|
||||
## Forges
|
||||
|
||||
- **Personal Gitea**: `https://gitea.godemperordoge.org` with `GITEA_DOGE_TOKEN` from secrets; use `/skill:gt`.
|
||||
- **Personal GitHub**: account **RustyRaptor** (`anonymous0programmer@gmail.com`) with `GITHUB_ACCESS_TOKEN` mapped to `GH_TOKEN` for `gh`. GitHub for `github.com` remotes, Gitea for the private forge — see `/skill:git`.
|
||||
|
||||
## Codemode sandbox rules
|
||||
|
||||
- Plain, valid JavaScript only: never wrap the script in markdown fences, never return JSON instead of code.
|
||||
- Restricted QuickJS: no `fetch`, `require`, `import`, Node/Bun/Deno APIs, filesystem, or timers. Only `tools` and standard JavaScript built-ins.
|
||||
- Check tool availability before calling (`"toolName" in tools`) and remember non-identifier characters in tool names become `_`.
|
||||
- Use `Promise.allSettled()` for batches so one failure does not abort the rest.
|
||||
- Filter, slice and summarise inside the script; return compact results to protect the context window.
|
||||
- Use codemode for multi-step or high-output work; run single straightforward commands or a CLI skill (`mise-cli`, `searxng`, `gt`, `playwright-cli`) directly.
|
||||
|
||||
## Documentation
|
||||
|
||||
- Operational notes and shared reference material go to Wiki.js (`https://wiki.godemperordoge.org`); code-specific documentation stays in each repository (`README.md`, `docs/`).
|
||||
- Record host specifics when you discover them: mounts, GPU devices, bridges, storage pools, SELinux state, service quirks.
|
||||
- Clear headings, tables for ports/mounts/specs, Mermaid where it helps, copy-paste-ready fenced configs.
|
||||
- After meaningful work: a concise LaPis entry and, when shared, a wiki update.
|
||||
|
||||
## Default stack
|
||||
|
||||
- **Go** is the default for software projects. If another language is a better fit, explain why and ask first.
|
||||
- Python via `uv`; JavaScript/TypeScript via `bun`; containers with rootless **Podman** (systemd, Quadlets) unless compatibility forces Docker.
|
||||
- Distributions: AlmaLinux 9/10 for enterprise and servers, Fedora for modern toolchains, Arch/SteamOS for rolling and client machines.
|
||||
|
||||
## Other agents on the same box
|
||||
|
||||
When running as Buffy (Freebuff/Codebuff) or another harness, the same policies apply with these substitutions:
|
||||
|
||||
- Skills live in `~/.agents/skills/` and load with the `skill` tool; there is no codemode sandbox, so run CLI commands directly.
|
||||
- Memory: LaPis CLI, `node ~/.pi/agent/git/github.com/GeneGulanesJr/LaPis/memory-store.js search|save|get|stats` against the shared `~/.pi/memory/memory.db` (`lapis-memory` skill).
|
||||
- Wiki MCP: `secretctl get WIKI3_MCP_TOKEN -- wiki-mcp <tool> '<json>'` (bridge at `~/.local/bin/wiki-mcp`; `wiki-mcp tools` lists tools).
|
||||
- SearXNG is not needed there; use the harness's native web search and fetch tools.
|
||||
@@ -22,6 +22,17 @@ in
|
||||
".free-pi/agent/mcp.json".source = link "config/free-pi/mcp.json";
|
||||
".free-pi/agent/AGENTS.md".source = link "config/free-pi/AGENTS.md";
|
||||
|
||||
# Progressive context disclosure: a thin always-on AGENTS.md, the detail in
|
||||
# skills, and an extension that refuses unbounded reads of large files.
|
||||
"AGENTS.md".source = link "config/pi/AGENTS.md";
|
||||
".pi/agent/AGENTS.md".source = link "config/pi/AGENTS.md";
|
||||
".pi/agent/extensions/context-guard.ts".source = link "config/pi/extensions/context-guard.ts";
|
||||
".pi/agent/skills/context-discipline/SKILL.md".source = link "config/pi/skills/context-discipline/SKILL.md";
|
||||
".pi/agent/skills/homelab-policies/SKILL.md".source = link "config/pi/skills/homelab-policies/SKILL.md";
|
||||
".free-pi/agent/extensions/context-guard.ts".source = link "config/pi/extensions/context-guard.ts";
|
||||
".free-pi/agent/skills/context-discipline/SKILL.md".source = link "config/pi/skills/context-discipline/SKILL.md";
|
||||
".free-pi/agent/skills/homelab-policies/SKILL.md".source = link "config/pi/skills/homelab-policies/SKILL.md";
|
||||
|
||||
# Cursor and Antigravity. Their wiki MCP server is the `mcp-wiki-remote`
|
||||
# wrapper in bin/, which pulls the token from secretctl at launch.
|
||||
".cursor/mcp.json".source = link "config/cursor/mcp.json";
|
||||
|
||||
Reference in new issue
Block a user