agentleFS
Ex-imanityEx-imanity/SkillCollections/skills/context-resilient-task/SKILL.md

context-resilient-task

Skill1 starsChanged 17 days agoMITView on GitHub

Context-resilient task management via a filesystem Minimum Recovery Set (MRS slots in .task-state/<slot>/; legacy layouts remain readable). Reconstructs task state from on-disk artifacts so work survives /clear, session interruption, agent switches, and context-window loss. Use this skill whenever the user mentions multi-phase tasks, multi-session work, cross-session recovery, task state restoration, MRS, .task-state, lost context, hallucinated todos, forgotten work, 任务状态恢复, 跨会话任务, 多会话开发, 上下文丢失, /clear 后继续, 任务恢复, or asks the agent to remember a task across sessions. Also trigger proactively when starting any task likely to span more than one session, even if the user doesn't explicitly request recovery — the upfront MRS structure prevents context-loss surprises later.

The file

Show its rules and text

We split this skill into the rules it gives an agent

23 rules. About 0 are common, 14 are distinctive, and 9 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈14

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 9

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    If missing: STOP, run initialization wizard.

    line 29
  2. Very specific:

    If missing: Follow existing Tier 1 warnings.

    line 39
  3. Distinctive:

    If missing: No action, continue normally.

    line 45
  4. Distinctive:

    Source Attribution: Every fact cites source file

    line 110
  5. Distinctive:

    Explicit Unknowns: If not in artifacts, mark "Unknown"

    line 111
  6. Distinctive:

    No Inference: Don't fill gaps with assumptions

    line 112
  7. Distinctive:

    Single Next Action: Only one concrete step at a time

    line 113
  8. Distinctive:

    Output Artifact: Every action produces/updates an artifact

    line 114
  9. Very specific:

    Single index rule: every resource is registered in utils.md, whatever its kind — 飞书文档, external web pages, repos, local paths, service …

    line 122
  10. Distinctive:

    Check current scope, preconditions, verification and superseding decisions.

    line 194
  11. Very specific:

    After the first reusable problem is triaged, record it in problems.md using the template, even if its cause is still unknown.

    line 199
  12. Distinctive:

    After a successful fix, immediately update its validation evidence.

    line 201
  13. Distinctive:

    If Tier 0 missing, run the bundled script (CLI or interactive):

    line 236
  14. Very specific:

    If you prefer manual setup, copy templates from assets/ (task_state.template.md, plan.template.md, snapshot.template.md, …

    line 258
  15. Very specific:

    Strict boundary: Only register files under the plan roots.

    line 274
  16. Very specific:

    All scripts read templates from assets/ so the rendered MRS files always match the documented schema.

    line 336
  17. Distinctive:

    When initializing MRS for a project that uses multiple agents (Claude Code, Codex, etc.):

    line 373
  18. Very specific:

    Update task_state.md in-place.

    line 381
  19. Very specific:

    Before compaction or session handoff, surface bounded latest entries from decisions.md, findings.md, and utils.md in the digest/snapshot

    line 386
  20. Distinctive:

    Search complete history before retries.

    line 391
  21. Distinctive:

    Leave completed todos in Active Todos list

    line 398
  22. Very specific:

    Put non-plan files or .superpowers/sdd/ ledgers in Plan Registry

    line 400
  23. Distinctive:

    Use forbidden temp paths

    line 402

≈ “Common” is an estimate: at least 1 in 5 of the 350,495 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Context-Resilient Task

Context is not input, it's output. Never rely on conversational memory. Always reconstruct task state from artifacts on disk.

File Authority

  • task_state.md — Source of truth. Always update in-place (edit existing fields). Never append dated sections.
  • progress.md — Append-only chronological log. Never overwrite.
  • snapshot.md — Latest checkpoint. Overwrite entire file on each update (archive previous first).
  • decisions.md — Stable conclusions and decisions. Append-only. Required for long tasks (see Tier 1 below).
  • utils.md — The single resource registry: every resource an agent may need to reach, internal or external, remote or local. Not findings, not deliverables.
  • problems.md — Reusable symptoms, failed attempts and verified fixes, including resolved problems. Update by stable ID; append attempts under the entry. Not the authority for current todos.
  • On conflict between files, task_state.md wins.
  • Recovery reserves separate slots for core state, decisions, findings, resources and problem/recall entry points within a global 4000-character budget. Pinned entries are prioritized within their slot; full text stays on disk and is searchable beyond the recent window.

Minimum Recovery Set (MRS)

Tier 0: Core Required (MUST exist)

  • task_state.md — Current state (in-place updated, Active Todos in header)
  • plan.md — Task plan + Plan Registry
  • snapshot.md — Latest checkpoint (overwrite, not append)

If missing: STOP, run initialization wizard.

Tier 1: Important Context (SHOULD exist)

  • findings.md — Research and discoveries
  • progress.md — Session execution log (append-only)
  • architecture.md — Architecture (for system-level tasks)
  • decisions.md — Stable conclusions/decisions (required when: multi-session, multi-agent, or >10 phases; otherwise optional)
  • utils.md — Resource registry (optional for legacy MRS; created for new MRS)
  • problems.md — Reusable problem records (created for new MRS; legacy absence is normal, create after the first reusable error/blocker)

If missing: Follow existing Tier 1 warnings; missing problems.md never pauses recovery or requires confirmation.

Tier 2: Optional Context (MAY exist)

  • blockers.md — Current blockers
  • Domain-specific artifacts

If missing: No action, continue normally.

Full MRS specification: references/minimum-recovery-set.md

On-Invoke Detection

1. Discover MRS: walk up from CWD; collect `.task-state/<slot>/` plus legacy
   `.task-state/` records and `.task-state-<slug>/` at the first owning project
   with records (run: `python <skill-root>/scripts/list_mrs.py`). Containers and
   archives are not tasks; partial MRS records remain visible for repair.
2. If 0 MRS found → Initialization mode
3. If 1 MRS found → use it; proceed to step 5
4. If >1 MRS found → ASK user which task to resume
   - List each with goal/status/updated timestamp
   - Recommend most recently updated (*) but never assume
5. Scan selected MRS for Tier 0 files
6. If status=completed → Skip recovery, prompt archival
7. If all Tier 0 present → Recovery mode (a present-but-malformed Tier 0 file is a
   repair task, never a reason to initialize over an existing MRS)
8. If any Tier 0 file is **absent** → Initialization mode
9. Check Tier 1, emit warnings if missing
10. Output "Reconstructed Task State"
11. Continue from last checkpoint

Task lifecycle: active → paused / blocked → active → completed

For parallel/interrupted tasks (multiple MRS in one project), see references/multi-task-workflow.md.

New tasks use .task-state/main/ by default or init_mrs.py --slot <slug>. main is not a current-task pointer. Existing MRS stays in place until explicitly migrated. Read references/mrs-layout-migration.md for preview/apply, historical path resolution and guarded rollback. Upgrade all readers/hooks before moving data; do not migrate a task with unfinished reviews.

Structured Output Template

At key checkpoints (recovery, phase transition, major decision, status request, error/blocker), output:

## Reconstructed Task State
### Goal
(from artifact: task_state.md)
### What Has Been Done
- <action> (source: <filename>)
### Current Artifacts
- <filename> (last updated: <timestamp>)
### Unknown / Missing
- <info not in artifacts>
### Next Required Action
<single concrete step>
### Artifact to Be Produced
<filename> - <purpose>
### Stable Context
- Latest decisions (source: `decisions.md`)
- Latest findings and explicit unknowns (source: `findings.md`)
- Utilities profile (source: `utils.md`, when present)
- Known problems and full-history recall entry point (source: `problems.md`, when present)

Full template specification: references/output-template.md

Anti-Hallucination Rules

  1. Source Attribution: Every fact cites source file
  2. Explicit Unknowns: If not in artifacts, mark "Unknown"
  3. No Inference: Don't fill gaps with assumptions
  4. Single Next Action: Only one concrete step at a time
  5. Output Artifact: Every action produces/updates an artifact

Resource Registry (utils.md)

Resources are the context most expensive to lose: after /clear or compaction an agent that cannot find the PRD link, the log query or the dev-server port asks the user to paste it all again. So they get one registration point, not one per kind.

Single index rule: every resource is registered in utils.md, whatever its kind — 飞书文档, external web pages, repos, local paths, service endpoints, databases, log platforms, dashboards, local processes, static previews, CLI/MCP tools, tickets, test assets, credential names. Other artifacts (findings.md, decisions.md, plan.md, task_state.md) cite the ID — (res: R3) — and never repeat the pointer. One place to write, one place to look.

## Resource Registry
| ID | Type | Name / Purpose | Pointer | Env | Access | Sensitivity | Verified |
|----|------|----------------|---------|-----|--------|-------------|----------|
| R1 | feishu-doc | 需求 PRD | https://xx.feishu.cn/docx/... | prod | 飞书登录 | internal | 2026-09-10 |
| R2 | local-process | 本地 dev server | http://localhost:3000 (pnpm dev) | local | — | internal | 2026-09-10 |

Type is an open enumeration — feishu-doc, web-page, repo, local-path, service-api, database, log-platform, dashboard, local-process, static-site, cli-tool, mcp-tool, ticket, test-asset, credential-ref — and anything uncovered is registered as other:<label> rather than a bare invented type, so a new resource kind is never a reason to file it somewhere else. verify_mrs.py warns on unknown types and on rows missing a sensitivity level.

Because it is an index and not a log, utils.md sections are pinned: no section is dropped by the recency window that trims append-only logs. The per-record (1800 chars) and whole-output (4000 chars) budgets still apply, so a very long registry is truncated from the tail with a utils.md:<line> pointer — pinning removes the recency cliff, not the budget.

Redaction is per row: one restricted resource is dropped without hiding its table siblings, and a row with no level is dropped fail-closed once any sibling row is restricted. Independently of any label, an entry containing a credential-shaped value (scheme://user:pass@host, ?token=…, Bearer …) is never emitted, and verify_mrs.py reports the file as invalid — the value must be removed, not just withheld from digests. It also warns when another MRS document (findings.md, progress.md, …) carries such a value, because those are replayed or committed too.

Register a resource the first time it is used, keep rows to one line, and prune dead entries (~25 rows is the working limit before a digest starts truncating).

Two columns carry more than they look like: Access holds the command or tool that reads the resource (lark-cli docs +fetch --doc <url>) as readily as a credential name — that is the part an agent cannot guess — and Verified holds the date plus the version read (2026-09-07 (rev 607)), because a doc that moved to a new revision invalidates conclusions drawn from the old one. Sub-resources (a Base's table inventory, a chapter outline) stay in ## Notes keyed by ID instead of taking a row each. Single source files cited as evidence for a finding are not resources.

Legacy MRS: python <skill-root>/scripts/scan_resources.py <mrs-dir> drafts the registry from the pointers already scattered in the MRS documents (read-only until --write). Drafts are machine-guessed, so they are written as restricted — on disk but withheld from every digest until a human fills in purpose/access and sets the real level. A pointer carrying an embedded credential is redacted (user:***@) before it is written, and the scanner names the source file that still holds the raw value.

Full schema and type reference: references/artifact-standards.md

Recall Before Retry

On an unexpected error, blocker or repeated anomaly, search the selected MRS before retrying or choosing another fix. Recovery summaries are entry points, not an exhaustive memory. Use the full history even if a prior fix is absent from the latest digest:

python <skill-root>/scripts/recall_context.py <mrs-dir> \
  --query '<error + component or command>' \
  --scope repo=<known-repo> --scope env=<known-environment>
  1. Query symptoms/signatures/components; inspect the matching source lines. The read-only script searches all entries in problems/findings/decisions/progress/utils, not just recent headings. No matches → continue normal diagnosis.
  2. Check current scope, preconditions, verification and superseding decisions. A lexical match is a candidate, not a root-cause verdict. Conflicting declared scope is excluded; missing scope or stale/open records require revalidation.
  3. Reuse a verified fix only when applicable. Retry a failed attempt only with changed conditions, new evidence or an explicit bounded transient-retry policy.
  4. After the first reusable problem is triaged, record it in problems.md using the template, even if its cause is still unknown. After a successful fix, immediately update its validation evidence. On recurrence, update the same ID and append the attempt/outcome; keep resolved entries searchable.
  5. Exclude expected TDD failures and disposable noise. Keep credentials/raw user data out. Promote stable cross-task lessons into existing project guidance or the relevant tool skill, with one authoritative body and a pointer here.

Required fields and retrieval semantics: references/problem-recall.md. This is an agent workflow instruction, not a new automatic tool-error hook.

Todo Management

task_state.md maintains two sections as the only authoritative source for todos:

  • Active Todos — Located near the top of the file (immediately after Status), ensuring recovery always reads them first.
  • Completed Items — Single-line summaries only. Details belong in progress.md.

Rules: completing a todo = remove from Active, append to Completed. Never infer status from progress.md. Each todo is a single line; detailed context references external files.

Full rules: references/artifact-standards.md

Failure Modes

ConditionSeverityAction
Missing Tier 0 fileSTOPRun initialization wizard
Tier 0 file present but invalidSTOPRepair the file. NEVER re-initialize — the MRS holds real history
Missing Tier 1 fileWARNAsk user to confirm continuation
Stale snapshot (>7 days)WARNOffer to regenerate
Conflicting artifactsSTOPAsk user which is correct
Task completedPROMPTOffer archive / new task / reopen

Full failure mode details: references/recovery-workflow.md

Initialization Wizard

If Tier 0 missing, run the bundled script (CLI or interactive):

# CLI form
python <skill-root>/scripts/init_mrs.py \
  --slot main \
  --goal "Build payment service" \
  --complexity medium \
  --requirements "Stripe integration;3DS handling;Webhook verifier"

# Interactive form (omit --goal/--complexity to be prompted)
python <skill-root>/scripts/init_mrs.py

Behavior:

  1. Collects: Task Goal, Complexity (small/medium/large), Key Requirements (optional)
  2. Renders Tier 0 from templates: task_state.md, plan.md, snapshot.md
  3. Creates Tier 1 logs/registries: findings.md, progress.md, utils.md, and the empty problems.md template
  4. Auto-creates decisions.md if --complexity large, --multi-agent, or >10 requirements
  5. Refuses to write into a non-empty target unless --force
  6. Reminds you to copy MRS rules to project AGENTS.md for Codex/other agent compatibility (see references/agents-md-snippet.md)

If you prefer manual setup, copy templates from assets/ (task_state.template.md, plan.template.md, snapshot.template.md, decisions.template.md, utils.template.md, problems.template.md) and fill the {...} placeholders.

Plan Registry

plan.md must include a Plan Registry tracking every plan/spec file produced for the task, by repo-relative path:

## Plan Registry
| File | Source Skill | Date | Status |
|------|-------------|------|--------|
| docs/superpowers/specs/2026-09-26-sync-design.md | brainstorming | 2026-09-26 | completed |
| docs/superpowers/plans/2026-09-26-sync.md | writing-plans | 2026-09-26 | in_progress |

Plan roots: docs/plans/ (superpowers ≤ 4.x, designs and plans together), docs/superpowers/specs/ + docs/superpowers/plans/ (superpowers ≥ 5.0). If the project relocates plans or specs, add a Plan roots: <dir>/, ... line inside the registry section. Legacy ## Plan Registry (docs/plans) headings stay valid.

Strict boundary: Only register files under the plan roots. Do NOT register CLAUDE.md, AGENTS.md, .task-state/*, docs/runbooks/*, or superpowers execution ledgers under .superpowers/sdd/.

Full cross-skill protocol: references/multi-skill-integration.md

File Standards

FileUpdate TriggerMethod
task_state.mdPhase transition, decision, todo changeIn-place edit. Compress if >300 lines.
plan.mdPhase status change, new plan fileIn-place edit (Registry append)
snapshot.mdPhase complete, blocker, major decision, session endOverwrite (archive previous)
decisions.mdStable conclusion reachedAppend only
findings.mdAfter discoveriesAppend only
progress.mdAfter each significant actionAppend only
utils.mdA resource is first used, or its pointer/access changesIn-place by row
problems.mdReusable error/blocker triaged, attempted fix or recurrenceIn-place by ID; append attempt history

Forbidden paths: /.cursor/, /agent-tools/, /temp/, /tmp/, /.cache/

Full standards: references/artifact-standards.md

Scripts

Locate scripts relative to this SKILL.md.

# Initialize a fresh MRS (CLI or interactive)
python <skill-root>/scripts/init_mrs.py --slot main \
    --goal "..." --complexity medium --requirements "a;b;c"
python <skill-root>/scripts/init_mrs.py                       # interactive wizard

# Check MRS health
python <skill-root>/scripts/verify_mrs.py .task-state/main
python <skill-root>/scripts/verify_mrs.py --json .task-state/main  # JSON for agents

# Search complete history before retrying an error/blocker (read-only)
python <skill-root>/scripts/recall_context.py .task-state/main --query 'error component'
python <skill-root>/scripts/recall_context.py .task-state/main --query 'error component' --scope env=local --json

# Draft a Resource Registry from pointers already in a legacy MRS (read-only by default)
python <skill-root>/scripts/scan_resources.py .task-state/main
python <skill-root>/scripts/scan_resources.py .task-state/main --write   # insert draft rows
python <skill-root>/scripts/scan_resources.py .task-state/main --json    # for agents

# List all MRS directories discoverable from CWD
python <skill-root>/scripts/list_mrs.py
python <skill-root>/scripts/list_mrs.py --json  # JSON for agents

# Generate snapshot (overwrites snapshot.md)
python <skill-root>/scripts/generate_snapshot.py .task-state/main
python <skill-root>/scripts/generate_snapshot.py .task-state/main --project-root .  # explicit source scan root
python <skill-root>/scripts/generate_snapshot.py --archive .task-state/main  # also archive

# Auto-hook scripts (read-only, non-blocking, silent when no MRS) — see Automatic Hooks below
python <skill-root>/scripts/restore_context.py     # rehydrate task state (session start / after /clear)
python <skill-root>/scripts/precompact_digest.py   # survival digest before compaction
python <skill-root>/scripts/gate_check.py          # remind to flush state if the tree drifted
python <skill-root>/scripts/install_hooks.py       # install into Claude Code settings.json
python <skill-root>/scripts/install_hooks.py --codex  # install into .codex/hooks.json
python <skill-root>/scripts/install_hooks.py --grok   # install into ~/.grok/hooks/context-resilient-task.json

All scripts read templates from assets/ so the rendered MRS files always match the documented schema. Snapshot, drift and ledger probes share the owning-project resolver for nested and legacy layouts; linked-worktree work still follows the current worktree unless --project-root is provided.

Automatic Hooks (optional)

Reading the MRS still depends on remembering to. The auto-hooks make an agent rehydrate, flush, and self-check the MRS at the right moments unprompted. All are read-only, non-blocking (exit 0), and silent when no MRS is discoverable, so a single global install is safe for every project.

EventScriptEffect
Session start / after /clearrestore_context.pyPrints "Reconstructed Task State" so a fresh context starts oriented
Before compactionprecompact_digest.pySurfaces a survival digest the summarizer should keep
End of turn (Stop)gate_check.pyReminds (never blocks) when the tree drifted past the last snapshot

Claude Code: python <skill-root>/scripts/install_hooks.py (add --project to scope to one repo, --uninstall to remove, --dry-run to preview). Merges into settings.json, idempotent, refuses invalid JSON.

Codex: python <skill-root>/scripts/install_hooks.py --codex installs the same three hooks into the current project's .codex/hooks.json. Add --dry-run to preview or --uninstall to remove only these hooks. Codex will request trust approval for new hook definitions.

Grok: python <skill-root>/scripts/install_hooks.py --grok installs into ~/.grok/hooks/context-resilient-task.json (add --project for ./.grok/hooks/...). Sets a 30s timeout per command. Grok does not inject SessionStart/PreCompact stdout into the model context — keep the AGENTS.md auto-recovery block so the model still runs restore_context.py when needed.

Codex / Gemini / other agents: wire the same scripts via AGENTS.md — see the auto-recovery block in references/agents-md-snippet.md.

Full details: references/hooks-setup.md.

Codex / Multi-Agent Compatibility

When initializing MRS for a project that uses multiple agents (Claude Code, Codex, etc.):

  1. Copy the content of references/agents-md-snippet.md into the project's root AGENTS.md
  2. This ensures all agents follow the same MRS update rules regardless of whether they have access to this skill

Best Practices

DO:

  • Update task_state.md in-place; keep Active Todos near the top
  • Append to progress.md for every action
  • Overwrite snapshot.md on key events (never append sections)
  • Append stable conclusions to decisions.md (not task_state.md)
  • Cite source files in all statements
  • Before compaction or session handoff, surface bounded latest entries from decisions.md, findings.md, and utils.md in the digest/snapshot
  • Register every resource (飞书文档/外部网页/本地进程/静态页/接口/数据库/工具…) in the utils.md registry on first use, and cite it elsewhere by ID; never put secrets or task conclusions there
  • Give every registry row an explicit Sensitivity: public|internal|restricted; restricted rows are excluded per row from snapshots and recovery digests, and likely credential values fail validation.
  • Legacy suffixed Completed Items subsections (for example, per-round history) are preserved with a warning; only repeated exact authoritative sections invalidate task_state.md.
  • Regenerate snapshot.md after updating Tier 1 logs; verification warns when source context is newer than the snapshot.
  • Search complete history before retries; capture reusable problems immediately, retain resolved fixes and recheck scope before reuse.
  • Register every new plan/spec file (under docs/plans/, docs/superpowers/plans/, docs/superpowers/specs/, or a declared root) in Plan Registry immediately
  • Compress task_state.md when it exceeds 300 lines

DON'T:

  • Rely on conversational memory
  • Append dated sections to task_state.md (use progress.md / decisions.md)
  • Leave completed todos in Active Todos list
  • Infer todo status from progress.md
  • Put non-plan files or .superpowers/sdd/ ledgers in Plan Registry
  • Scatter resource pointers into findings/decisions/plan instead of registering them in utils.md
  • Use forbidden temp paths

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.