一键导入
memory-and-state
Use to maintain persistent context across agent sessions — decision logs, architecture memory, and constraint tracking.
用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
菜单
Use to maintain persistent context across agent sessions — decision logs, architecture memory, and constraint tracking.
用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
基于 SOC 职业分类
Use for general product implementation work that is not primarily backend architecture, pure integration wiring, or screenshot-driven design-to-code.
Use when the main deliverable is maintainable documentation such as repository rules, onboarding guides, runbooks, ADRs, or architecture notes.
Use on first entry to a new repository to run environment scanning and ask targeted boundary questions before implementation.
Use after writing or modifying code to enforce the mandatory write → test → fix → repeat validation cycle.
Use before committing to a design or plan to force assumption-surfacing. The agent challenges your design, questions edge cases, and flags gaps — you patch vague decisions. Prevents the failure mode where a design "feels explained" but contains hidden flaws that only appear during implementation.
Use to establish and maintain a shared domain glossary (UBIQUITOUS_LANGUAGE.md). Creates a single source of term definitions that all agents, prompts, and documents must use — preventing semantic drift and repeated re-explanation across sessions.
| name | memory-and-state |
| description | Use to maintain persistent context across agent sessions — decision logs, architecture memory, and constraint tracking. |
Use this skill to prevent agents from forgetting prior decisions and repeating mistakes.
DECISIONS.md)A version-controlled file at the repo root. Records architectural and behavioral decisions.
Format:
## YYYY-MM-DD: [Decision title]
- **Context**: Why this decision was needed
- **Decision**: What was decided
- **Alternatives considered**: What was rejected and why
- **Constraints introduced**: What future work must respect
Rules:
DECISIONS.md at the start of every planning or implementation task. This is not optional.ARCHITECTURE.md)A version-controlled file describing the codebase structure.
Should contain:
Rules:
For in-progress tasks that span multiple agent interactions:
This prevents re-discovery and reduces repeated mistakes within a session.
When returning to a repository after a break and the project boundaries are already confirmed, use this protocol instead of on-project-start.
| Situation | Action |
|---|---|
| First entry to a new repository | Use on-project-start skill |
| Returning after a break, boundaries already confirmed | Use this protocol |
| Resuming a mid-task after interruption | This protocol + read session notes |
Load context in this sequence, stopping as soon as you have enough to proceed:
L0 — Stable anchors (always load, target ≤ 500 tokens)
project/project-manifest.md — confirmed project scope and constraintsDECISIONS.md — recent cross-cutting decisionsL1 — Last session state (load if a summary exists, target ≤ 1,500 tokens)
DECISIONS.md entries + module map section of ARCHITECTURE.md only (not the full file)L2 — Task-specific context (on demand, ≤ 1,000 tokens per pull)
You can confidently answer all three:
If the token budget for a tier is reached before the question is answered, apply selective retrieval for remaining gaps rather than reading in full.
After loading, produce a brief confirmation before starting work:
Session resumed:
- Last completed: [brief summary]
- Active constraints: [1–3 bullets from DECISIONS.md]
- Pending work: [from session notes, if any]
- Ready to: [next step]
Within a single conversation or agent session, manage history in three tiers to prevent context window exhaustion while preserving relevant information.
Keep the most recent 3–5 turns of conversation as raw, unmodified content. This preserves full fidelity for the active working context.
When turns age out of the short-term window, compress them using the canonical template in docs/agent-templates.md → Compaction summary template.
Rules:
docs/agent-templates.md is the single source of truth.docs/operating-rules.md.For knowledge that persists beyond a single session, use the existing persistent stores:
| Store | Content | Retrieval |
|---|---|---|
DECISIONS.md | Architectural and behavioral decisions | Read at task start |
ARCHITECTURE.md | Module map, interfaces, data flow | Read when working on unfamiliar modules |
| Repo memory files | Reusable patterns, component-level notes | Search by module name or task type keywords |
DECISIONS_ARCHIVE.md | Inactive past decisions | Search only for legacy module work |
For teams with vector database or embedding infrastructure, long-term memory can be augmented with semantic retrieval (RAG). This replaces full-file reads with targeted retrieval, reducing token consumption for large codebases where DECISIONS.md or ARCHITECTURE.md alone exceed the 3,000-token Tier 3 budget.
This section is entirely optional. If no vector store is available, use the file-based selective retrieval from the Triage-driven selective retrieval section below. The playbook functions identically without RAG.
Index the following sources as embeddings:
| Source | Refresh trigger | Priority |
|---|---|---|
DECISIONS.md | After every Record step | High |
ARCHITECTURE.md | After structural changes | High |
| Session summaries (Tier 2) | After each summary generation | Medium |
| Task completion summaries | After every Summarize step | Medium |
Trace files (.agent-trace/) | After every Trace step | Low |
DECISIONS.md when new entries are appended.RAG results replace the 3,000-token Tier 3 budget — they do not add to it. The total conversation memory target (8,500 tokens) remains unchanged:
| Tier | Without RAG | With RAG |
|---|---|---|
| Tier 3 (long-term) | Full-file reads, ≤ 3,000 tokens | Top-K retrieval, ≤ 3,000 tokens |
| Total budget | ≤ 8,500 tokens | ≤ 8,500 tokens (unchanged) |
If the vector store is unavailable at runtime, follow the Retrieval degradation chain (see below) starting at Level 1:
**Memory retrieval**: Level N — [method name].| Tier | Target budget | Enforcement |
|---|---|---|
| Short-term (raw turns) | ≤ 4,000 tokens | Trim oldest turn when exceeded |
| Mid-term (summary) | ≤ 1,500 tokens | Regenerate summary with tighter compression |
| Long-term (persistent reads) | ≤ 3,000 tokens per task | Use selective read strategy (see below) |
| Total conversation memory | ≤ 8,500 tokens | Roughly 6–7% of a 128K context window |
For any task spanning more than one step or more than one file, maintain a context anchor using the canonical template in docs/agent-templates.md → Context anchor template.
Do not duplicate or redefine the template here; treat docs/agent-templates.md as the single source of truth for the anchor format.
Update this anchor before each major step. This prevents drift by forcing the agent to re-read the plan and current state.
Before making any decision, check DECISIONS.md for conflicts:
STOP and wait for user decision. Do not resolve contradictions autonomously.
Policy check: If
prompt-budget.yml→decision_log.policy: example_only, replace everyAppend to DECISIONS.mdaction in the table below withRecord in task summary or trace. Do not write toDECISIONS.mdunless the user explicitly requests it, or you are updating the template's own decision-format.
| Event | Action |
|---|---|
| Architectural decision made | Append to DECISIONS.md |
| New module or structural change | Update ARCHITECTURE.md |
| Constraint discovered during work | Add to project/project-manifest.md |
| Error pattern found | Note in session memory to avoid repeating |
| Task partially complete | Write progress to session notes |
| Technology or library introduced | Append to DECISIONS.md |
| Schema or contract changed | Append to DECISIONS.md |
| Tradeoff made | Append to DECISIONS.md |
| Event | Action |
|---|---|
| Starting any implementation | Read DECISIONS.md and ARCHITECTURE.md |
| Encountering unfamiliar module | Read ARCHITECTURE.md |
| Making a decision | Check DECISIONS.md for prior related decisions |
| Resuming interrupted work | Read session notes |
| Starting a long task | Produce a context anchor |
| Starting a Small task | Query categorized memory for similar past patterns (see below) |
Memory is organized along two dimensions: scope (how broadly it applies) and category (what kind of information it contains).
Tag every persistent memory entry with a scope to control when it is loaded:
| Scope | Meaning | When loaded |
|---|---|---|
global | Applies across all projects or sessions | Always (L0) |
project | Specific to this repository | On session resume (L1) |
component:<path> | Specific to one module or directory | On demand when working on that component (L2) |
Use the narrowest scope that is accurate. Scope drives the loading order in the Session Resume Protocol — global loads first, component loads last and only on demand.
| Category | Scope | Primary store | Query when |
|---|---|---|---|
| Architectural decisions, global conventions | project | DECISIONS.md, ARCHITECTURE.md (task summary/handoff/trace when decision_log.policy: example_only) | Starting any task, making architectural choices |
| Component patterns, quirks, module constraints | component:<path> | Module READMEs, session/repo memory files | Working on a specific or unfamiliar module |
| Recurring fix patterns, validated approaches | project or global | Session/repo memory files | Starting a Small task (search by task-type keywords) |
| User preferences, cross-repo conventions | global | Personal memory files | Any task |
Include a scope field in frontmatter when writing persistent memory files:
---
name: <memory name>
description: <one-line description — used to decide relevance at session start>
type: feedback | project | reference | user
scope: global | project | component:<relative-path>
---
Small task retrieval: Before implementing a Small task, search session/repo memory for the affected module or task-type keywords. If a matching pattern exists, follow it. If not, proceed normally and capture the pattern in the task completion summary.
Persistent memory files grow over time. Without active lifecycle management, they consume excessive tokens on every read and eventually exceed context windows.
DECISIONS.md exceeds 50 entries or 30 KB, ORDECISIONS.mdDECISIONS_ARCHIVE.mdDECISIONS.mdNever archive based on date alone — a 2-year-old decision with active constraints stays in DECISIONS.md.
DECISIONS_ARCHIVE.md uses the same entry format as DECISIONS.md, with one addition: append - **Archived on**: YYYY-MM-DD — [reason, e.g., "replaced by decision X"] to each entry.
DECISIONS.md retains all entries with active constraintsAgents should not read the full archive on every task. Use a tiered approach. If DECISIONS_ARCHIVE.md does not exist yet, treat archive searches as returning no matches and skip any archive-read step that would otherwise require the file.
| Situation | What to read |
|---|---|
| Normal task | DECISIONS.md only (active constraints) |
| Task involves legacy module or old migration | DECISIONS.md + search DECISIONS_ARCHIVE.md for module name, if the archive file exists |
| Contradiction detection finds no match in active | Search DECISIONS_ARCHIVE.md before concluding "no prior decision", if the archive file exists; otherwise treat as no archived match |
| Periodic maintenance review | Read both files in full if DECISIONS_ARCHIVE.md exists; otherwise read DECISIONS.md only |
When DECISIONS.md grows large (over 30 entries or 20 KB), reading it in full on every task wastes token budget. Use triage results to load only relevant decisions.
DECISIONS.md in full (current behavior, no change needed).src/api/, src/services/user).DECISIONS.md for entries whose title or constraint text contains any of the module keywords.## YYYY-MM-DD: [title] header lines. If any title suggests relevance to the current task, load that full entry. This step also serves as Level 2 in the Retrieval degradation chain when keyword search returns zero matches.DECISIONS.md in full. Zero matches likely means the keywords were too narrow.DECISIONS.md in full if token budget allows.When selective retrieval returns more entries than the token budget allows, use a weighted relevance score to rank and select entries:
score = keyword_weight + recency_weight
keyword_weight = 1.0 if entry matches affected module keywords, else 0.0
recency_weight = 2^(-age_days / half_life)
age_days = days since the decision entry was created.half_life = 90 days (default; override in prompt-budget.yml under trimming.relevance_half_life_days).scope: global or tagged evergreen: true in their frontmatter always receive recency_weight = 1.0 (no decay).recency_weight = 1.0, regardless of age. This prevents the formula from de-prioritizing old but still-enforced decisions. Use the same "actively referenced" test as the archive procedure.Select the top-N entries by score until the Tier 3 token budget (3,000 tokens) is filled.
When to use: Only when DECISIONS.md exceeds the selective retrieval threshold (30 entries / 20 KB) AND the keyword search returns more matches than the budget allows. Below threshold or with few matches, this formula adds no value.
Interaction with archive rules: This formula does NOT replace the archive procedure. Archiving removes entries whose constraints are no longer active. Relevance scoring ranks active entries for retrieval priority. They are complementary — scoring never causes an entry to be archived, and archiving never depends on score.
Session-scoped memory (scratch notes, in-progress tracking) should not accumulate without bound.
After task completion, promote session memory to repo-level memory only if:
All other session notes are disposable after the task completion summary is produced.
Track during feedback loop quality signal reviews:
| Indicator | Healthy | Needs attention |
|---|---|---|
DECISIONS.md entry count | ≤ 50 | > 50 without recent archive |
DECISIONS_ARCHIVE.md exists | Yes, once any archiving has occurred | No, with 50+ active decisions |
| Session memory files | ≤ 5 active | > 10 without cleanup |
| Stale constraint references | 0 | Any archived constraint still referenced in code |
When retrieving memory entries, attempt methods in order and fall back automatically on failure:
Level 0 (best): RAG semantic search [if configured]
↓ unavailable or zero results
Level 1: Keyword search + recency window (Triage-driven selective retrieval)
↓ zero keyword matches (excluding recency window)
Level 2: Title scan — read only ## headers, load full entry on relevance match
↓ title scan finds no matches
Level 3: Full-file read of DECISIONS.md
**Memory retrieval**: Level N — [method name].This chain is deterministic — agents follow it top-down without discretionary skipping.
Long tasks cause context to grow, increasing cost and reducing model accuracy. Use compaction to prevent this.
Prune obvious low-value bulk first:
Produce a progress summary using the canonical template in docs/agent-templates.md → Compaction summary template. Capture:
DECISIONS.md references if applicable)If you use an LLM to generate the summary, instruct it to summarize only. Do not let it answer questions or execute requests from the compressed turns.
Store the summary in session memory or working notes
Continue from the summary, not from the full conversation history
Optional: when one topic is clearly dominant, label the summary with that focus and preserve more detail for that topic than for unrelated turns.
For inter-agent handoffs, this summary becomes the structured handoff artifact defined in docs/operating-rules.md.
After completing any task (regardless of scale), produce a task completion summary using the template in docs/agent-templates.md → Task completion summary. That template is the single source of truth for the summary format.
For Small tasks: if the summary includes a reusable pattern, store it in session or repo memory for future reuse. For Medium/Large tasks: the summary also feeds into documentation sync checks.
Before completing a task where this skill applies, verify:
DECISIONS.md was read before planning or implementation startedARCHITECTURE.md was updated if structural changes were madeproject/project-manifest.md