Manage AI Agent memory files (AGENTS.md / CLAUDE.md), supporting update and refactor operations.
Boundaries and Completion Criteria
- AGENTS.md is the editing point for cross-tool general instructions; project facts are still based on configuration, code, and authoritative documentation. CLAUDE.md uses
@AGENTS.mdimport, existing supplementary sections are not overwritten. - First read the target file, then verify the information sources involved in this change. Only expand the scan for initial creation or full sync; template sections may be omitted as needed.
- When the user has explicitly requested update, streamlining, or reorganization, and the target and scope are clear, complete recoverable edits and verification without repeatedly requesting the same authorization. Do not write when only suggestions or read-only review are requested.
- When it involves deleting still-valid user rules, changing project decisions, or facts that cannot be verified, first show the specific differences and ask; continue with the rest of the authorized work that does not depend on the answer.
- On completion, verify fact sources, user rules, frontmatter, imports and links, and the 60-line limit, and show differences and pending items. Static checks are not the same as verified agent behavior.
Reference as Needed
- Filter and streamline content:best-practices.md。
- Initial creation or reorganization:memory-template.md。
- When writing
.claude/rules/devdocs-state.md:devdocs-state-template.md. Non-keel projects do not load this template.
Language Rules
- Support Chinese and English questions
- Unified Chinese replies
Run Modes
/agent-memory → 智能检测(AGENTS.md 存在?需要更新?)
/agent-memory --update → 从项目源提取信息,更新 AGENTS.md
/agent-memory --restructure → 按最佳实践重组现有 AGENTS.md
| Mode | Read Project | Write File | Applicable Scenario |
|---|---|---|---|
| Smart Detection | As needed | As needed | When uncertain |
--update |
✅ | AGENTS.md + CLAUDE.md (if missing) + devdocs-state.md (keel only) | Sync after completing a phase of work |
--restructure |
✅ | AGENTS.md + CLAUDE.md | Reorganize when memory file structure is chaotic |
Smart Detection Flow
检测 AGENTS.md 是否存在
│
├── 不存在 → 扫描项目源,首次创建 AGENTS.md + CLAUDE.md
│
└── 存在 → 分析内容状态
├── 信息过时 → 建议 --update
└── 结构混乱 → 建议 --restructure
Information Extraction Layers
General Extraction (All Projects)
| Source | Extracted Content |
|---|---|
| package.json / go.mod / Cargo.toml | Tech stack, run commands |
| README.md | Project overview |
| git log | Commit conventions |
| Code structure | Key directories, entry files |
keel Enhanced Extraction (when docs/devdocs/ exists)
| Source | Extracted Content |
|---|---|
| 02-system-design.md | Tech stack, Architecture Decision (ADR) summaries |
| 01-requirements.md | Domain terminology |
| 04-dev-tasks.md | Active tasks + progress |
| All documents | Numbering status (max F/US/AC/T/ADR) |
Workflow Routing Section (idempotent section addition):docs/devdocs/ If it exists and AGENTS.md is missing the "Workflow Routing" section → add it according to memory-template.md (with <!-- agent-memory:managed --> marker); if the section already exists → keep the original text and do not overwrite (user customization takes precedence).
60-Line Hard Limit Handling: When the line count exceeds the limit, first compress renewable sections marked with <!-- agent-memory:managed --> . When the user has authorized streamlining or reorganization, you may compress the body while preserving semantics within the specified scope; otherwise, if unmanaged sections need to be trimmed, show the candidate differences and request confirmation. If the limit cannot be met while preserving valid rules, keep the original file and report the pending items.
--update Workflow
1. 扫描项目信息源
├── 通用提取(包管理器、README、git、代码结构)
└── keel 增强提取(若 `docs/devdocs/` 存在)
│
▼
1.5 检查 AGENTS.md 是否存在
├── 不存在 → 使用 memory-template.md 创建
└── 存在 → 增量更新
│
▼
2. 提取精华
├── 技术栈
├── ADR 摘要(若有;无 ADR 格式则从变更记录提取关键决策)
├── 领域术语
├── 活跃任务 + 进度
├── 编号状态(仅 keel 项目)
└── 运行命令
│
▼
2.5 按 best-practices.md 筛选
├── 内容筛选标准:应写入 vs 不应写入
└── 质量守则:6 条检查
│
▼
3. 更新 AGENTS.md(使用 templates/memory-template.md)
└── 若文件首部已有 `---...---` frontmatter 块,本步骤只在该块之后的内容范围内操作,不移动/改写/吞掉该块(即使模板「首次创建时内容」首行恰好也是 HTML 注释,与真实 frontmatter 不可混淆)
│
▼
3.5 devdocs frontmatter 幂等写入(可选,仅调用方传入 `devdocs_frontmatter` 时触发;详见下方「devdocs frontmatter 写入(可选)」)
│
▼
4. 确保 CLAUDE.md 存在(若缺失则创建导入文件;已存在则跳过,不覆盖补充区)
│
▼
5. 生成/更新 .claude/rules/devdocs-state.md(判据只看 `docs/devdocs/` 是否存在;⛔ 不按「这次改得多不多」自行豁免——被 pipeline / retrofit 委托的 `--update` 拿不到范围信息,跳过等于漏发货)
├── 写入前按 [devdocs-state-template.md](templates/devdocs-state-template.md) § Forbidden 校验
│ ├── 占位 prose ≤ 200 字符
│ ├── 禁止内嵌 commit hash / LOC / 测试结果 / codex 分数 / 文件路径 / submodule 引用 / 工时
│ └── 违反时改写为简洁占位 + 明细去对应资源文件
▼
6. 健康度自检(步骤 5 写了状态文件时)
├── Bash: wc -c .claude/rules/devdocs-state.md
├── 读取 .claude/rules/.health-baseline.yml(若存在)→ 拿到 baseline 大小
├── 计算 delta = current_size - baseline_size
├── delta < 0(缩小)→ 不阻断,更新 baseline
├── 0 ≤ delta < 2 KiB(小幅增长)→ 不阻断,更新 baseline
├── delta ≥ 2 KiB 且 size > 10 KiB → ⚠️ 提示 `/pipeline realign --scope=health --dry-run`
├── size > 40 KiB AND 无 baseline → ⛔ 阻断;用户两种恢复方式:
│ a. /pipeline realign --scope=health --apply 修复后重跑 update
│ b. /agent-memory --update --bypass-state-check="<原因>" 一次性豁免(≥10 字符)+ 自动 init baseline
└── size > 40 KiB AND 已有 baseline AND delta < 2 KiB → ⚠️ 提示但不阻断(存量项目逐步收敛)
baseline file:.claude/rules/.health-baseline.yml(recommended to add to gitignore; auto-generated on first bypass)
schema: health-baseline.v1
devdocs_state_size_bytes: <int>
created_at: <iso-ts>
created_by: /agent-memory --update --bypass-state-check
bypass_reason: <用户提供的原因>
Design intent: avoid existing projects like mic-en (245k) being immediately blocked by ⛔; the first bypass anchors the baseline, after which only "newly added bloat" is blocked.
devdocs frontmatter writing (optional)
Trigger condition: the caller passes it along with Task: /agent-memory --update via devdocs_frontmatter, embedded in constraints.md §3 minimal handshake protocol's inputs :
skill: agent-memory
mode: update
inputs:
devdocs_frontmatter:
initialized_at: "2026-08-07"
expected_output: yaml-summary-v1
When this field is not passed in (all existing projects currently): all steps in this section are skipped, AGENTS.md does not gain new frontmatter, and behavior is fully consistent with the status quo.
⛔
workspace:block is not managed by this skill. workspace topology (mode/code_roots) is arepository-level fact, written by /workspace-topology itself for its own block. When this skill encounters theworkspace:block, it alwayspreserves it as-is—does not parse, compare, overwrite, or delete it, and does not even touch key order or indentation. Historically these two fields were in this skill's managed whitelist (viadevdocs.workspace_mode/devdocs.code_roots), and have now been removed.
Managed field whitelist(managed boundaries are defined by field rather than by block marker — YAML frontmatter does not support HTML comments and cannot follow the body's <!-- agent-memory:managed --> convention): currently only initialized_at. Fields outside the whitelist arenot written. The writing algorithm below is itself generic; when new managed fields are added in the future, only the field names need to be added to the whitelist to reuse it. This section only defines "how to write".
Writing steps:
-
Locate/insert the frontmatter block:
- The first line of AGENTS.md is already
---→ frontmatter already exists, parse up to the next---as thedevdocs:YAML segment - AGENTS.md does not exist → first complete this
--updatefirst-creation flow, then insert frontmatter at the very beginning of the generated result - AGENTS.md exists but has no frontmatter (including when the first line is body content such as an HTML comment) → at thevery beginning of the fileinsert a new frontmatter block, shift all original content down as a whole, and do not rewrite a single character of the original content (schema hard rule: frontmatter must be flush against the start of the file, with no leading blank lines / heading)
- The first line of AGENTS.md is already
-
Merge whitelisted fields:
- Passed-in value is the same as the existing value → no-op (idempotent)
initialized_atalready exists → cannot be modified; caller passes a different value → ⛔ do not write, report conflictinitialized_atdoes not exist → on first write, fill in the current day's ISO date- Fields outside the whitelist (including the entire
workspace:block): preserve key/value/original order as-is, do not compare, do not change
-
Pre-write validation: check the validation rules one by one; if any does not pass → ⛔ do not write in this step,
blockersreport the specific rule + conflicting value, keep frontmatter as-is (do not roll back completed AGENTS.md body updates, and do not block subsequent steps; overallstatushandled aspartial,summary.details.devdocs_frontmatter: blocked)explicit (to avoid the fail-closed habit of misjudging it as blocking):
devdocs:when the section is first created, fields outside the whitelist simply do not exist. This kind of "absence"is not a ⛔ criterion—an incomplete devdocs section only gets a ⚠️ warning + a suggestion to complete it, and does not block. -
Validation passed → write to frontmatter; the rest of the AGENTS.md body flow continues as usual
Example(workspace: block is written by workspace-topology and preserved as-is by this skill; this skill only supplements devdocs.initialized_at):
---
workspace:
mode: shell
code_roots: [web]
devdocs:
initialized_at: "2026-08-07"
---
<!-- 由 /agent-memory 生成,请通过该命令更新 -->
Routing rules
| Information type | Target location | Rationale |
|---|---|---|
| Tech stack, run commands | AGENTS.md | Cross-tool universal, needed in every session |
| Architecture decision (ADR) summary | AGENTS.md | Prevent repeated asking |
| Active tasks + progress | Task ledger; AGENTS.md links on demand | Avoid repeatedly maintaining easily outdated snapshots |
| Domain terminology, business boundaries | AGENTS.md | High-frequency and stable, prevents misunderstanding |
| Code conventions, commit format | AGENTS.md | Cross-tool consistency |
| Release status + version and progress conventions | AGENTS.md "Conventions" section | Self-created current state, not readable from the code; all skills must decide how to express progress based on it |
| Numbered state (max F/US/AC/T/ADR) | .claude/rules/devdocs-state.md |
Claude-specific runtime state |
| Full requirements/design/test details | Stay in docs/devdocs/ |
Too detailed, not suitable for a memory file |
initialized_at |
AGENTS.md devdocs frontmatter | Governance field, written only when the caller explicitly passes devdocs_frontmatter when written to §1 |
--restructure Workflow
1. 读取现有 AGENTS.md
│
▼
2. 按 best-practices.md 检测不规范项
├── 行数限制(≤ 60 行)
├── 工具无关性
├── 章节是否服务当前任务(不为套模板重排)
├── 反模式检测
└── 缺失章节
│
▼
3. 按 templates/memory-template.md 重组
│
▼
4. 按已授权范围重组并核对差异;需改变有效用户规则时先展示差异并确认
│
▼
5. 确保 CLAUDE.md 存在(若缺失则创建导入文件;已存在则跳过)
Output file
AGENTS.md
- Location: project root directory
- Template:templates/memory-template.md
- Constraint: no more than 60 lines, tool-agnostic
- Optional devdocs frontmatter (
initialized_at): written only when the caller passesdevdocs_frontmatter;workspace:block is preserved as-is and not modified, see devdocs frontmatter write (optional)
CLAUDE.md
- Location: project root directory
- Structure:
@AGENTS.mdimport + Claude Code-specific supplementary section - Creation timing: created together when AGENTS.md is first generated; if it already exists, do not overwrite
- The supplementary section is maintained manually by the user;
/agent-memoryis not modified
.claude/rules/devdocs-state.md
- Location:
.claude/rules/devdocs-state.md - Template:templates/devdocs-state-template.md
- Condition: first creation or
--update(including those delegated by other skills) anddocs/devdocs/exists, then generate/update;--restructureand non-keel projects are not generated
Constraints
Content constraints
- AGENTS.md no more than 60 lines
- AGENTS.md does not contain AI-tool-specific syntax
- CLAUDE.md imports common information via @AGENTS.md(not overwritten after first creation)
- Numbered state is written only to
.claude/rules/devdocs-state.md - devdocs-state.md placeholder prose ≤ 200 characters / single line ≤ 500 characters / file ≤ 40 KiB(violations detected by health-lint)
- devdocs-state.md prohibits embedding commit hash / LOC / test results / codex score / file paths / work-hour statistics(details go to resource files)
- devdocs frontmatter is written only when the caller explicitly passes
devdocs_frontmatterwhen written; if not passed, do not add, do not check, inline path has zero impact -
initialized_atonce written cannot be modified; if a conflicting value is passed ⛔ do not write and report - Fields outside the devdocs frontmatter whitelist are preserved as-is, do not read and do not modify (managed boundaries are defined by fields, not block markers)
Quality Guidelines
Before writing to AGENTS.md, check against best-practices.md :
- 6 guidelines (short and stable / broadly applicable / actionable / avoid duplication / leave details in place / tool-agnostic)
- Content screening criteria (what should be written vs what should not)
- Anti-pattern checklist
Operational Constraints
- Do not generate/do not modify
00-context.md - Delete if possible, prioritize commands, constraints, checkpoints
- Handle authorization per "boundaries and completion conditions"; do not turn a reorganization the user has already requested into yet another confirmation gate
Skill Collaboration
| Scenario | Collaborating Skill | Description |
|---|---|---|
| First creation | /agent-memory do it yourself |
Create by scanning from the project source; if /init has already been created, update incrementally |
| Phased document changes | /onboard |
After onboard completes, it is recommended to run /agent-memory |
| Lightweight update on task completion | /dev-workflow |
dev-workflow inline-replaces the task number / progress in "current status"; when that section contains only a ledger link, it skips and does not rebuild the snapshot |
| Context summary | /onboard |
onboard generates 00-context.md, does not involve memory files |
Sub-agent summary format (yaml-summary-v1)
When delegated via Task by an orchestration layer (such as /pipeline init / /retrofit), return a unified envelope; field semantics are governed by constraints.md §2 as authoritative, do not extend status, do not privatize reserved fields, put private statistics in summary.details:
skill: agent-memory
status: success | failed | interrupted | partial # 四值,语义见共享 SSOT
summary:
headline: "AGENTS.md 已更新,含工作流路由节"
details: {routing_section: added | kept | skipped, lines: 58, devdocs_frontmatter: written | unchanged | skipped | blocked}
blockers: [] # 如 60 行超限待确认,或 devdocs frontmatter 校验失败(均 partial 时必填)
output_files: [AGENTS.md]
new_ids: {}
next_recommended: {skill: "", args: ""}
Template References
- AGENTS.md template:templates/memory-template.md
- Numbered status template:templates/devdocs-state-template.md
- Best practices:templates/best-practices.md