{"id":"d05fe828-0f69-4488-bde3-4d425e023aaf","entityType":"agent","slug":"clawhub-biociao-apm-agent-progressive-memory","name":"Apm Agent Progressive Memory","canonicalUrl":"https://www.xpersona.co/agent/clawhub-biociao-apm-agent-progressive-memory","canonicalPath":"/agent/clawhub-biociao-apm-agent-progressive-memory","generatedAt":"2026-10-11T07:40:11.762Z","source":"CLAWHUB","claimStatus":"UNCLAIMED","verificationTier":"NONE","summary":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"medium","updatedAt":"2026-10-11T04:21:34.523Z","emptyReason":null},"description":"APM Protocol (Agent Progressive Memory): Progressive disclosure protocol for group chat AND DM (main session) memory.","descriptionLabel":"Source description","evidenceSummary":"Capability contract not published. No trust telemetry is available yet. 1.2K downloads reported by the source. Last updated 10/11/2026.","installCommand":"clawhub skill install s17dtx203kvnxrae9yp2v5epcn83kj3f:apm-agent-progressive-memory","sourceUrl":"https://clawhub.ai/biociao/apm-agent-progressive-memory","homepage":"https://clawhub.ai/biociao/skills/apm-agent-progressive-memory","primaryLinks":[{"label":"View on ClawHub","url":"https://clawhub.ai/biociao/apm-agent-progressive-memory","kind":"source"},{"label":"Homepage","url":"https://clawhub.ai/biociao/skills/apm-agent-progressive-memory","kind":"homepage"}],"safetyScore":84,"overallRank":62,"popularityScore":61,"trustScore":null,"claimedByName":null,"isOwner":false,"seoDescription":"Apm Agent Progressive Memory technical dossier on Xpersona with agent coverage, OPENCLEW support, and live trust metadata."},"coverage":{"evidence":{"source":"public-profile","verified":false,"confidence":"medium","updatedAt":"2026-10-11T04:21:34.523Z","emptyReason":null},"protocols":[{"protocol":"OPENCLEW","label":"OpenClaw","status":"self-declared","notes":"Declared in the public agent profile."}],"capabilities":[],"verifiedCount":0,"selfDeclaredCount":1,"capabilityMatrix":{"rows":[{"key":"OPENCLEW","type":"protocol","support":"unknown","confidenceSource":"profile","notes":"Listed on profile"}],"flattenedTokens":"protocol:OPENCLEW|unknown|profile"}},"adoption":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"medium","updatedAt":"2026-10-11T04:21:34.523Z","emptyReason":null},"stars":null,"forks":null,"downloads":1161,"packageName":null,"latestVersion":"1.6.1","tractionLabel":"1.2K downloads"},"release":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"medium","updatedAt":"2026-10-11T04:21:34.455Z","emptyReason":null},"lastUpdatedAt":"2026-10-11T04:21:34.523Z","lastCrawledAt":"2026-10-11T04:21:34.455Z","lastIndexedAt":null,"nextCrawlAt":"2026-10-12T04:21:34.455Z","lastVerifiedAt":null,"highlights":[{"version":"1.6.1","createdAt":"2026-06-20T16:25:14.508Z","changelog":"**Summary:** Introduced dedicated session start hook and improved group name mapping. - Added new `apm_session_start` hook for memory initialization and entry handling. - Moved group name mapping file to `memory/groups/group_names.json` (from `memory/group_names.json`). - Removed deprecated bootstrap script and related hook files. - Updated docs to clarify agent vs. hook responsibilities for memory initialization and first-join flows. - Minor refinements to loading rules and file structure explanations.","fileCount":13,"zipByteSize":29348},{"version":"1.6.0","createdAt":"2026-06-17T17:32:45.353Z","changelog":"v1.6.0 (2026-06-18) NEW: bootstrap.sh — idempotent initialization/repair script that creates memory/main/ DM entry, group indexes, standard sub-files, and flush-state.json. Flags: --yes, --dry-run, --group NAME, --workspace PATH. Sandbox-safe. NEW: apm-bootstrap hook (bundled in hooks/apm-bootstrap/) — auto-runs bootstrap.sh --yes on agent:bootstrap and gateway:startup events. Resolves bootstrap.sh across 4 install paths. Configurable (autoYes, coldStartOnly, onlyGroup). UPDATED: SKILL.md — added Bundled Bootstrap Script and Bundled Hooks sections. UPDATED: HOOKS.md — added full apm-bootstrap hook docs (config, install, safety, tuning). UPDATED: handler.js — multi-path resolution (was single-path heuristic). FIX: Cold-start initialization gap. Before: a fresh install of APM sat dormant — no groups got auto-initialized, no DM entry created. After: any group in group_names.json + memory/main/ + flush-state.json all auto-created on first agent startup.","fileCount":12,"zipByteSize":24647},{"version":"1.5.0","createdAt":"2026-05-19T05:23:21.317Z","changelog":"Split into 3 files: SKILL.md (core protocol), ADDENDUM.md (templates/details), HOOKS.md (hooks); Support both group and DM; Flush: /remem + Pre-compact + Idle 30min","fileCount":9,"zipByteSize":12429},{"version":"1.4.3","createdAt":"2026-05-19T04:54:58.692Z","changelog":"Update flush triggers: /remem + Pre-compact + Idle 30min (no repeat); Remove cron schedule","fileCount":6,"zipByteSize":13402},{"version":"1.4.2","createdAt":"2026-05-19T04:50:08.443Z","changelog":"Add: tested Evening cron format; Auto-flush on idle (30min); Precompact-remem hook documentation","fileCount":6,"zipByteSize":13578},{"version":"1.4.1","createdAt":"2026-05-19T01:29:51.053Z","changelog":"Fix: DM progressive disclosure guide in AGENTS.md (not SOUL.md), MEMORY.md unchanged, longterm.md as experience summary + detail supplement layer","fileCount":6,"zipByteSize":12849},{"version":"1.4.0","createdAt":"2026-05-19T01:21:45.158Z","changelog":"Add DM (main session) progressive disclosure layout, independent from group chat system, compatible with original MEMORY.md after uninstall","fileCount":6,"zipByteSize":12143},{"version":"1.3.2","createdAt":"2026-05-19T01:16:47.626Z","changelog":"Add APM alias convention to SKILL.md","fileCount":6,"zipByteSize":10385}]},"execution":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"low","updatedAt":null,"emptyReason":"No published capability contract is available yet."},"installCommand":"clawhub skill install s17dtx203kvnxrae9yp2v5epcn83kj3f:apm-agent-progressive-memory","setupComplexity":"low","setupSteps":["Install using `clawhub skill install s17dtx203kvnxrae9yp2v5epcn83kj3f:apm-agent-progressive-memory` in an isolated environment before connecting it to live workloads.","No published capability contract is available yet, so validate auth and request/response behavior manually.","Review the upstream CLAWHUB listing at https://clawhub.ai/biociao/apm-agent-progressive-memory before using production credentials."],"contract":{"contractStatus":"missing","authModes":[],"requires":[],"forbidden":[],"supportsMcp":false,"supportsA2a":false,"supportsStreaming":false,"inputSchemaRef":null,"outputSchemaRef":null,"dataRegion":null,"contractUpdatedAt":null,"sourceUpdatedAt":null,"freshnessSeconds":null},"invocationGuide":{"preferredApi":{"snapshotUrl":"https://www.xpersona.co/api/v1/agents/clawhub-biociao-apm-agent-progressive-memory/snapshot","contractUrl":"https://www.xpersona.co/api/v1/agents/clawhub-biociao-apm-agent-progressive-memory/contract","trustUrl":"https://www.xpersona.co/api/v1/agents/clawhub-biociao-apm-agent-progressive-memory/trust"},"curlExamples":["curl -s \"https://www.xpersona.co/api/v1/agents/clawhub-biociao-apm-agent-progressive-memory/snapshot\"","curl -s \"https://www.xpersona.co/api/v1/agents/clawhub-biociao-apm-agent-progressive-memory/contract\"","curl -s \"https://www.xpersona.co/api/v1/agents/clawhub-biociao-apm-agent-progressive-memory/trust\""],"jsonRequestTemplate":{"query":"summarize this repo","constraints":{"maxLatencyMs":2000,"protocolPreference":["OPENCLEW"]}},"jsonResponseTemplate":{"ok":true,"result":{"summary":"...","confidence":0.9},"meta":{"source":"CLAWHUB","generatedAt":"2026-10-11T07:40:11.761Z"}},"retryPolicy":{"maxAttempts":3,"backoffMs":[500,1500,3500],"retryableConditions":["HTTP_429","HTTP_503","NETWORK_TIMEOUT"]}},"endpoints":{"dossierUrl":"https://www.xpersona.co/api/v1/agents/clawhub-biociao-apm-agent-progressive-memory/dossier","snapshotUrl":"https://www.xpersona.co/api/v1/agents/clawhub-biociao-apm-agent-progressive-memory/snapshot","contractUrl":"https://www.xpersona.co/api/v1/agents/clawhub-biociao-apm-agent-progressive-memory/contract","trustUrl":"https://www.xpersona.co/api/v1/agents/clawhub-biociao-apm-agent-progressive-memory/trust"}},"reliability":{"evidence":{"source":"runtime-metrics","verified":false,"confidence":"low","updatedAt":null,"emptyReason":"No trust, reliability, or runtime telemetry is available."},"trust":{"status":"unavailable","handshakeStatus":"UNKNOWN","verificationFreshnessHours":null,"reputationScore":null,"p95LatencyMs":null,"successRate30d":null,"fallbackRate":null,"attempts30d":null,"trustUpdatedAt":null,"trustConfidence":"unknown","sourceUpdatedAt":null,"freshnessSeconds":null},"decisionGuardrails":{"doNotUseIf":["Contract metadata is missing or unavailable for deterministic execution."],"safeUseWhen":[],"riskFlags":["missing_or_unavailable_contract","trust_data_unavailable","schema_references_missing"],"operationalConfidence":"low"},"executionMetrics":{"observedLatencyMsP50":null,"observedLatencyMsP95":null,"estimatedCostUsd":null,"uptime30d":null,"rateLimitRpm":null,"rateLimitBurst":null,"lastVerifiedAt":null,"verificationSource":null},"runtimeMetrics":{"successRate":null,"avgLatencyMs":null,"avgCostUsd":null,"hallucinationRate":null,"retryRate":null,"disputeRate":null,"p50Latency":null,"p95Latency":null,"lastUpdated":null}},"benchmarks":{"evidence":{"source":"no-benchmark-data","verified":false,"confidence":"low","updatedAt":null,"emptyReason":"No benchmark suites or observed failure patterns are available."},"suites":[],"failurePatterns":[]},"artifacts":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"medium","updatedAt":"2026-10-11T04:21:34.523Z","emptyReason":null},"readme":"Skill: Apm Agent Progressive Memory\n\nOwner: biociao\n\nSummary: APM Protocol (Agent Progressive Memory): Progressive disclosure protocol for group chat AND DM (main session) memory.\n\nTags: latest:1.6.1\n\nVersion history:\n\nv1.6.1 | 2026-06-20T16:25:14.508Z | user\n\n**Summary:** Introduced dedicated session start hook and improved group name mapping.\n\n- Added new `apm_session_start` hook for memory initialization and entry handling.\n- Moved group name mapping file to `memory/groups/group_names.json` (from `memory/group_names.json`).\n- Removed deprecated bootstrap script and related hook files.\n- Updated docs to clarify agent vs. hook responsibilities for memory initialization and first-join flows.\n- Minor refinements to loading rules and file structure explanations.\n\nv1.6.0 | 2026-06-17T17:32:45.353Z | user\n\nv1.6.0 (2026-06-18)\n\nNEW: bootstrap.sh — idempotent initialization/repair script that creates memory/main/ DM entry, group indexes, standard sub-files, and flush-state.json. Flags: --yes, --dry-run, --group NAME, --workspace PATH. Sandbox-safe.\n\nNEW: apm-bootstrap hook (bundled in hooks/apm-bootstrap/) — auto-runs bootstrap.sh --yes on agent:bootstrap and gateway:startup events. Resolves bootstrap.sh across 4 install paths. Configurable (autoYes, coldStartOnly, onlyGroup).\n\nUPDATED: SKILL.md — added Bundled Bootstrap Script and Bundled Hooks sections.\nUPDATED: HOOKS.md — added full apm-bootstrap hook docs (config, install, safety, tuning).\nUPDATED: handler.js — multi-path resolution (was single-path heuristic).\n\nFIX: Cold-start initialization gap. Before: a fresh install of APM sat dormant — no groups got auto-initialized, no DM entry created. After: any group in group_names.json + memory/main/ + flush-state.json all auto-created on first agent startup.\n\nv1.5.0 | 2026-05-19T05:23:21.317Z | user\n\nSplit into 3 files: SKILL.md (core protocol), ADDENDUM.md (templates/details), HOOKS.md (hooks); Support both group and DM; Flush: /remem + Pre-compact + Idle 30min\n\nv1.4.3 | 2026-05-19T04:54:58.692Z | user\n\nUpdate flush triggers: /remem + Pre-compact + Idle 30min (no repeat); Remove cron schedule\n\nv1.4.2 | 2026-05-19T04:50:08.443Z | user\n\nAdd: tested Evening cron format; Auto-flush on idle (30min); Precompact-remem hook documentation\n\nv1.4.1 | 2026-05-19T01:29:51.053Z | user\n\nFix: DM progressive disclosure guide in AGENTS.md (not SOUL.md), MEMORY.md unchanged, longterm.md as experience summary + detail supplement layer\n\nv1.4.0 | 2026-05-19T01:21:45.158Z | user\n\nAdd DM (main session) progressive disclosure layout, independent from group chat system, compatible with original MEMORY.md after uninstall\n\nv1.3.2 | 2026-05-19T01:16:47.626Z | user\n\nAdd APM alias convention to SKILL.md\n\nv1.3.1 | 2026-05-19T01:14:04.515Z | user\n\nRename to APM-agent-progressive-memory\n\nv1.3.0 | 2026-05-18T19:12:43.889Z | user\n\nRenamed from agent-progressive-memory to memoir/progressive-memory-v2. Added /remem all support, fixed hook exports, improved flush detection.\n\nv1.0.0 | 2026-05-14T06:06:55.387Z | user\n\nInitial release\n\nArchive index:\n\nArchive v1.6.1: 13 files, 29348 bytes\n\nFiles: _meta.json (147b), .clawhub/origin.json (160b), ADDENDUM.md (8867b), CHANGELOG.md (3282b), HOOKS.md (4630b), hooks/apm_session_start/handler.js (16088b), hooks/apm_session_start/HOOK.md (8354b), hooks/precompact-remem/handler.js (4685b), hooks/precompact-remem/HOOK.md (1960b), hooks/remem-flush/handler.js (5606b), hooks/remem-flush/HOOK.md (2240b), skill-card.md (2462b), SKILL.md (12225b)\n\nFile v1.6.1:SKILL.md\n\n---\nname: APM-agent-progressive-memory\ndescription: \"APM Protocol (Agent Progressive Memory): Progressive disclosure protocol for group chat AND DM (main session) memory.\"\n---\n\n# APM — Progressive Disclosure Protocol\n\nAPM supports **both group chat and private (main session DM)** memory management. The two structures are completely independent and do not interfere with each other.\n\n## Group vs DM: Strategy Comparison\n\n| Aspect | Group Chat | DM (Main Session) |\n|-------|-----------|-------------------|\n| **Memory path** | `memory/groups/{group_name}/` | `memory/main/` |\n| **Loading** | 5-step progressive (index → P0 → P1 → P2 → P3) | 3-layer progressive (index → attention → longterm) |\n| **Index file** | `memory/groups/{group_name}.md` | `memory/main/index.md` |\n| **Priority files** | attention.md, project.md, experience.md, people.md | attention.md, longterm.md |\n| **Entry rule** | Must read index first, no subdirectory bypass | Must read index first |\n| **Flush trigger** | Per-group flush on `/remem` | Full-session flush on `/remem` |\n\n**Key differences**:\n- Group uses **5-step loading** with budget controls; DM uses simpler **3-layer**\n- Group has **conventions/** sub-directory; DM does not\n- DM reuses existing **MEMORY.md**; Group uses dedicated files\n- Uninstaller: Group loses memory access; DM retains MEMORY.md\n\nAgent must follow the **layered disclosure protocol** when accessing memory in group chats: read the index first, then load layers on demand.\n\n## Core Rules\n\n### 1. Entry Gate\n\n- The **only legal entry point** for group chat memory is `memory/groups/{group_name}.md` (index file)\n- **Forbidden**: directly reading any sub-files under `memory/groups/{group_name}/`\n- **Forbidden**: bypassing the index to directly `memory_search` subdirectories\n- **Group name mapping rule**: group chat room IDs must first be resolved via `memory/groups/group_names.json` to a friendly name `{group_name}` before use\n\n### 2. Five-Step Loading Flow\n\n| Step | Action | Output |\n|------|--------|--------|\n| 0. Group name mapping | Check `memory/groups/group_names.json`, convert room ID to `{group_name}` | Friendly name |\n| 1. Route to index | `memory_get(\"memory/groups/{group_name}.md\")` | Hard Rules + routing table |\n| 2. Intent matching | Match current message to trigger scenario | File to load |\n| 3. Explicit load | `memory_get(\"memory/groups/{group_name}/{file}.md\")` | Actual memory content |\n| 4. Sub-layer control | Load only if Step 3 file references `conventions/` | 1 sub-file max |\n| 5. Budget circuit-breaker | Stop when cumulative tokens exceed `memory_budget` | Stop loading |\n\nOnly **one** best-matching file is loaded per session (highest priority wins).\n\n### 3. Loading Discipline\n\n- **Per group chat (5-step flow)**:\n  - Step 3 loads **1 P-file** (highest-priority match) per session\n  - Step 4 may load **1 sub-file** under `conventions/` (only if Step 3 referenced it)\n  - **Total ceiling**: 2 P0–P2 files + 1 P3 file (per AGENTS.md layering)\n- **Per DM session (3-layer flow)**:\n  - Layer 0: `memory/main/index.md` (always)\n  - Layer 1: up to **2 P-files** from attention/longterm/daily-synced/projects\n- When switching group chats, clear old context first, then restart from Step 1\n\n### 4. Write-Back on Updates\n\n- New decision → append to `experience.md`\n- Task status change → update `attention.md`\n- Index files: append-only (mark deleted entries `[DEPRECATED]` instead of removing)\n\n### 5. Memory Flush\n\n| Trigger | Condition | Action |\n|---------|-----------|--------|\n| `/remem` | User manual trigger | Full flush |\n| Pre-compact | Context near limit | Auto-flush before loss |\n| Idle timeout | 30min inactive, no flush | One-time auto-flush |\n\n### 6. Auto-Initialization on Missing Memory\n\n> When a flush is triggered for a session whose memory system has **not yet been initialized**, the Agent must initialize it based on available information.\n\n| Scenario | Action | Who does it |\n|----------|--------|-------------|\n| Group index missing (`memory/groups/{name}.md`) | Create from `memory/groups/group_names.json` + context; ask group \"purpose\" if first-join | `apm_session_start` hook skips injection; **agent** handles per AGENTS.md \"First-Join Flow\" |\n| DM index missing (`memory/main/index.md`) | Create from `MEMORY.md` content | `apm_session_start` hook skips injection; **agent** handles per AGENTS.md \"Every Session\" |\n| `memory/groups/group_names.json` missing | Create from existing room id list (if any) | Operator (out of band) |\n\n**Initialization is not overwriting**: existing files are never overwritten — only created when completely absent.\n\n> ⚠️ The `apm_session_start` hook handles the **read** side (skip injection if index missing → defer to agent). The **write** side (create the index) is always the agent's responsibility. The hook never writes to memory files.\n\n## File Structure\n\n```\nmemory/groups/\n├── {group_name}.md          # L0: Entry gate (mandatory read)\n└── {group_name}/             # Group memory (direct access forbidden)\n    ├── attention.md          # P0: Current focus\n    ├── project.md            # P1: Project static info\n    ├── experience.md         # P2: Experience / decision log\n    ├── people.md             # P3: People profiles\n    └── conventions/          # L3: Detailed specifications\n        ├── api.md\n        └── ...\n\nmemory/main/                    # DM progressive disclosure\n├── index.md                # L0: DM entry index\n├── attention.md            # P0: Current tasks, blockers\n├── longterm.md             # P1: MEMORY.md distilled summary\n├── daily-synced.md         # P2: Daily notes summary\n└── projects/               # P3: Project context\n    └── {name}.md\n```\n\n## Priority Definitions\n\n### Group Chat (P0–P3)\n\n| Priority | File | Content | When to Load |\n|----------|------|---------|--------------|\n| P0 | `attention.md` | Active tasks, blockers | Any work conversation |\n| P1 | `project.md` | Tech stack, architecture | Technical decisions |\n| P2 | `experience.md` | Lessons learned | Search hit + append |\n| P3 | `people.md` | Team roles, contacts | Need to find someone |\n\n### DM (Main Session)\n\n| Priority | File | Content | When to Load |\n|----------|------|---------|--------------|\n| P0 | `memory/main/attention.md` | Active tasks, blockers | Always (cold start) |\n| P1 | `memory/main/longterm.md` | MEMORY.md distilled summary | When project context needed |\n| P2 | `memory/main/daily-synced.md` | Daily notes summary | Recent activity context |\n| P3 | `memory/main/projects/{name}.md` | Project-specific deep context | Project-specific questions |\n\n> DM uses **3-layer progressive loading** (not 4-P like group): the\n> index → attention → longterm, with daily-synced and projects/ loaded\n> on-demand per the routing table in `memory/main/index.md`.\n\n## MEMORY.md Discipline (v1.6.0)\n\n> ⚠️ `MEMORY.md` is the **authoritative long-term memory** but must remain **lean and stable**.\n> All project-level, event-level, and temporary information MUST go elsewhere.\n\n### ✅ Allowed in MEMORY.md\n\n| Category | Example | Reason |\n|----------|---------|--------|\n| Identity | Agent self-reference (role, style, principles) | Self-reference, stable |\n| User basics | Name, timezone, tech stack | Rarely changes |\n| Environment | Server host, key DB paths | Constants |\n| Project index | One-liner per project → file | Pointer, not content |\n| Other memory entry pointers | `memory/main/...`, `memory/groups/...` | Routing only |\n\n### ❌ Forbidden in MEMORY.md\n\n| Category | Where it goes instead |\n|----------|----------------------|\n| Project progress | `memory/main/projects/{name}.md` |\n| Event logs (incident, fix) | `memory/YYYY-MM-DD.md` |\n| Decisions & lessons | `memory/main/longterm.md` |\n| Tool lists (iqtree, bcftools...) | Runtime `which` / `command -v` |\n| Group chat metadata | `memory/groups/{name}.md` |\n| Temporary fix instructions | Daily notes (auto-rotate) |\n| Cross-snapshot result narratives | Project report files |\n\n### Rule of Thumb\n\n> - If a new agent could figure it out from `ls` or `which`, **don't write it to MEMORY.md**.\n> - If it's about a specific project, **write to `projects/{name}.md`**.\n> - If it changes more than once a month, **don't put it in MEMORY.md**.\n> - If `MEMORY.md` exceeds 50 lines, **it's bloated** — extract project details.\n\n### MEMORY.md Anti-Pattern\n\n```\n❌ 95 lines of \"long-term memory\" with project details\n❌ Tool lists that `which` can answer\n❌ Temporary fix notes lingering in MEMORY.md a month later\n❌ Group names listed directly\n❌ Event outcomes with specific samples or measurements\n\n✅ 30-line identity + index\n✅ Project index table → projects/{name}.md\n✅ Key events → daily notes + longterm index\n✅ Group chats → memory/groups/{name}.md\n```\n\n## File Templates\n\nAll file templates (MEMORY.md, projects/{name}.md, longterm.md, group index, attention) live in **ADDENDUM.md** → \"File Templates\" section. Use them as starting points.\n\n## DM Entry Loading (to add in AGENTS.md)\n\n```markdown\n## Every Session\n\n1. Read `SOUL.md` → USER.md → MEMORY.md\n2. **If in MAIN SESSION** (DM):\n   - Read `memory/main/index.md` — DM progressive index\n   - Based on routing, load up to 2 files\n   - Report `last flush: YYYY-MM-DD HH:mm` (from `memory/flush-state.json` — DM-only)\n3. Read `memory/YYYY-MM-DD.md` (today + yesterday)\n```\n\n> ⚠️ The `flush-state.json` referenced here is the **DM** flush state\n> (`memory/flush-state.json`), NOT the group one. See \"Flush State Files\"\n> above for the two-file split.\n\n## Flush State Files\n\nAPM uses **two separate flush-state files** to keep DM and group memory\nisolated:\n\n| File | Scope | Owner |\n|------|-------|-------|\n| `memory/flush-state.json` | DM (main session) | `remem-flush`, `precompact-remem`, `apm_session_start` (DM path) |\n| `memory/groups/flush-state.json` | Group chat | `remem-flush`, `precompact-remem`, `apm_session_start` (group path) |\n\nThis separation is a **privacy boundary** — group sessions must never\nread or write the DM flush-state (and vice versa).\n\n### `memory/flush-state.json` (DM)\n\n```json\n{\n  \"last_flush_time\": \"2026-06-20T17:20:23+08:00\",\n  \"flush_number\": 6,\n  \"context_usage_at_flush\": null,\n  \"pending_items\": [],\n  \"<file>_mtime\": \"ISO-8601\"  \n}\n```\n\n### `memory/groups/flush-state.json` (group)\n\nSame shape, scoped to one group. Multiple groups each have their own\nflush-state under `memory/groups/{name}/flush-state.json` (when groups\nare nested under a parent group name); the top-level\n`memory/groups/flush-state.json` aggregates across all groups.\n\n> The `mtime` keys are written by `remem-flush` and `precompact-remem` to\n> enable delta-only flushes. See HOOKS.md → \"Shared Conventions\".\n\n## Anti-Pattern\n\n```\n❌ Load all at once        → ✅ Load only one at a time\n❌ Skip index           → ✅ Read index first\n❌ Load two groups      → ✅ Clear old, reload from Step 1\n```\n\n## Complete Protocol Checklist\n\n1. **Entry gate** — index is the only entry\n2. **Five-step loading** — name mapping → index → intent → load → sub-layer → budget\n3. **Loading discipline** — 2+1 file limit, clear on switch\n4. **Write-back** — immediately update on decisions\n5. **Memory Flush** — `/remem` + Pre-compact + Idle\n6. **Auto-Flush** — precompact hook before compaction\n7. **DM Progressive** — independent layout, survives uninstall\n8. **Auto-Initialization** — init missing memory from known info\n9. **MEMORY.md Discipline (v1.6.0)** — keep MEMORY.md ≤ 50 lines, project details go to `projects/{name}.md`\n\n## MEMORY.md Audit Checklist (v1.6.0)\n\nRun this mental check whenever you touch MEMORY.md:\n\n- [ ] Total lines ≤ 50?\n- [ ] No project-specific progress or paths (just index pointers)?\n- [ ] No event logs or \"X happened on YYYY-MM-DD\" narratives?\n- [ ] No tool lists (iqtree, bcftools, etc.)?\n- [ ] No group names (those live in `memory/groups/`)?\n- [ ] No specific project result narratives (sample IDs, measurements)?\n- [ ] All project details have a `projects/{name}.md` file behind them?\n\nIf any answer is **no** → extract to proper layer.\n\nFile v1.6.1:_meta.json\n\n{\n  \"ownerId\": \"kn7dz0are44vk4ct393b9kxe4n8209wv\",\n  \"slug\": \"apm-agent-progressive-memory\",\n  \"version\": \"1.6.1\",\n  \"publishedAt\": 1781972714508\n}\n\nFile v1.6.1:ADDENDUM.md\n\n# APM — ADDENDUM (Technical Details)\n\n## File Templates (v1.6.0)\n\n### MEMORY.md Template (lean, ≤ 50 lines)\n\n```markdown\n# MEMORY.md — Long-term Memory (Authoritative Source)\n\n> ⚠️ This file only stores **high-level identity + index**.\n> Project details go to `memory/main/projects/`.\n> Event logs go to `memory/YYYY-MM-DD.md`.\n\n## Identity\n- **Me**: {agent name}, {role}, {style}\n- **Principles**: {3-5 max}\n\n## User\n- **Name**: {user name} / {aliases}\n- **Timezone**: {tz}\n- **Stack**: {languages/tools}\n\n## Servers\n- **Host**: {hostname}\n- **Access**: {ssh/sftp url}\n\n## Key Databases\n- **{db name}**: {path}\n\n## Project Index (see `memory/main/projects/`)\n\n| Project | Path | Detail File |\n|---------|------|-------------|\n| {name} | {path} | `projects/{name}.md` |\n| ... | ... | ... |\n\n## Other Memory Entries\n- Current tasks: `memory/main/attention.md`\n- Experience index: `memory/main/longterm.md`\n- Daily logs: `memory/YYYY-MM-DD.md`\n- Group chats: `memory/groups/` (APM 5-step)\n- DVC / data: {path}\n```\n\n### projects/{name}.md Template\n\n```markdown\n# {Project Name}\n\n**Status**: {one-line state, e.g. \"Stage3 analysis, batch1 138/140 done\"}\n\n## Project Info\n- **Path**: {absolute path}\n- **Description**: {one-liner}\n- **Group**: {group chat name, if any}\n\n## Progress / Milestones\n- ✅ {milestone 1}\n- ✅ {milestone 2}\n- ⏳ {current}\n\n## Key Findings / Notes\n- {decision, gotcha, or constraint}\n\n## References\n- Source repo: {path}\n- Data storage: {path}\n- Project report: {path}\n\n## See Also\n- `memory/main/attention.md` (current task tracking)\n```\n\n### longterm.md Template (DM experience index)\n\n```markdown\n# Long-term Memory (APM DM Summary)\n\n> Experience index layer for MEMORY.md.\n> Project details → `memory/main/projects/{name}.md`.\n> Current tasks → `memory/main/attention.md`.\n\n## Project Status Index\n\n| Project | Detail File | Current Stage |\n|---------|-------------|---------------|\n| {name} | `projects/{name}.md` | {stage} |\n\n## Key Events Index\n\n| Event | Date | Location |\n|-------|------|----------|\n| {event} | YYYY-MM-DD | {file path} |\n\n## Server Resources\n- Host: {hostname}\n- DVC: {path}\n- Key DBs: {path list}\n```\n\n## Group Index File Template\n\n```markdown\n---\ngroup_name: {group_name}\nlast_updated: YYYY-MM-DD\nstatus: active\nmemory_budget: 6000\n---\n\n# {Group Name} — Progressive Disclosure Index\n\n> ⚠️ This file is the **only legal entry point** for accessing this group's memory.\n\n## Hard Rules\n\n- rule 1\n- rule 2\n\n## Routing Index\n\n| Trigger Scenario | Load File | Priority |\n|-----------------|-----------|----------|\n| Current tasks, Sprint, blockers | `attention.md` | P0 |\n| Tech stack, architecture constraints | `project.md` | P1 |\n| Historical decisions, lessons learned | `experience.md` | P2 |\n| Team roles, contacts | `people.md` | P3 |\n| API development details | `conventions/api.md` | P2-L3 |\n```\n\n## DM Index File Template\n\n```markdown\n---\ntype: main-session-index\nlast_updated: YYYY-MM-DD\nstatus: active\nmemory_budget: 8000\n---\n\n# Main Session Memory Index\n\n> This file is the **only entry point** for DM progressive disclosure.\n\n## Reference Declarations\n\n- **Authoritative long-term memory**: `MEMORY.md` (workspace root)\n- **Raw daily logs**: `memory/YYYY-MM-DD.md`\n\n## Routing Index\n\n| Trigger Scenario | Load File | Priority |\n|-----------------|-----------|----------|\n| Current tasks, blockers | `attention.md` | P0 |\n| MEMORY.md summary | `longterm.md` | P1 |\n| Daily notes summary | `daily-synced.md` | P2 |\n| Project context | `projects/{name}.md` | P3 |\n\n## Relationship with MEMORY.md\n\n> ⚠️ **MEMORY.md is the authoritative original. It stays completely unchanged.**\n> APM's `longterm.md` serves as MEMORY.md's **experience summary + detail supplement layer**.\n\n## attention.md (Group)\n\n```markdown\n# {Group} — Current Focus\n\n## Active Tasks\n\n| Task | Status | Notes |\n|------|--------|-------|\n| ... | ... | ... |\n\n## Blockers\n\n- ...\n\n## Environment Snapshot\n\n- Last session: YYYY-MM-DD\n```\n\n## attention.md (DM)\n\n```markdown\n# Main Session — Current Focus\n\n## Active Tasks\n\n| Task | Status | Notes |\n|------|--------|-------|\n| ... | ... | ... |\n\n## Blockers\n\n- ...\n\n## Environment Snapshot\n\n- Last session: YYYY-MM-DD\n- Pending items: N\n```\n\n## experience.md (Group)\n\n```markdown\n# Experience Log\n\n## Decisions\n\n- [YYYY-MM-DD] Decision: ... → Context: ... | Action: ...\n- [YYYY-MM-DD] Decision: ... → Context: ... | Action: ...\n\n## Lessons Learned\n\n- [YYYY-MM-DD] ... → Problem: ... | Solution: ...\n```\n\n## longterm.md (DM)\n\n```markdown\n# Long-Term Memory — Experience Summary\n\n## MEMORY.md Experience Index\n\n| Topic | MEMORY.md Location | Summary |\n|-------|-------------------|---------|\n| ... | §... | ... |\n\n## Detail Supplements\n\n| Entry | Detail | Source Date |\n|-------|--------|-------------|\n| ... | ... | YYYY-MM-DD |\n\n## Decision Log\n\n- [YYYY-MM-DD] Decision: ... → MEMORY.md §...\n```\n\n## Flush Content Decisions\n\n### ✅ Write This\n\n| Category | Target File | Decision Criteria |\n|----------|------------|-------------------|\n| Confirmed decision | `experience.md` | User explicitly agreed/confirmed |\n| Task status change | `attention.md` | in-progress → completed/blocked |\n| New project agreement | `project.md` | Cross-confirmed by two messages |\n| Personnel role change | `people.md` | Explicit role assignment |\n| Environment change | `attention.md` | Server migration, port change |\n| Lessons learned | `experience.md` | Complete problem + solution |\n\n### ❌ Don't Write\n\n| Category | Reason |\n|----------|--------|\n| Small talk, greetings | No informational value |\n| Opinion only, not landed | No decision formed |\n| Repeating existing content | Already recorded |\n| Temporary exploration | Direction undecided |\n\n## Write-Back Rules\n\n### Group Chat (`memory/groups/{group}/`)\n\n- **`experience.md`**: append-only, reverse chronological, each entry `YYYY-MM-DD` + context + decision + action\n- **`attention.md`**: overwrite (task progress is factual)\n- **`project.md`, `people.md`**: primarily append; deletions require confirmation\n\n### DM (`memory/main/`)\n\n- **`longterm.md`**: each flush, distill MEMORY.md updates with original references\n- **`attention.md`**: overwrite-update tasks/blockers\n- **`daily-synced.md`**: flush-merged summary (append-only)\n- **`MEMORY.md`**: **do not touch**\n\n## MEMORY.md Size Audit (v1.6.0)\n\n| Lines | Verdict | Action |\n|-------|---------|--------|\n| ≤ 30 | ✅ Lean | Maintain |\n| 31–50 | ⚠️ Watch | Trim if growth continues |\n| 51–80 | ❌ Bloated | Extract project details → `projects/{name}.md` |\n| > 80 | 🚨 Violates design | Immediate extraction, treat as bug |\n\n**Symptoms of bloat**:\n- Tool lists (which/command -v)\n- Temporary fix notes (e.g. post-upgrade instructions) lingering in MEMORY.md\n- Project progress with versioned counts (e.g. \"batch_1 138/140\")\n- Result narratives with specific samples or measurements\n- Group names listed inline\n\n**Quick extract script** (run from `memory/main/`):\n\n```bash\n# Find candidate extraction targets\ngrep -nE '^- (Stage|batch|complete|finished|installed|fixed)' MEMORY.md\n# Find tool lists\ngrep -nE '(iqtree|vcftools|bcftools|GATK|FastQC|BWA|spades|busco|quast|braker|augustus|metaphlan|bowtie|star|hisat|salmon|kallisto|trinity|canu|flye|raven|miniasm|wtdbg|smartdenovo)' MEMORY.md\n# Find event markers\ngrep -nE '20[0-9]{2}-[0-9]{2}-[0-9]{2}' MEMORY.md\n```\n\nIf any match → move to `projects/{name}.md` or `longterm.md`.\n\n## Flush State Tracking (v1.6.0)\n\nAPM uses **two separate flush-state files** (privacy boundary between DM\nand group memory). See `SKILL.md` → \"Flush State Files\" for the rationale.\n\n### `memory/flush-state.json` (DM)\n\n```json\n{\n  \"last_flush_time\": \"YYYY-MM-DDTHH:MM:SS+08:00\",\n  \"flush_number\": 6,\n  \"context_usage_at_flush\": 45,\n  \"session_id\": \"agent:<id>:matrix:direct:room:...\",\n  \"pending_items\": [],\n  \"memory/main/attention.md_mtime\": \"YYYY-MM-DDTHH:MM:SS+08:00\",\n  \"memory/main/longterm.md_mtime\":  \"YYYY-MM-DDTHH:MM:SS+08:00\"\n}\n```\n\n### `memory/groups/flush-state.json` (group)\n\nSame shape, scoped to one or more groups:\n\n```json\n{\n  \"last_flush_time\": \"YYYY-MM-DDTHH:MM:SS+08:00\",\n  \"flush_number\": 2,\n  \"context_usage_at_flush\": null,\n  \"session_id\": \"agent:<id>:matrix:channel:room:...\",\n  \"pending_items\": [],\n  \"memory/groups/{group_name}/attention.md_mtime\": \"YYYY-MM-DDTHH:MM:SS+08:00\"\n}\n```\n\n### Rules\n\n- **DM flush writes only** to `memory/flush-state.json`\n- **Group flush writes only** to `memory/groups/flush-state.json`\n- `pending_items` is **NOT** shared — each file is independent\n- `mtime` keys are written by `remem-flush` and `precompact-remem` to\n  enable delta-only flushes; old timestamps are preserved across flushes\n  for unchanged files\n- `context_usage_at_flush` records the context-usage percentage at\n  flush time (useful for tuning `precompact-remem` thresholds)\n\nFile v1.6.1:CHANGELOG.md\n\n# APM Skill — Changelog\n\n## 1.6.0 (2026-06-20)\n\n### Added\n\n- **New hook**: `apm_session_start` — auto-injects APM context per chat\n  type on every agent run.\n  - Chat-type aware: DM gets `APM_SESSION_START.md`; groups get\n    `APM_GROUP_SESSION_START.md` with privacy gate.\n  - Channel-agnostic sessionKey parsing (Matrix / Telegram / Slack / Discord).\n  - Group-name resolution via `memory/groups/group_names.json` (full\n    key match + Matrix-specific room-only fallback).\n  - Idempotent per session (cached via `bootstrapFiles`).\n- **New chapter in SKILL.md**: `MEMORY.md Discipline` — explicit\n  allowed/forbidden rules for what belongs in `MEMORY.md` vs other\n  memory layers.\n- **New chapter in SKILL.md**: `MEMORY.md Audit Checklist` — quick\n  mental check whenever editing `MEMORY.md`.\n- **New chapter in ADDENDUM.md**: `File Templates` — three canonical\n  templates: `MEMORY.md` (lean, ≤ 50 lines), `projects/{name}.md`,\n  `longterm.md` (experience index).\n- **New chapter in ADDENDUM.md**: `MEMORY.md Size Audit` — line-count\n  rating table and a quick-extract script (grep) for finding\n  bloat candidates.\n- **New chapter in HOOKS.md**: `Hook Interaction` flow diagram and\n  shared conventions (mtime-based deltas, idempotency, flush-state shape).\n- **Shipped hook code**: `hooks/apm_session_start/{HOOK.md,handler.js}`\n  in this skill (operators can `cp -r` to install).\n- **Shipped hook code**: synced `hooks/remem-flush/` and\n  `hooks/precompact-remem/` from deployed state (catch up to current\n  `~/.openclaw/hooks/` versions).\n- **CHANGELOG.md** — this file.\n\n### Changed\n\n- `SKILL.md` — added new chapters; existing content unchanged.\n- `ADDENDUM.md` — added new templates and audit section; existing\n  content unchanged.\n- `HOOKS.md` — restructured as pure overview + links (was duplicating\n  per-hook content); install instructions consolidated.\n- `_meta.json` — version bumped 1.5.0 → 1.6.0.\n\n### Privacy / Channel Improvements\n\n- All skill documentation **stripped of personal references** (agent\n  name, project names, server paths, specific room IDs).\n- `apm_session_start` hook explicitly documents channel support matrix\n  (Matrix primary, others compatible) and Matrix-specific fallbacks\n  (room-only key match) are noted as such.\n- All non-English references in `apm_session_start` translated\n  to English (e.g. \"Progressive Disclosure Protocol\",\n  \"Entry Gate\", \"First-Join Flow\") to keep the skill monolingual.\n\n### Known Limitations (unchanged)\n\n- `MEMORY.md` is still injected by OpenClaw as a workspace bootstrap\n  file in group sessions; the privacy gate is enforced by agent\n  discipline until OpenClaw adds filtering.\n- `chatType === 'unknown'` falls back to DM protocol + warning.\n\n## 1.5.0 (2026-05-19)\n\n- Initial published version.\n- Two hooks: `remem-flush`, `precompact-remem`.\n- Group 5-step + DM 3-layer loading protocol.\n- File templates in ADDENDUM.md (group index, attention, experience).\n\n---\n\n## Versioning\n\n- **Major** (1.x → 2.x) — breaking protocol change (loading flow,\n  file layout, hook contract).\n- **Minor** (1.5.x → 1.6.x) — additive, backward-compatible\n  (new hooks, new templates, new chapters).\n- **Patch** (1.6.0 → 1.6.1) — docs fixes, comment clarifications,\n  no protocol change.\n\nFile v1.6.1:HOOKS.md\n\n# APM — Hooks Overview\n\nThis skill ships **three OpenClaw hooks** that automate the APM memory\nlifecycle. Each hook has its own `HOOK.md` with full details; this file is\nthe entry point and contains only the overview, shared conventions, and\ninstallation instructions.\n\n## Hook Index\n\n| Hook | Event | Purpose | Full docs |\n|------|-------|---------|-----------|\n| `apm_session_start` | `agent:bootstrap` | Auto-inject APM context per chat type (DM vs group, channel-agnostic) | [`hooks/apm_session_start/HOOK.md`](hooks/apm_session_start/HOOK.md) |\n| `remem-flush` | `message:received`, `system:event` | Manual flush on `/remem` (user or cron) | [`hooks/remem-flush/HOOK.md`](hooks/remem-flush/HOOK.md) |\n| `precompact-remem` | `session:compact:before` | Auto-flush before context is lost | [`hooks/precompact-remem/HOOK.md`](hooks/precompact-remem/HOOK.md) |\n\n## Shipped Files\n\n```\nhooks/\n├── apm_session_start/\n│   ├── HOOK.md\n│   └── handler.js\n├── remem-flush/\n│   ├── HOOK.md\n│   └── handler.js\n└── precompact-remem/\n    ├── HOOK.md\n    └── handler.js\n```\n\n## Channel Compatibility\n\nAll three hooks are **channel-agnostic at the chat-type level** (DM vs\ngroup). `apm_session_start` additionally detects multiple channel\nsessionKey patterns:\n\n| Channel  | DM | Group | Notes |\n|----------|----|----|-------|\n| Matrix   | ✅ | ✅ | First-class; full + room-only key matching |\n| Telegram | ✅ | ✅ | chat_id as key (negative for groups) |\n| Slack    | ✅ | ✅ | channel_id snowflake as key |\n| Discord  | ✅ | ✅ | channel_id snowflake as key |\n\nTo add a new channel, update `detectChatTypeFromSessionKey` in\n`hooks/apm_session_start/handler.js` and document the key format in\n`hooks/apm_session_start/HOOK.md`.\n\n## Installation\n\nInstall all three hooks in one go:\n\n```bash\nSKILL_DIR=~/.openclaw/workspace/skills/apm-agent-progressive-memory\nHOOKS_DIR=~/.openclaw/hooks\n\ncp -r \"$SKILL_DIR/hooks/apm_session_start/\"   \"$HOOKS_DIR/\"\ncp -r \"$SKILL_DIR/hooks/remem-flush/\"          \"$HOOKS_DIR/\"\ncp -r \"$SKILL_DIR/hooks/precompact-remem/\"     \"$HOOKS_DIR/\"\n\n# Avoid double-flush with the built-in memory-flush hook\nopenclaw hooks disable memory-flush\n\n# Enable precompact (apm_session_start and remem-flush are auto-loaded)\nopenclaw hooks enable precompact-remem\n```\n\n## Verification\n\nAfter installation, verify all three handlers load:\n\n```bash\n# Each handler should parse and export { handler } without error\nfor hook in apm_session_start remem-flush precompact-remem; do\n  node -e \"require('./hooks/$hook/handler.js'); console.log('$hook OK')\"\ndone\n```\n\n## Hook Interaction\n\n```\nagent run start\n   │\n   ▼\nagent:bootstrap event\n   │\n   ├─► apm_session_start  ──► injects APM_SESSION_START.md (DM)\n   │                       or APM_GROUP_SESSION_START.md (group)\n   │\n   ▼\nagent responds to user\n   │\n   ▼\nuser sends /remem (or cron fires /remem)\n   │\n   ├─► remem-flush        ──► records mtime deltas in\n   │                          memory/flush-state.json (DM) OR\n   │                          memory/groups/flush-state.json (group)\n   │\n   ▼\n... session continues ...\n   │\n   ▼\ncontext near limit OR session idle\n   │\n   ├─► precompact-remem   ──► records mtime deltas in\n   │                          memory/flush-state.json (DM) OR\n   │                          memory/groups/flush-state.json (group)\n   │\n   ▼\nsession:compact fires\n```\n\n## Shared Conventions\n\n### flush-state.json Shape\n\nAll three hooks read/write `memory/flush-state.json` (DM) and may\nalso read `memory/groups/flush-state.json` (group). See\n[`ADDENDUM.md`](ADDENDUM.md) for the full schema.\n\n### mtime-based Deltas\n\n`remem-flush` and `precompact-remem` use file mtime to detect\nchanges since last flush. They preserve prior `_mtime` keys in\n`flush-state.json` so unchanged files don't trigger re-flushes.\n\n### Idempotency\n\n`apm_session_start` is idempotent per session (cached in\n`bootstrapFiles`). `remem-flush` and `precompact-remem` write to\n`flush-state.json` but use mtime gating to avoid re-stamping\nunchanged files.\n\n## OpenClaw Built-ins to Disable\n\n| Built-in hook | Why disable |\n|---------------|-------------|\n| `memory-flush` | Listens to `/new` (not `/remem`); fires too late (after context is lost) |\n\n```bash\nopenclaw hooks disable memory-flush\n```\n\n## See Also\n\n- [`SKILL.md`](SKILL.md) — core APM protocol (loading, write-back, flush triggers)\n- [`ADDENDUM.md`](ADDENDUM.md) — file templates, audit rules, flush-state schema\n- `hooks/<name>/HOOK.md` — full per-hook documentation\n\nFile v1.6.1:hooks/apm_session_start/HOOK.md\n\n---\nname: apm_session_start\ndescription: \"Inject APM (Agent Progressive Memory) bootstrap context per chat type — DM uses memory/main/*, group chat uses memory/groups/{name}.md. Channel-agnostic (Matrix / Telegram / Slack / Discord).\"\nmetadata: |\n  {\n    \"openclaw\": {\n      \"export\": \"handler\",\n      \"events\": [\"agent:bootstrap\"]\n    }\n  }\n---\n\n# apm_session_start Hook (chat-type aware, channel-agnostic)\n\nAuto-loads the right APM memory context per chat type and injects a synthetic\nbootstrap file. Solves two problems:\n\n1. **DRY** — Agent never has to remember to load memory on the first turn.\n2. **Privacy** — Group chats **MUST NOT** receive DM-only memory\n   (`MEMORY.md`, `memory/main/*`, `memory/YYYY-MM-DD.md`).\n\n## Supported Channels\n\nThe hook is channel-agnostic for chat-type detection. The sessionKey patterns\nbelow are handled uniformly:\n\n| Channel  | DM pattern                            | Group pattern                          |\n|----------|---------------------------------------|----------------------------------------|\n| Matrix   | `agent:<id>:matrix:direct:<room>`     | `agent:<id>:matrix:channel:<room>`     |\n| Telegram | `agent:<id>:telegram:<direct\\|group>:<chat_id>` | (Telegram only has `group` for groups) |\n| Slack    | `agent:<id>:slack:direct:<user_id>`   | `agent:<id>:slack:channel:<channel_id>` |\n| Discord  | `agent:<id>:discord:direct:<user_id>` | `agent:<id>:discord:channel:<guild_id>` |\n\n**Matrix is the primary supported channel.** Other channels are handled by\nthe same chat-type detection logic but require operators to populate\n`memory/groups/group_names.json` with channel-appropriate keys (see\n[Group-Name Resolution](#group-name-resolution) below).\n\n## Chat-Type Detection\n\n`agent:bootstrap` event context does **not** include `chatType`. The hook\nparses `event.sessionKey` to derive it:\n\n| Token in sessionKey | Detected  | Action                |\n|---------------------|-----------|-----------------------|\n| `:direct:`          | `direct`  | DM protocol           |\n| `:channel:`         | `channel` | Group protocol        |\n| `:group:`           | `channel` | Group protocol (Telegram alias) |\n| `:subagent:`        | `subagent`| Skip (renderer filters anyway)   |\n| `cron:` / `:cron-*` | `cron`    | Skip                  |\n| anything else       | `unknown` | DM protocol + warn    |\n\n## Behavior (7 steps)\n\nOn every `agent:bootstrap` event:\n\n1. **Type detection** — parse `event.sessionKey` → `chatType`\n2. **Scope guard** — return early if `subagent` / `cron`\n3. **Empty-list guard** — skip if `context.bootstrapFiles` is empty\n   (lightweight non-heartbeat runs — nothing to attach to)\n4. **Chat-type branching**:\n   - `channel` → resolve friendly name via `memory/groups/group_names.json`,\n     then read `memory/groups/{name}.md` (L0) + `memory/groups/flush-state.json`\n   - `direct` / `unknown` → read APM DM files (`memory/main/index.md` +\n     attention/longterm/daily-synced + today/yesterday daily notes +\n     `memory/flush-state.json`)\n5. **Privacy gate (group)** — group sessions **MUST NOT** receive DM-only\n   memory. The injected entry includes an explicit DO-NOT-READ block listing\n   `memory/main/*`, `MEMORY.md`, and `memory/YYYY-MM-DD.md`. If group index\n   is missing (first-join), inject nothing and log; AGENTS.md \"First-join\"\n   flow handles it.\n6. **Idempotency** — skip if our synthetic entry name is already in\n   `bootstrapFiles` (cached per session)\n7. **Push** a synthetic entry to `context.bootstrapFiles`\n\n## Injected Entry Names\n\n| Chat Type | Entry Name                   | Path                                          |\n|-----------|------------------------------|-----------------------------------------------|\n| DM        | `APM_SESSION_START.md`       | `memory/APM_SESSION_START.md`                 |\n| Group     | `APM_GROUP_SESSION_START.md` | `memory/groups/APM_GROUP_SESSION_START.md`    |\n\nBoth names are intentionally distinct from recognized workspace basenames\n(`MEMORY.md`, `AGENTS.md`, etc.) to avoid collisions with workspace templates.\n\n## Group-Name Resolution\n\nGroup-chat sessions require `memory/groups/group_names.json` to map\n**channel-specific id** → friendly name. The hook tries:\n\n1. **Full key match** (channel-agnostic) — the raw channel id as extracted\n   from `sessionKey`:\n   - Matrix: `!roomId:domain.example`\n   - Telegram: `<chat_id>` (e.g. `-1001234567890`)\n   - Slack: `<channel_id>` (snowflake, e.g. `C0123ABCDEF`)\n   - Discord: `<channel_id>` (snowflake, e.g. `123456789012345678`)\n2. **Matrix-only fallback** — strip `:domain` suffix and try `!roomId`.\n   (Other channels' ids don't contain `:`, so this is a no-op for them.)\n\nIf neither matches → **log warning + fall back to DM protocol** (NOT\nRECOMMENDED — private memory may leak). Operators should add the missing\nmapping before relying on this fallback.\n\n### Expected `group_names.json` shape\n\n```json\n{\n  \"<channel_id_key>\": {\n    \"name\": \"<friendly_name>\",\n    \"channel\": \"matrix|telegram|slack|discord\"\n  }\n}\n```\n\nExample for a multi-channel workspace:\n\n```json\n{\n  \"!roomId1:matrix.example.com\": { \"name\": \"team-alpha\", \"channel\": \"matrix\" },\n  \"-1001234567890\":              { \"name\": \"team-alpha-tg\", \"channel\": \"telegram\" },\n  \"C0123ABCDEF\":                 { \"name\": \"team-alpha-slack\", \"channel\": \"slack\" }\n}\n```\n\n## Token Caps\n\n| Constant | Value | Reason |\n|----------|-------|--------|\n| `APM_MAX_TOTAL_CHARS` | 12000 | Stay well under bootstrap total limit |\n| `DAILY_NOTE_MAX_CHARS` | 6000 | Per-day cap for today/yesterday daily notes |\n| `FILE_READ_MAX_CHARS` | 30000 | Per-file read cap for non-daily files |\n\nIf exceeded, the relevant section is truncated with an explicit\n`[... truncated at N chars; original M chars at PATH]` marker.\n\n## Configuration\n\n| Item | Value |\n|------|-------|\n| Hook event | `agent:bootstrap` |\n| Hook path | `~/.openclaw/hooks/apm_session_start/` |\n| Trigger | Every agent run (one shot per session) |\n\n## Installation\n\n```bash\n# From skill directory:\ncp -r hooks/apm_session_start/ ~/.openclaw/hooks/apm_session_start/\n```\n\n### Post-install Structure\n\n```\n~/.openclaw/hooks/apm_session_start/\n├── HOOK.md\n└── handler.js\n```\n\n## Why\n\nAGENTS.md mandates:\n\n- **DM**: APM 1.6.0 protocol — load `memory/main/index.md` first, then up\n  to 2 P-files on-demand\n- **Group**: Progressive Disclosure Protocol — only `memory/groups/{name}.md`\n  is the legal entry; everything else loads on-demand per the L0 routing\n  table; **never** read `MEMORY.md` or `memory/YYYY-MM-DD.md` in group chat\n\nWithout chat-type awareness the hook would inject DM context into group\nsessions — a privacy violation. This hook respects the group protocol by\ndefault.\n\n## Idempotency Notes\n\n- `applyBootstrapHookOverrides` fires the hook on every agent turn, but\n  `bootstrapFiles` is cached per session. Once the synthetic entry is\n  pushed, subsequent turns see it and skip.\n- For `lightweight + heartbeat` runs the renderer strips non-`HEARTBEAT.md`\n  entries later in the pipeline, so injecting APM context there wastes\n  tokens. We skip those runs up-front via the empty-list guard.\n\n## Known Limitations\n\n1. **`MEMORY.md` is still injected by OpenClaw as a workspace bootstrap file**\n   in group sessions (the hook cannot filter it out — that requires a\n   separate change in OpenClaw's `loadWorkspaceBootstrapFiles`). The\n   injected entry includes an explicit DO-NOT-READ warning; rely on agent\n   discipline until OpenClaw-level filtering lands.\n2. **`chatType === 'unknown'` falls back to DM.** If OpenClaw adds new\n   sessionKey formats in the future, update `detectChatTypeFromSessionKey`.\n   The handler logs a warning for unrecognized patterns.\n3. **Group-name resolution depends on operator-configured\n   `group_names.json`.** New channels must add their key format to\n   `resolveGroupName` and document it above.\n\n## Related\n\n- `AGENTS.md` — \"Every Session\" → APM DM Progressive Loading + Progressive Disclosure Protocol\n- `memory/main/index.md` — DM APM routing table (L0)\n- `memory/groups/group_names.json` — channel id → friendly name map\n- `memory/groups/{name}.md` — per-group L0 entry (only legal entry for groups)\n- `memory/groups/flush-state.json` — group-only flush state (NOT memory/flush-state.json)\n- OpenClaw docs: `/automation/hooks`, `/plugins/hooks`\n\nFile v1.6.1:hooks/precompact-remem/HOOK.md\n\n---\nname: precompact-remem\ndescription: \"Before session context compaction, record mtime-gated deltas to flush-state.json so no context is lost. Channel-agnostic.\"\nmetadata: |\n  {\n    \"openclaw\": {\n      \"export\": \"handler\",\n      \"events\": [\"session:compact:before\"]\n    }\n  }\n---\n\n# precompact-remem Hook\n\nIntercepts `session:compact:before` and records mtime-based deltas to\n`flush-state.json` so context isn't lost when OpenClaw compacts the\ntranscript. Like `remem-flush`, this is the **detection** side; actual\nmemory-file updates happen via the agent's own write-back.\n\n## Events\n\n- `session:compact:before` — fires just before OpenClaw compacts the transcript\n\n## Behavior (6 steps)\n\n1. **Detect** session context (messageCount, tokenCount)\n2. **Skip** if session too small (msgCount < 10 AND tokens < 1000)\n3. **Discover** active memory groups under `memory/groups/`\n4. **Read** old mtime records from `flush-state.json`\n5. **Compute** deltas (files modified since last flush)\n6. **Stamp** new mtimes + flush timestamp into `flush-state.json` with `trigger: \"precompact\"`\n\n## Why Auto-Trigger?\n\n- `remem-flush` handles **user-explicit** flush (`/remem` command)\n- `precompact-remem` handles **automatic** flush (context loss imminent)\n- Both share the same mtime-gated delta logic and `flush-state.json` file\n- Together they form a belt-and-suspenders safety net for context preservation\n\n## Files Modified\n\n| File | When | Notes |\n|------|------|-------|\n| `memory/flush-state.json` | Before compaction | Adds `trigger: \"precompact\"` + mtimes |\n\n> ⚠️ Same known limitation as `remem-flush`: writes to a single\n> `memory/flush-state.json` regardless of chat type. Group compaction\n> shares the DM flush-state until a future revision adds the split.\n\n## Files Read\n\n- `memory/groups/*.md` (filenames only)\n- `memory/flush-state.json` (existing mtimes)\n- `event.context.messageCount`, `event.context.tokenCount`\n- `event.sessionKey` (for logging)\n\nFile v1.6.1:hooks/remem-flush/HOOK.md\n\n---\nname: remem-flush\ndescription: \"Memory flush hook for /remem command. Updates flush-state.json with mtime-gated delta tracking when user (or cron) sends /remem. Channel-agnostic.\"\nmetadata: |\n  {\n    \"openclaw\": {\n      \"export\": \"handler\",\n      \"events\": [\"message:received\", \"system:event\"]\n    }\n  }\n---\n\n# remem-flush Hook\n\nIntercepts `/remem` commands and triggers a 6-step memory flush that\nrecords mtime-based deltas. This is the **detection** side of APM\nflushing; actual memory-file updates happen via the agent's own\nwrite-back (see SKILL.md → \"Write-Back on Updates\").\n\n## Events\n\n- `message:received` — manual `/remem` from user\n- `system:event` — cron-triggered `/remem` (e.g. 06:17 / 18:17 Asia/Shanghai)\n\n> The `system:event` support was added in v1.6.0 to enable scheduled\n> flushes without user intervention. The handler detects both event types\n> and routes to the same logic.\n\n## Behavior (6 steps)\n\n1. **Intercept** messages matching `/remem` or `/remem <args>`\n2. **Extract** session context (sessionId, contextUsage)\n3. **Discover** active memory groups under `memory/groups/`\n4. **Read** old mtime records from `flush-state.json`\n5. **Compute** deltas (files modified since last flush)\n6. **Stamp** new mtimes + flush timestamp into `flush-state.json`\n\nThe hook does **NOT** modify `memory/main/*.md` or\n`memory/groups/{name}/*.md` — those are the agent's job (via\n`memory_get` / `write` after this hook signals pending deltas).\n\n## Files Modified\n\n| File | When | Notes |\n|------|------|-------|\n| `memory/flush-state.json` | Every flush | mtime records + flush timestamp |\n| `memory/groups/flush-state.json` | Every flush (if groups active) | Per-group mtime records |\n\n> ⚠️ The handler currently writes to a single `memory/flush-state.json`\n> regardless of chat type. A future revision will split this into DM vs\n> group files per `apm_session_start` hook's privacy boundary. For now,\n> group flushes share the DM flush-state — a known limitation.\n\n## Files Read\n\n- `memory/groups/*.md` (filenames only — used to discover group names)\n- `memory/flush-state.json` (existing mtimes)\n- `event.context.content` (for `/remem` detection)\n- `event.context.usagePercent` (for context-usage recording)\n\nFile v1.6.1:skill-card.md\n\n## Description:\n\nAPM Protocol (Agent Progressive Memory): Progressive disclosure protocol for group chat AND DM (main session) memory.\n\nThis skill is ready for commercial/non-commercial use.\n\n## Publisher:\n\n[biociao](https://clawhub.ai/user/biociao)\n\n### License/Terms of Use:\n\nMIT-0\n\n## Use Case:\n\nDevelopers and operators use this skill to structure agent memory for private sessions and group chats, with progressive loading, memory write-back rules, and hooks for session bootstrap and flush tracking.\n\n### Deployment Geography for Use:\n\nGlobal\n\n## Known Risks and Mitigations:\n\nRisk: Private DM memory can be exposed in group sessions when chat mapping or detection fails.\n\nMitigation: Avoid group use until the DM fallback fails closed, keep group_names.json mappings complete, and review behavior before installing in workspaces with private notes or group chats.\n\nRisk: Automatic memory bootstrap and persistence can surface or retain sensitive workspace context.\n\nMitigation: Install only in workspaces where automatic memory loading and persistence are acceptable, and review the bundled hooks before enabling them.\n\nRisk: Flush-state handling can blur DM and group boundaries in the current hook design.\n\nMitigation: Avoid group workflows until flush-state separation is fixed and verified.\n\n## Reference(s):\n\n- [ClawHub skill page](https://clawhub.ai/biociao/skills/apm-agent-progressive-memory)\n- [SKILL.md](artifact/SKILL.md)\n- [HOOKS.md](artifact/HOOKS.md)\n- [ADDENDUM.md](artifact/ADDENDUM.md)\n- [apm_session_start hook documentation](artifact/hooks/apm_session_start/HOOK.md)\n- [remem-flush hook documentation](artifact/hooks/remem-flush/HOOK.md)\n- [precompact-remem hook documentation](artifact/hooks/precompact-remem/HOOK.md)\n\n## Skill Output:\n\n**Output Type(s):** [Text, Markdown, Code, Shell commands, Configuration, Guidance]\n\n**Output Format:** [Markdown guidance with file templates, hook installation commands, and JavaScript hook code]\n\n**Output Parameters:** [1D]\n\n**Other Properties Related to Output:** [Includes bootstrap and flush hooks that can read or update workspace memory state when installed.]\n\n## Skill Version(s):\n\n1.6.1 (source: server release evidence)\n\n## Ethical Considerations:\n\nUsers should evaluate whether this skill is appropriate for their environment, review any generated or modified files before relying on them, and apply their organization's safety, security, and compliance requirements before deployment.\n\nFile v1.6.1:.clawhub/origin.json\n\n{\n  \"version\": 1,\n  \"registry\": \"https://clawhub.ai\",\n  \"slug\": \"apm-agent-progressive-memory\",\n  \"installedVersion\": \"1.5.0\",\n  \"installedAt\": 1779169165540\n}\n\nArchive v1.6.0: 12 files, 24647 bytes\n\nFiles: _meta.json (147b), ADDENDUM.md (4961b), bootstrap.sh (23900b), HOOKS.md (5294b), hooks/apm-bootstrap/handler.js (5408b), hooks/apm-bootstrap/HOOK.md (2229b), hooks/precompact-remem/handler.js (4369b), hooks/precompact-remem/HOOK.md (1113b), hooks/remem-flush/handler.js (4829b), hooks/remem-flush/HOOK.md (847b), skill-card.md (2356b), SKILL.md (7519b)\n\nFile v1.6.0:SKILL.md\n\n---\nname: APM-agent-progressive-memory\ndescription: \"APM Protocol (Agent Progressive Memory): Progressive disclosure protocol for group chat AND DM (main session) memory.\"\n---\n\n# APM — Progressive Disclosure Protocol\n\nAPM supports **both group chat and private (main session DM)** memory management. The two structures are completely independent and do not interfere with each other.\n\n## Group vs DM: Strategy Comparison\n\n| Aspect | Group Chat | DM (Main Session) |\n|-------|-----------|-------------------|\n| **Memory path** | `memory/groups/{group_name}/` | `memory/main/` |\n| **Loading** | 5-step progressive (index → P0 → P1 → P2 → P3) | 3-layer progressive (index → attention → longterm) |\n| **Index file** | `memory/groups/{group_name}.md` | `memory/main/index.md` |\n| **Priority files** | attention.md, project.md, experience.md, people.md | attention.md, longterm.md |\n| **Entry rule** | Must read index first, no subdirectory bypass | Must read index first |\n| **Flush trigger** | Per-group flush on `/remem` | Full-session flush on `/remem` |\n\n**Key differences**:\n- Group uses **5-step loading** with budget controls; DM uses simpler **3-layer**\n- Group has **conventions/** sub-directory; DM does not\n- DM reuses existing **MEMORY.md**; Group uses dedicated files\n- Uninstaller: Group loses memory access; DM retains MEMORY.md\n\nAgent must follow the **layered disclosure protocol** when accessing memory in group chats: read the index first, then load layers on demand.\n\n## Core Rules\n\n### 1. Entry Gate\n\n- The **only legal entry point** for group chat memory is `memory/groups/{group_name}.md` (index file)\n- **Forbidden**: directly reading any sub-files under `memory/groups/{group_name}/`\n- **Forbidden**: bypassing the index to directly `memory_search` subdirectories\n- **Group name mapping rule**: group chat room IDs must first be resolved via `memory/group_names.json` to a friendly name `{group_name}` before use\n\n### 2. Five-Step Loading Flow\n\n| Step | Action | Output |\n|------|--------|--------|\n| 0. Group name mapping | Check `memory/group_names.json`, convert room ID to `{group_name}` | Friendly name |\n| 1. Route to index | `memory_get(\"memory/groups/{group_name}.md\")` | Hard Rules + routing table |\n| 2. Intent matching | Match current message to trigger scenario | File to load |\n| 3. Explicit load | `memory_get(\"memory/groups/{group_name}/{file}.md\")` | Actual memory content |\n| 4. Sub-layer control | Load only if Step 3 file references `conventions/` | 1 sub-file max |\n| 5. Budget circuit-breaker | Stop when cumulative tokens exceed `memory_budget` | Stop loading |\n\nOnly **one** best-matching file is loaded per session (highest priority wins).\n\n### 3. Loading Discipline\n\n- Maximum **2 P0-P2 files + 1 P3 file** per session\n- `conventions/` files: only **1** at a time\n- When switching group chats, clear old context first, then restart from Step 1\n\n### 4. Write-Back on Updates\n\n- New decision → append to `experience.md`\n- Task status change → update `attention.md`\n- Index files: append-only (mark deleted entries `[DEPRECATED]` instead of removing)\n\n### 5. Memory Flush\n\n| Trigger | Condition | Action |\n|---------|-----------|--------|\n| `/remem` | User manual trigger | Full flush |\n| Pre-compact | Context near limit | Auto-flush before loss |\n| Idle timeout | 30min inactive, no flush | One-time auto-flush |\n\n### 6. Auto-Initialization on Missing Memory\n\n> When a flush is triggered for a session whose memory system has **not yet been initialized**, the Agent must initialize it based on available information.\n\n| Scenario | Action |\n|----------|--------|\n| Group index missing | Create from `group_names.json` + context |\n| DM index missing | Create from `MEMORY.md` content |\n\n**Initialization is not overwriting**: existing files are never overwritten — only created when completely absent.\n\n## File Structure\n\n```\nmemory/groups/\n├── {group_name}.md          # L0: Entry gate (mandatory read)\n└── {group_name}/             # Group memory (direct access forbidden)\n    ├── attention.md          # P0: Current focus\n    ├── project.md            # P1: Project static info\n    ├── experience.md         # P2: Experience / decision log\n    ├── people.md             # P3: People profiles\n    └── conventions/          # L3: Detailed specifications\n        ├── api.md\n        └── ...\n\nmemory/main/                    # DM progressive disclosure\n├── index.md                # L0: DM entry index\n├── attention.md            # P0: Current tasks, blockers\n├── longterm.md             # P1: MEMORY.md distilled summary\n├── daily-synced.md         # P2: Daily notes summary\n└── projects/               # P3: Project context\n    └── {name}.md\n```\n\n## Priority Definitions\n\n| Priority | File | Content | When to Load |\n|----------|------|---------|--------------|\n| P0 | `attention.md` | Active tasks, blockers | Any work conversation |\n| P1 | `project.md` | Tech stack, architecture | Technical decisions |\n| P2 | `experience.md` | Lessons learned | Search hit + append |\n| P3 | `people.md` | Team roles, contacts | Need to find someone |\n\n## DM Entry Loading (to add in AGENTS.md)\n\n```markdown\n## Every Session\n\n1. Read `SOUL.md` → USER.md → MEMORY.md\n2. **If in MAIN SESSION** (DM):\n   - Read `memory/main/index.md` — DM progressive index\n   - Based on routing, load up to 2 files\n   - Report `上次 flush: YYYY-MM-DD HH:mm` (from `flush-state.json`)\n3. Read `memory/YYYY-MM-DD.md` (today + yesterday)\n```\n\n## Flush State File\n\n`memory/flush-state.json`:\n\n```json\n{\n  \"groups\": { \"last_flush_time\": \"...\" },\n  \"main_session\": { \"last_flush_time\": \"...\" },\n  \"pending_items\": []\n}\n```\n\n## Anti-Pattern\n\n```\n❌ Load all at once        → ✅ Load only one at a time\n❌ Skip index           → ✅ Read index first\n❌ Load two groups      → ✅ Clear old, reload from Step 1\n```\n\n## Complete Protocol Checklist\n\n1. **Entry gate** — index is the only entry\n2. **Five-step loading** — name mapping → index → intent → load → sub-layer → budget\n3. **Loading discipline** — 2+1 file limit, clear on switch\n4. **Write-back** — immediately update on decisions\n5. **Memory Flush** — `/remem` + Pre-compact + Idle\n6. **Auto-Flush** — precompact hook before compaction\n7. **DM Progressive** — independent layout, survives uninstall\n8. **Auto-Initialization** — init missing memory from known info\n\n## Bundled Bootstrap Script (v1.6.0+)\n\nA `bootstrap.sh` ships with the skill to **idempotently initialize the\nmemory tree**. Use it:\n\n- **First install** — create the full layout from scratch\n- **Adding a group** — register it in `group_names.json` then re-run\n- **Recovering from corruption** — re-run; missing files are recreated\n\n```bash\n# Full initialization\n./bootstrap.sh --yes\n\n# Preview changes (no writes)\n./bootstrap.sh --dry-run\n\n# Just one group\n./bootstrap.sh --yes --group Pan.C.par\n\n# Sandbox / CI mode\n./bootstrap.sh --yes --workspace /tmp/test\n```\n\nFor automatic bootstrap on every agent startup, enable the\n`apm-bootstrap` hook (see `HOOKS.md`).\n\n## Bundled Hooks (v1.6.0+)\n\n| Hook | Purpose | Event |\n|------|---------|-------|\n| `apm-bootstrap` | First-time init of memory tree | `agent:bootstrap`, `gateway:startup` |\n| `remem-flush` | Manual `/remem` flush | `message:received` |\n| `precompact-remem` | Auto flush before compaction | `session:compact:before` |\n\nSee `HOOKS.md` for installation and configuration.\n\nFile v1.6.0:_meta.json\n\n{\n  \"ownerId\": \"kn7dz0are44vk4ct393b9kxe4n8209wv\",\n  \"slug\": \"apm-agent-progressive-memory\",\n  \"version\": \"1.6.0\",\n  \"publishedAt\": 1781717565353\n}\n\nFile v1.6.0:ADDENDUM.md\n\n# APM — ADDENDUM (Technical Details)\n\n## Group Index File Template\n\n```markdown\n---\ngroup_name: {group_name}\nlast_updated: YYYY-MM-DD\nstatus: active\nmemory_budget: 6000\n---\n\n# {Group Name} — Progressive Disclosure Index\n\n> ⚠️ This file is the **only legal entry point** for accessing this group's memory.\n\n## Hard Rules\n\n- rule 1\n- rule 2\n\n## Routing Index\n\n| Trigger Scenario | Load File | Priority |\n|-----------------|-----------|----------|\n| Current tasks, Sprint, blockers | `attention.md` | P0 |\n| Tech stack, architecture constraints | `project.md` | P1 |\n| Historical decisions, lessons learned | `experience.md` | P2 |\n| Team roles, contacts | `people.md` | P3 |\n| API development details | `conventions/api.md` | P2-L3 |\n```\n\n## DM Index File Template\n\n```markdown\n---\ntype: main-session-index\nlast_updated: YYYY-MM-DD\nstatus: active\nmemory_budget: 8000\n---\n\n# Main Session Memory Index\n\n> This file is the **only entry point** for DM progressive disclosure.\n\n## Reference Declarations\n\n- **Authoritative long-term memory**: `MEMORY.md` (workspace root)\n- **Raw daily logs**: `memory/YYYY-MM-DD.md`\n\n## Routing Index\n\n| Trigger Scenario | Load File | Priority |\n|-----------------|-----------|----------|\n| Current tasks, blockers | `attention.md` | P0 |\n| MEMORY.md summary | `longterm.md` | P1 |\n| Daily notes summary | `daily-synced.md` | P2 |\n| Project context | `projects/{name}.md` | P3 |\n\n## Relationship with MEMORY.md\n\n> ⚠️ **MEMORY.md is the authoritative original. It stays completely unchanged.**\n> APM's `longterm.md` serves as MEMORY.md's **experience summary + detail supplement layer**.\n\n## attention.md (Group)\n\n```markdown\n# {Group} — Current Focus\n\n## Active Tasks\n\n| Task | Status | Notes |\n|------|--------|-------|\n| ... | ... | ... |\n\n## Blockers\n\n- ...\n\n## Environment Snapshot\n\n- Last session: YYYY-MM-DD\n```\n\n## attention.md (DM)\n\n```markdown\n# Main Session — Current Focus\n\n## Active Tasks\n\n| Task | Status | Notes |\n|------|--------|-------|\n| ... | ... | ... |\n\n## Blockers\n\n- ...\n\n## Environment Snapshot\n\n- Last session: YYYY-MM-DD\n- Pending items: N\n```\n\n## experience.md (Group)\n\n```markdown\n# Experience Log\n\n## Decisions\n\n- [YYYY-MM-DD] Decision: ... → Context: ... | Action: ...\n- [YYYY-MM-DD] Decision: ... → Context: ... | Action: ...\n\n## Lessons Learned\n\n- [YYYY-MM-DD] ... → Problem: ... | Solution: ...\n```\n\n## longterm.md (DM)\n\n```markdown\n# Long-Term Memory — Experience Summary\n\n## MEMORY.md Experience Index\n\n| Topic | MEMORY.md Location | Summary |\n|-------|-------------------|---------|\n| ... | §... | ... |\n\n## Detail Supplements\n\n| Entry | Detail | Source Date |\n|-------|--------|-------------|\n| ... | ... | YYYY-MM-DD |\n\n## Decision Log\n\n- [YYYY-MM-DD] Decision: ... → MEMORY.md §...\n```\n\n## Flush Content Decisions\n\n### ✅ Write This\n\n| Category | Target File | Decision Criteria |\n|----------|------------|-------------------|\n| Confirmed decision | `experience.md` | User explicitly agreed/confirmed |\n| Task status change | `attention.md` | in-progress → completed/blocked |\n| New project agreement | `project.md` | Cross-confirmed by two messages |\n| Personnel role change | `people.md` | Explicit role assignment |\n| Environment change | `attention.md` | Server migration, port change |\n| Lessons learned | `experience.md` | Complete problem + solution |\n\n### ❌ Don't Write\n\n| Category | Reason |\n|----------|--------|\n| Small talk, greetings | No informational value |\n| Opinion only, not landed | No decision formed |\n| Repeating existing content | Already recorded |\n| Temporary exploration | Direction undecided |\n\n## Write-Back Rules\n\n### Group Chat (`memory/groups/{group}/`)\n\n- **`experience.md`**: append-only, reverse chronological, each entry `YYYY-MM-DD` + context + decision + action\n- **`attention.md`**: overwrite (task progress is factual)\n- **`project.md`, `people.md`**: primarily append; deletions require confirmation\n\n### DM (`memory/main/`)\n\n- **`longterm.md`**: each flush, distill MEMORY.md updates with original references\n- **`attention.md`**: overwrite-update tasks/blockers\n- **`daily-synced.md`**: flush-merged summary (append-only)\n- **`MEMORY.md`**: **do not touch**\n\n## Flush State Tracking\n\n```json\n{\n  \"groups\": {\n    \"last_flush_time\": \"2026-05-15T07:30:00+08:00\",\n    \"attention_last_updated\": \"2026-05-15T07:00:00+08:00\",\n    \"experience_last_appended\": \"2026-05-15T06:00:00+08:00\",\n    \"session_id\": \"last-group-session-id\"\n  },\n  \"main_session\": {\n    \"last_flush_time\": \"2026-05-15T07:30:00+08:00\",\n    \"longterm_last_synced\": \"2026-05-15T07:30:00+08:00\",\n    \"attention_last_updated\": \"2026-05-15T07:00:00+08:00\",\n    \"session_id\": \"last-main-session-id\"\n  },\n  \"context_usage_at_flush\": 45,\n  \"pending_items\": [\"Confirm Zhang San is the PM\"]\n}\n```\n\n**Rules**:\n- `groups` and `main_session` are independent\n- Group flush updates `groups.*`\n- DM flush updates `main_session.*`\n- `pending_items` is shared cross-scenario\n\nFile v1.6.0:HOOKS.md\n\n# APM — Hooks Documentation\n\n## Overview\n\nAPM ships with three hooks (two for memory flush, one for first-time bootstrap):\n\n| Hook | Event | Trigger | Action |\n|------|-------|---------|--------|\n| `apm-bootstrap` | `agent:bootstrap`, `gateway:startup` | Agent/gateway starts | Idempotently initialize memory tree (only creates missing files) |\n| `remem-flush` | `message:received` | User sends `/remem` | Manual flush with full session context |\n| `precompact-remem` | `session:compact:before` | Context near limit or idle 30min | Auto-flush before compaction |\n\n**Bootstrap order matters**: install and enable `apm-bootstrap` **first** so the\nmemory tree exists before any flush hook runs. Without `apm-bootstrap`, a fresh\ninstall of APM sits dormant until you run `bootstrap.sh --yes` manually.\n\n## apm-bootstrap Hook (New in v1.6.0)\n\n### Why it exists\n\nBefore v1.6.0, the APM skill shipped only with flush hooks (`remem-flush` and\n`precompact-remem`). Result: a fresh install never initialized the memory\ntree (`memory/main/`, per-group indexes, `flush-state.json`). The 2026-06-18\naudit caught this — three groups were configured but only one had an index,\nand `memory/main/` was completely missing.\n\n`apm-bootstrap` fixes the cold-start gap by running `bootstrap.sh --yes` on\nevery agent startup. The script is idempotent (it never overwrites existing\nfiles), so a fully-initialized workspace pays no cost.\n\n### Configuration\n\n| Item | Config |\n|------|--------|\n| Hook events | `agent:bootstrap`, `gateway:startup` |\n| Hook path (in skill) | `skills/apm-agent-progressive-memory/hooks/apm-bootstrap/` |\n| Hook path (after install) | `~/.openclaw/hooks/apm-bootstrap/` |\n| Trigger conditions | Every agent startup |\n| Side effects | None on initialized trees; creates missing files on cold starts |\n\n### Installation\n\n```bash\n# 1. Copy hook to OpenClaw hooks directory\ncp -r skills/apm-agent-progressive-memory/hooks/apm-bootstrap/ \\\n      ~/.openclaw/hooks/apm-bootstrap/\n\n# 2. Enable the hook\nopenclaw hooks enable apm-bootstrap\n```\n\n### Post-install structure\n\n```\n~/.openclaw/hooks/apm-bootstrap/\n├── HOOK.md\n└── handler.js\n```\n\n### What it does\n\n1. Resolves the workspace root (`event.workspace` → `$WORKSPACE` → heuristic)\n2. Locates `bootstrap.sh` (checks dev path, workspace path, global path)\n3. Spawns `bash bootstrap.sh --yes --workspace <path>`\n4. Logs to `memory/.bootstrap.log`\n\n### Safety guarantees\n\n- `bootstrap.sh` is **idempotent** — never overwrites existing files\n- `bootstrap.sh --workspace` accepts an explicit path → safe in sandboxes\n- Cold-start detection: set `coldStartOnly: true` in hook config to skip\n  when `memory/main/index.md` already exists\n- All actions logged; failures are non-fatal (hook returns `{ok: false}` but\n  does not block agent startup)\n\n### Tuning\n\n| Behavior | Config | Default |\n|----------|--------|---------|\n| Auto-create missing files | `autoYes: true` | `true` |\n| Only run on cold start | `coldStartOnly: true` | `false` |\n| Restrict to one group | `onlyGroup: NAME` | unset |\n\nExample config in `~/.openclaw/config.yaml`:\n\n```yaml\nhooks:\n  internal:\n    entries:\n      apm-bootstrap:\n        enabled: true\n        autoYes: true\n        coldStartOnly: false\n```\n\n## Why Not Use `/new` Hook?\n\nThe built-in `memory-flush` hook listens to `/new` command:\n\n**Problem**: When hook fires on `/new`:\n1. New session is already created\n2. Old session context is lost\n3. Hook has nothing to flush\n\n**Solution**: Custom `remem-flush` hook intercepts `/remem` at message layer. Session is still active.\n\n## remem-flush Hook\n\n### Configuration\n\n| Item | Config |\n|------|--------|\n| Hook event | `message:received` |\n| Hook path | `~/.openclaw/hooks/remem-flush/` |\n| Trigger command | `/remem` |\n\n### Installation\n\n```bash\n# From skill directory:\ncp -r hooks/remem-flush/ ~/.openclaw/hooks/remem-flush/\n```\n\n### Post-install Structure\n\n```\n~/.openclaw/hooks/remem-flush/\n├── HOOK.md\n└── handler.js\n```\n\n### Note\n\nBuilt-in `memory-flush` hook must be disabled:\n```bash\nopenclaw hooks disable memory-flush\n```\n\n## precompact-remem Hook\n\n### Configuration\n\n| Item | Config |\n|------|--------|\n| Hook event | `session:compact:before` |\n| Hook path | `~/.openclaw/hooks/precompact-remem/` |\n| Trigger conditions | Session idle 30min OR tokens ≥1000 |\n\n### Installation\n\n```bash\n# From skill directory:\ncp -r hooks/precompact-remem/ ~/.openclaw/hooks/precompact-remem/\nopenclaw hooks enable precompact-remem\n```\n\n### Post-install Structure\n\n```\n~/.openclaw/hooks/precompact-remem/\n├── HOOK.md\n└── handler.js\n```\n\n## Hook Execution Flow (6 steps)\n\n1. **Context check** — Discover which memory groups are active in session\n2. **Discover groups** — Find all groups with pending updates\n3. **Read old memory** — Compare current state with last flush\n4. **Apply updates** — Write session deltas to files\n5. **Stamp timestamp** — Record flush time\n6. **Write flush-state** — Update `flush-state.json`\n\n## Key Design Principles\n\n- `/remem` fires **while session is still active** → full context available\n- Pre-compact fires **before** context is lost → preserves memory\n- Idle timeout triggers **once only** → no repeated auto-flush\n- Both hooks are **independent** and can run together\n\nFile v1.6.0:hooks/apm-bootstrap/HOOK.md\n\n---\nname: apm-bootstrap\ndescription: \"Idempotently initialize APM progressive-memory layout on agent startup\"\nhomepage: https://docs.openclaw.ai/automation/hooks\nmetadata:\n  {\n    \"openclaw\":\n      {\n        \"emoji\": \"🪄\",\n        \"events\": [\"agent:bootstrap\", \"gateway:startup\"],\n        \"requires\": { \"bins\": [\"bash\"], \"files\": [\"skills/apm-agent-progressive-memory/bootstrap.sh\"] }\n      }\n  }\n---\n\n# APM Bootstrap Hook\n\nOn `agent:bootstrap` and `gateway:startup` events, runs\n`skills/apm-agent-progressive-memory/bootstrap.sh --yes` to ensure\nthe progressive-memory layout is complete.\n\n## What it does\n\n- Creates `memory/main/` (DM progressive entry) if missing\n- Creates progressive indexes for every group in `memory/group_names.json`\n- Creates `memory/flush-state.json` if missing\n- **Never overwrites** existing files (idempotent)\n- Skips groups that already have a complete layout\n\n## Why\n\nBefore this hook, the APM skill shipped with `precompact-remem` and\n`remem-flush` hooks but **no initialization hook**. Result: a fresh\ninstall of the APM skill would sit dormant until someone manually\ncreated the memory tree. The 2026-06-18 audit revealed that even on\na long-running install, missing groups (Pan.C.par, NFP) and the DM\nentry (`memory/main/`) were never created because:\n\n1. APM's auto-init rule triggers on `/remem`/flush\n2. The flush hooks were never `openclaw hooks enable`d\n3. Lazy-init only kicks in for *active* groups, not cold-start ones\n\nThis hook fixes the gap by bootstrapping on every agent startup.\n\n## Configuration\n\nAfter installing this hook, enable it:\n\n```bash\nopenclaw hooks enable apm-bootstrap\n```\n\nOr add to `~/.openclaw/config.yaml`:\n\n```yaml\nhooks:\n  internal:\n    entries:\n      apm-bootstrap:\n        enabled: true\n        autoYes: true   # pass --yes to bootstrap.sh\n```\n\n## Tuning\n\n| Behavior | Flag | Default |\n|----------|------|---------|\n| Auto-create missing files | `autoYes: true` | `true` |\n| Only run on cold start (no files) | `coldStartOnly: true` | `false` |\n| Restrict to specific group | `onlyGroup: NAME` | unset |\n\n## Logs\n\nAll actions logged to `memory/.bootstrap.log`.\n\nSee `skills/apm-agent-progressive-memory/bootstrap.sh --help` for\nthe underlying CLI options.\n\nFile v1.6.0:hooks/precompact-remem/HOOK.md\n\n---\nname: precompact-remem\ndescription: \"Before session context compaction, trigger a memory flush to preserve current session memory.\"\nevents:\n  - session:compact:before\nrequires:\n  config:\n    - workspace.dir\ninstall:\n  - id: precompact-remem-hook\n    kind: local\n    label: \"Pre-Compaction Memory Flush\"\n---\n\n# precompact-remem Hook\n\nIntercepts `session:compact:before` event and runs a 6-step memory flush\nto preserve the current session's context before it gets summarized away.\n\n## Behavior\n\n1. Detect session context (message count, token count)\n2. Discover active memory groups\n3. Read old memory timestamps from flush-state\n4. Compute deltas (changed files since last flush)\n5. Update memory files with session context\n6. Stamp flush-state timestamp\n\n## Events\n\n- `session:compact:before` — fires just before OpenClaw compacts the transcript\n\n## Notes\n\n- This hook complements `remem-flush` which responds to `/remem` commands.\n- `precompact-remem` handles the automatic case: session is being compacted,\n  flush now so no context is lost.\n- Both hooks share the same flush logic and flush-state file.\n\nFile v1.6.0:hooks/remem-flush/HOOK.md\n\n---\nname: remem-flush\ndescription: \"Memory flush hook for /remem command. Triggers 6-step memory flush when user sends /remem in any chat.\"\nevents:\n  - message:received\nrequires:\n  config:\n    - workspace.dir\ninstall:\n  - id: remem-flush-hook\n    kind: local\n    label: \"Memory Flush Hook\"\n---\n\n# remem-flush Hook\n\nIntercept `/remem` messages and trigger a 6-step memory flush.\n\n## Events\n\n- `message:received` — listens for `/remem` command\n\n## Behavior\n\n1. Intercept messages matching `/remem` or `/remem <args>`\n2. Extract session context\n3. Detect active memory groups\n4. Compare with old memory for deltas\n5. Update memory files\n6. Stamp flush-state timestamp\n7. Return control to AI for confirmation reply\n\n## Files Modified\n\n- `memory/flush-state.json` — updated on each flush\n- `memory/groups/{group}/*.md` — updated based on deltas\n\nFile v1.6.0:skill-card.md\n\n## Description: <br>\nAPM Protocol (Agent Progressive Memory): Progressive disclosure protocol for group chat AND DM (main session) memory. <br>\n\nThis skill is ready for commercial/non-commercial use. <br>\n\n## Publisher: <br>\n[biociao](https://clawhub.ai/user/biociao) <br>\n\n### License/Terms of Use: <br>\nMIT-0 <br>\n\n\n## Use Case: <br>\nDevelopers and OpenClaw users use this skill to organize persistent workspace memory with progressive disclosure for group chats and main-session memory. It provides memory access rules, initialization commands, and hooks for manual or pre-compaction memory flushes. <br>\n\n### Deployment Geography for Use: <br>\nGlobal <br>\n\n## Known Risks and Mitigations: <br>\nRisk: The skill creates and updates persistent memory files, which can retain sensitive project or personal information if users store it there. <br>\nMitigation: Install only when persistent workspace memory is intended, and avoid storing secrets or sensitive personal data in MEMORY.md or memory files unless that retention is deliberate. <br>\nRisk: Startup and flush hooks can create or update files under memory/ during agent startup, /remem handling, or session compaction. <br>\nMitigation: Review and enable only the hooks needed for the workspace, especially apm-bootstrap, remem-flush, and precompact-remem; use dry-run or explicit workspace settings when testing. <br>\n\n\n## Reference(s): <br>\n- [ClawHub skill page](https://clawhub.ai/biociao/apm-agent-progressive-memory) <br>\n- [OpenClaw hooks documentation](https://docs.openclaw.ai/automation/hooks) <br>\n\n\n## Skill Output: <br>\n**Output Type(s):** [guidance, markdown, shell commands, configuration, code] <br>\n**Output Format:** [Markdown guidance with shell command examples, hook configuration, and bundled shell and JavaScript files] <br>\n**Output Parameters:** [1D] <br>\n**Other Properties Related to Output:** [Persistent memory behavior writes under memory/ when the bundled bootstrap script or enabled hooks run.] <br>\n\n## Skill Version(s): <br>\n1.6.0 (source: server release evidence, created 2026-06-18) <br>\n\n## Ethical Considerations: <br>\nUsers should evaluate whether this skill is appropriate for their environment, review any generated or modified files before relying on them, and apply their organization's safety, security, and compliance requirements before deployment. <br>\n\nArchive v1.5.0: 9 files, 12429 bytes\n\nFiles: _meta.json (147b), ADDENDUM.md (4961b), HOOKS.md (2426b), hooks/precompact-remem/handler.js (4369b), hooks/precompact-remem/HOOK.md (1113b), hooks/remem-flush/handler.js (4829b), hooks/remem-flush/HOOK.md (847b), skill-card.md (2051b), SKILL.md (6476b)\n\nFile v1.5.0:SKILL.md\n\n---\nname: APM-agent-progressive-memory\ndescription: \"APM Protocol (Agent Progressive Memory): Progressive disclosure protocol for group chat AND DM (main session) memory.\"\n---\n\n# APM — Progressive Disclosure Protocol\n\nAPM supports **both group chat and private (main session DM)** memory management. The two structures are completely independent and do not interfere with each other.\n\n## Group vs DM: Strategy Comparison\n\n| Aspect | Group Chat | DM (Main Session) |\n|-------|-----------|-------------------|\n| **Memory path** | `memory/groups/{group_name}/` | `memory/main/` |\n| **Loading** | 5-step progressive (index → P0 → P1 → P2 → P3) | 3-layer progressive (index → attention → longterm) |\n| **Index file** | `memory/groups/{group_name}.md` | `memory/main/index.md` |\n| **Priority files** | attention.md, project.md, experience.md, people.md | attention.md, longterm.md |\n| **Entry rule** | Must read index first, no subdirectory bypass | Must read index first |\n| **Flush trigger** | Per-group flush on `/remem` | Full-session flush on `/remem` |\n\n**Key differences**:\n- Group uses **5-step loading** with budget controls; DM uses simpler **3-layer**\n- Group has **conventions/** sub-directory; DM does not\n- DM reuses existing **MEMORY.md**; Group uses dedicated files\n- Uninstaller: Group loses memory access; DM retains MEMORY.md\n\nAgent must follow the **layered disclosure protocol** when accessing memory in group chats: read the index first, then load layers on demand.\n\n## Core Rules\n\n### 1. Entry Gate\n\n- The **only legal entry point** for group chat memory is `memory/groups/{group_name}.md` (index file)\n- **Forbidden**: directly reading any sub-files under `memory/groups/{group_name}/`\n- **Forbidden**: bypassing the index to directly `memory_search` subdirectories\n- **Group name mapping rule**: group chat room IDs must first be resolved via `memory/group_names.json` to a friendly name `{group_name}` before use\n\n### 2. Five-Step Loading Flow\n\n| Step | Action | Output |\n|------|--------|--------|\n| 0. Group name mapping | Check `memory/group_names.json`, convert room ID to `{group_name}` | Friendly name |\n| 1. Route to index | `memory_get(\"memory/groups/{group_name}.md\")` | Hard Rules + routing table |\n| 2. Intent matching | Match current message to trigger scenario | File to load |\n| 3. Explicit load | `memory_get(\"memory/groups/{group_name}/{file}.md\")` | Actual memory content |\n| 4. Sub-layer control | Load only if Step 3 file references `conventions/` | 1 sub-file max |\n| 5. Budget circuit-breaker | Stop when cumulative tokens exceed `memory_budget` | Stop loading |\n\nOnly **one** best-matching file is loaded per session (highest priority wins).\n\n### 3. Loading Discipline\n\n- Maximum **2 P0-P2 files + 1 P3 file** per session\n- `conventions/` files: only **1** at a time\n- When switching group chats, clear old context first, then restart from Step 1\n\n### 4. Write-Back on Updates\n\n- New decision → append to `experience.md`\n- Task status change → update `attention.md`\n- Index files: append-only (mark deleted entries `[DEPRECATED]` instead of removing)\n\n### 5. Memory Flush\n\n| Trigger | Condition | Action |\n|---------|-----------|--------|\n| `/remem` | User manual trigger | Full flush |\n| Pre-compact | Context near limit | Auto-flush before loss |\n| Idle timeout | 30min inactive, no flush | One-time auto-flush |\n\n### 6. Auto-Initialization on Missing Memory\n\n> When a flush is triggered for a session whose memory system has **not yet been initialized**, the Agent must initialize it based on available information.\n\n| Scenario | Action |\n|----------|--------|\n| Group index missing | Create from `group_names.json` + context |\n| DM index missing | Create from `MEMORY.md` content |\n\n**Initialization is not overwriting**: existing files are never overwritten — only created when completely absent.\n\n## File Structure\n\n```\nmemory/groups/\n├── {group_name}.md          # L0: Entry gate (mandatory read)\n└── {group_name}/             # Group memory (direct access forbidden)\n    ├── attention.md          # P0: Current focus\n    ├── project.md            # P1: Project static info\n    ├── experience.md         # P2: Experience / decision log\n    ├── people.md             # P3: People profiles\n    └── conventions/          # L3: Detailed specifications\n        ├── api.md\n        └── ...\n\nmemory/main/                    # DM progressive disclosure\n├── index.md                # L0: DM entry index\n├── attention.md            # P0: Current tasks, blockers\n├── longterm.md             # P1: MEMORY.md distilled summary\n├── daily-synced.md         # P2: Daily notes summary\n└── projects/               # P3: Project context\n    └── {name}.md\n```\n\n## Priority Definitions\n\n| Priority | File | Content | When to Load |\n|----------|------|---------|--------------|\n| P0 | `attention.md` | Active tasks, blockers | Any work conversation |\n| P1 | `project.md` | Tech stack, architecture | Technical decisions |\n| P2 | `experience.md` | Lessons learned | Search hit + append |\n| P3 | `people.md` | Team roles, contacts | Need to find someone |\n\n## DM Entry Loading (to add in AGENTS.md)\n\n```markdown\n## Every Session\n\n1. Read `SOUL.md` → USER.md → MEMORY.md\n2. **If in MAIN SESSION** (DM):\n   - Read `memory/main/index.md` — DM progressive index\n   - Based on routing, load up to 2 files\n   - Report `上次 flush: YYYY-MM-DD HH:mm` (from `flush-state.json`)\n3. Read `memory/YYYY-MM-DD.md` (today + yesterday)\n```\n\n## Flush State File\n\n`memory/flush-state.json`:\n\n```json\n{\n  \"groups\": { \"last_flush_time\": \"...\" },\n  \"main_session\": { \"last_flush_time\": \"...\" },\n  \"pending_items\": []\n}\n```\n\n## Anti-Pattern\n\n```\n❌ Load all at once        → ✅ Load only one at a time\n❌ Skip index           → ✅ Read index first\n❌ Load two groups      → ✅ Clear old, reload from Step 1\n```\n\n## Complete Protocol Checklist\n\n1. **Entry gate** — index is the only entry\n2. **Five-step loading** — name mapping → index → intent → load → sub-layer → budget\n3. **Loading discipline** — 2+1 file limit, clear on switch\n4. **Write-back** — immediately update on decisions\n5. **Memory Flush** — `/remem` + Pre-compact + Idle\n6. **Auto-Flush** — precompact hook before compaction\n7. **DM Progressive** — independent layout, survives uninstall\n8. **Auto-Initialization** — init missing memory from known info\n\nFile v1.5.0:_meta.json\n\n{\n  \"ownerId\": \"kn7dz0are44vk4ct393b9kxe4n8209wv\",\n  \"slug\": \"apm-agent-progressive-memory\",\n  \"version\": \"1.5.0\",\n  \"publishedAt\": 1779168201317\n}\n\nFile v1.5.0:ADDENDUM.md\n\n# APM — ADDENDUM (Technical Details)\n\n## Group Index File Template\n\n```markdown\n---\ngroup_name: {group_name}\nlast_updated: YYYY-MM-DD\nstatus: active\nmemory_budget: 6000\n---\n\n# {Group Name} — Progressive Disclosure Index\n\n> ⚠️ This file is the **only legal entry point** for accessing this group's memory.\n\n## Hard Rules\n\n- rule 1\n- rule 2\n\n## Routing Index\n\n| Trigger Scenario | Load File | Priority |\n|-----------------|-----------|----------|\n| Current tasks, Sprint, blockers | `attention.md` | P0 |\n| Tech stack, architecture constraints | `project.md` | P1 |\n| Historical decisions, lessons learned | `experience.md` | P2 |\n| Team roles, contacts | `people.md` | P3 |\n| API development details | `conventions/api.md` | P2-L3 |\n```\n\n## DM Index File Template\n\n```markdown\n---\ntype: main-session-index\nlast_updated: YYYY-MM-DD\nstatus: active\nmemory_budget: 8000\n---\n\n# Main Session Memory Index\n\n> This file is the **only entry point** for DM progressive disclosure.\n\n## Reference Declarations\n\n- **Authoritative long-term memory**: `MEMORY.md` (workspace root)\n- **Raw daily logs**: `memory/YYYY-MM-DD.md`\n\n## Routing Index\n\n| Trigger Scenario | Load File | Priority |\n|-----------------|-----------|----------|\n| Current tasks, blockers | `attention.md` | P0 |\n| MEMORY.md summary | `longterm.md` | P1 |\n| Daily notes summary | `daily-synced.md` | P2 |\n| Project context | `projects/{name}.md` | P3 |\n\n## Relationship with MEMORY.md\n\n> ⚠️ **MEMORY.md is the authoritative original. It stays completely unchanged.**\n> APM's `longterm.md` serves as MEMORY.md's **experience summary + detail supplement layer**.\n\n## attention.md (Group)\n\n```markdown\n# {Group} — Current Focus\n\n## Active Tasks\n\n| Task | Status | Notes |\n|------|--------|-------|\n| ... | ... | ... |\n\n## Blockers\n\n- ...\n\n## Environment Snapshot\n\n- Last session: YYYY-MM-DD\n```\n\n## attention.md (DM)\n\n```markdown\n# Main Session — Current Focus\n\n## Active Tasks\n\n| Task | Status | Notes |\n|------|--------|-------|\n| ... | ... | ... |\n\n## Blockers\n\n- ...\n\n## Environment Snapshot\n\n- Last session: YYYY-MM-DD\n- Pending items: N\n```\n\n## experience.md (Group)\n\n```markdown\n# Experience Log\n\n## Decisions\n\n- [YYYY-MM-DD] Decision: ... → Context: ... | Action: ...\n- [YYYY-MM-DD] Decision: ... → Context: ... | Action: ...\n\n## Lessons Learned\n\n- [YYYY-MM-DD] ... → Problem: ... | Solution: ...\n```\n\n## longterm.md (DM)\n\n```markdown\n# Long-Term Memory — Experience Summary\n\n## MEMORY.md Experience Index\n\n| Topic | MEMORY.md Location | Summary |\n|-------|-------------------|---------|\n| ... | §... | ... |\n\n## Detail Supplements\n\n| Entry | Detail | Source Date |\n|-------|--------|-------------|\n| ... | ... | YYYY-MM-DD |\n\n## Decision Log\n\n- [YYYY-MM-DD] Decision: ... → MEMORY.md §...\n```\n\n## Flush Content Decisions\n\n### ✅ Write This\n\n| Category | Target File | Decision Criteria |\n|----------|------------|-------------------|\n| Confirmed decision | `experience.md` | User explicitly agreed/confirmed |\n| Task status change | `attention.md` | in-progress → completed/blocked |\n| New project agreement | `project.md` | Cross-confirmed by two messages |\n| Personnel role change | `people.md` | Explicit role assignment |\n| Environment change | `attention.md` | Server migration, port change |\n| Lessons learned | `experience.md` | Complete problem + solution |\n\n### ❌ Don't Write\n\n| Category | Reason |\n|----------|--------|\n| Small talk, greetings | No informational value |\n| Opinion only, not landed | No decision formed |\n| Repeating existing content | Already recorded |\n| Temporary exploration | Direction undecided |\n\n## Write-Back Rules\n\n### Group Chat (`memory/groups/{group}/`)\n\n- **`experience.md`**: append-only, reverse chronological, each entry `YYYY-MM-DD` + context + decision + action\n- **`attention.md`**: overwrite (task progress is factual)\n- **`project.md`, `people.md`**: primarily append; deletions require confirmation\n\n### DM (`memory/main/`)\n\n- **`longterm.md`**: each flush, distill MEMORY.md updates with original references\n- **`attention.md`**: overwrite-update tasks/blockers\n- **`daily-synced.md`**: flush-merged summary (append-only)\n- **`MEMORY.md`**: **do not touch**\n\n## Flush State Tracking\n\n```json\n{\n  \"groups\": {\n    \"last_flush_time\": \"2026-05-15T07:30:00+08:00\",\n    \"attention_last_updated\": \"2026-05-15T07:00:00+08:00\",\n    \"experience_last_appended\": \"2026-05-15T06:00:00+08:00\",\n    \"session_id\": \"last-group-session-id\"\n  },\n  \"main_session\": {\n    \"last_flush_time\": \"2026-05-15T07:30:00+08:00\",\n    \"longterm_last_synced\": \"2026-05-15T07:30:00+08:00\",\n    \"attention_last_updated\": \"2026-05-15T07:00:00+08:00\",\n    \"session_id\": \"last-main-session-id\"\n  },\n  \"context_usage_at_flush\": 45,\n  \"pending_items\": [\"Confirm Zhang San is the PM\"]\n}\n```\n\n**Rules**:\n- `groups` and `main_session` are independent\n- Group flush updates `groups.*`\n- DM flush updates `main_session.*`\n- `pending_items` is shared cross-scenario\n\nFile v1.5.0:HOOKS.md\n\n# APM — Hooks Documentation\n\n## Overview\n\nAPM uses two hooks for automatic memory flush:\n\n| Hook | Event | Trigger | Action |\n|------|-------|---------|--------|\n| `remem-flush` | `message:received` | User sends `/remem` | Manual flush with full session context |\n| `precompact-remem` | `session:compact:before` | Context near limit or idle 30min | Auto-flush before compaction |\n\n## Why Not Use `/new` Hook?\n\nThe built-in `memory-flush` hook listens to `/new` command:\n\n**Problem**: When hook fires on `/new`:\n1. New session is already created\n2. Old session context is lost\n3. Hook has nothing to flush\n\n**Solution**: Custom `remem-flush` hook intercepts `/remem` at message layer. Session is still active.\n\n## remem-flush Hook\n\n### Configuration\n\n| Item | Config |\n|------|--------|\n| Hook event | `message:received` |\n| Hook path | `~/.openclaw/hooks/remem-flush/` |\n| Trigger command | `/remem` |\n\n### Installation\n\n```bash\n# From skill directory:\ncp -r hooks/remem-flush/ ~/.openclaw/hooks/remem-flush/\n```\n\n### Post-install Structure\n\n```\n~/.openclaw/hooks/remem-flush/\n├── HOOK.md\n└── handler.js\n```\n\n### Note\n\nBuilt-in `memory-flush` hook must be disabled:\n```bash\nopenclaw hooks disable memory-flush\n```\n\n## precompact-remem Hook\n\n### Configuration\n\n| Item | Config |\n|------|--------|\n| Hook event | `session:compact:before` |\n| Hook path | `~/.openclaw/hooks/precompact-remem/` |\n| Trigger conditions | Session idle 30min OR tokens ≥1000 |\n\n### Installation\n\n```bash\n# From skill directory:\ncp -r hooks/precompact-remem/ ~/.openclaw/hooks/precompact-remem/\nopenclaw hooks enable precompact-remem\n```\n\n### Post-install Structure\n\n```\n~/.openclaw/hooks/precompact-remem/\n├── HOOK.md\n└── handler.js\n```\n\n## Hook Execution Flow (6 steps)\n\n1. **Context check** — Discover which memory groups are active in session\n2. **Discover groups** — Find all groups with pending updates\n3. **Read old memory** — Compare current state with last flush\n4. **Apply updates** — Write session deltas to files\n5. **Stamp timestamp** — Record flush time\n6. **Write flush-state** — Update `flush-state.json`\n\n## Key Design Principles\n\n- `/remem` fires **while session is still active** → full context available\n- Pre-compact fires **before** context is lost → preserves memory\n- Idle timeout triggers **once only** → no repeated auto-flush\n- Both hooks are **independent** and can run together\n\nFile v1.5.0:hooks/precompact-remem/HOOK.md\n\n---\nname: precompact-remem\ndescription: \"Before session context compaction, trigger a memory flush to preserve current session memory.\"\nevents:\n  - session:compact:before\nrequires:\n  config:\n    - workspace.dir\ninstall:\n  - id: precompact-remem-hook\n    kind: local\n    label: \"Pre-Compaction Memory Flush\"\n---\n\n# precompact-remem Hook\n\nIntercepts `session:compact:before` event and runs a 6-step memory flush\nto preserve the current session's context before it gets summarized away.\n\n## Behavior\n\n1. Detect session context (message count, token count)\n2. Discover active memory groups\n3. Read old memory timestamps from flush-state\n4. Compute deltas (changed files since last flush)\n5. Update memory files with session context\n6. Stamp flush-state timestamp\n\n## Events\n\n- `session:compact:before` — fires just before OpenClaw compacts the transcript\n\n## Notes\n\n- This hook complements `remem-flush` which responds to `/remem` commands.\n- `precompact-remem` handles the automatic case: session is being compacted,\n  flush now so no context is lost.\n- Both hooks share the same flush logic and flush-state file.\n\nFile v1.5.0:hooks/remem-flush/HOOK.md\n\n---\nname: remem-flush\ndescription: \"Memory flush hook for /remem command. Triggers 6-step memory flush when user sends /remem in any chat.\"\nevents:\n  - message:received\nrequires:\n  config:\n    - workspace.dir\ninstall:\n  - id: remem-flush-hook\n    kind: local\n    label: \"Memory Flush Hook\"\n---\n\n# remem-flush Hook\n\nIntercept `/remem` messages and trigger a 6-step memory flush.\n\n## Events\n\n- `message:received` — listens for `/remem` command\n\n## Behavior\n\n1. Intercept messages matching `/remem` or `/remem <args>`\n2. Extract session context\n3. Detect active memory groups\n4. Compare with old memory for deltas\n5. Update memory files\n6. Stamp flush-state timestamp\n7. Return control to AI for confirmation reply\n\n## Files Modified\n\n- `memory/flush-state.json` — updated on each flush\n- `memory/groups/{group}/*.md` — updated based on deltas\n\nFile v1.5.0:skill-card.md\n\n## Description: <br>\nAPM Protocol (Agent Progressive Memory): Progressive disclosure protocol for group chat AND DM (main session) memory. <br>\n\nThis skill is ready for commercial/non-commercial use. <br>\n\n## Publisher: <br>\n[biociao](https://clawhub.ai/user/biociao) <br>\n\n### License/Terms of Use: <br>\nMIT-0 <br>\n\n\n## Use Case: <br>\nDevelopers and OpenClaw users use this skill to maintain progressive local memory across group chats and DM sessions while controlling when memory files are loaded and flushed. <br>\n\n### Deployment Geography for Use: <br>\nGlobal <br>\n\n## Known Risks and Mitigations: <br>\nRisk: The skill persists and reloads local workspace memory across chats and DM sessions. <br>\nMitigation: Install only when persistent local memory is desired, and review MEMORY.md, daily notes, memory/main, and group memory files regularly. <br>\nRisk: /remem and pre-compaction hooks can update memory state without a separate preview. <br>\nMitigation: Review hook behavior before enabling it, monitor memory/flush-state.json, and disable the hooks if automatic memory updates are not appropriate for the workspace. <br>\n\n\n## Reference(s): <br>\n- [APM Progressive Disclosure Protocol](artifact/SKILL.md) <br>\n- [APM Technical Details](artifact/ADDENDUM.md) <br>\n- [APM Hooks Documentation](artifact/HOOKS.md) <br>\n\n\n## Skill Output: <br>\n**Output Type(s):** [guidance, markdown, code, shell commands, configuration] <br>\n**Output Format:** [Markdown guidance with JavaScript hook code and shell command examples] <br>\n**Output Parameters:** [1D] <br>\n**Other Properties Related to Output:** [May create or update local memory Markdown files and flush-state JSON through installed hooks.] <br>\n\n## Skill Version(s): <br>\n1.5.0 (source: server release metadata) <br>\n\n## Ethical Considerations: <br>\nUsers should evaluate whether this skill is appropriate for their environment, review any generated or modified files before relying on them, and apply their organization's safety, security, and compliance requirements before deployment. <br>\n\nArchive v1.4.3: 6 files, 13402 bytes\n\nFiles: _meta.json (147b), hooks/precompact-remem/handler.js (4369b), hooks/precompact-remem/HOOK.md (1113b), hooks/remem-flush/handler.js (4829b), hooks/remem-flush/HOOK.md (847b), SKILL.md (21800b)\n\nFile v1.4.3:SKILL.md\n\n---\nname: APM-agent-progressive-memory\ndescription: \"APM Protocol (Agent Progressive Memory): Progressive disclosure protocol for group chat memory. Activated when an Agent needs to access historical memory in group/team/project collaboration scenarios. Prevents Agents from loading all memory at once or skipping the index to read subdirectories directly.\"\n---\n\n> **Skill Alias**: When users mention `APM`, they refer to this skill: `APM-agent-progressive-memory`.\n> Agents installing this skill should record this alias mapping in MEMORY.md or AGENTS.md.\n\n# APM — Progressive Disclosure Protocol\n\nAPM supports **both group chat and private (main session DM)** memory management. The two structures are completely independent and do not interfere with each other.\n\nAgent must follow the **layered disclosure protocol** when accessing memory in group chats: read the index first, then load layers on demand.\n\n## Core Rules\n\n### 1. Entry Gate\n\n- The **only legal entry point** for group chat memory is `memory/groups/{group_name}.md` (index file)\n- **Forbidden**: directly reading any sub-files under `memory/groups/{group_name}/`\n- **Forbidden**: bypassing the index to directly `memory_search` subdirectories\n- **Group name mapping rule**: Matrix room IDs (e.g., `!xxx:matrix.example.com`) must first be resolved via `memory/group_names.json` to a friendly name `{group_name}` before use\n\n### 2. Five-Step Loading Flow\n\n| Step | Action | Output |\n|------|--------|--------|\n| 0. Group name mapping | Check `memory/group_names.json`, convert Matrix room ID to `{group_name}` | Friendly name |\n| 1. Route to index | `memory_get(\"memory/groups/{group_name}.md\")` | Hard Rules + routing table |\n| 2. Intent matching | Match current message to one trigger scenario in the index | File to load |\n| 3. Explicit load | `memory_get(\"memory/groups/{group_name}/{file}.md\")` | Actual memory content |\n| 4. Sub-layer control | Load only if Step 3 file references `conventions/` | 1 sub-file max |\n| 5. Budget circuit-breaker | Stop when cumulative tokens exceed `memory_budget` | Prompt user |\n\n> Step 0 is mandatory: every time entering group chat memory, **must resolve the group name first**, converting the Matrix room ID to a friendly name before file operations.\n> `group_names.json` format: `{room_id}: {name, display_name}`\n\nOnly **one** best-matching file is loaded per session (highest priority wins).\n\n### 3. Loading Discipline\n\n- Maximum **2 P0-P2 files + 1 P3 file** per session\n- `conventions/` files: only **1** at a time\n- When `attention.md` is marked `[ARCHIVED]`, only load `project.md`\n- When switching group chats, clear old context first, then restart from Step 1\n\n### 4. Write-Back on Updates\n\n- New decision → append to `experience.md`\n- Task status change → update `attention.md`\n- Index files: append-only (mark deleted entries `[DEPRECATED]` instead of removing)\n\n### 5. Auto-Initialization on Missing Memory\n\n> When a flush is triggered for a session (group or DM) whose memory system has **not yet been initialized**, the Agent must initialize it based on available information.\n\n\n**Trigger condition**: During `/remem`, Cron, or precompact flush, the Agent detects that the target group's index file (`memory/groups/{group_name}.md`) or the DM index file (`memory/main/index.md`) does not exist.\n\n**Initialization rules**:\n\n| Scenario | Condition | Action |\n|----------|-----------|--------|\n| Group chat index missing | `memory/groups/{group_name}.md` not found | Create index from `group_names.json` entry; scan conversation context for project name, participants, and topic; write Hard Rules + routing table |\n| Group sub-files missing | `memory/groups/{group_name}/` directory empty | Initialize with default attention.md + one blank project.md or experience.md based on context |\n| DM index missing | `memory/main/index.md` not found | Create from existing MEMORY.md content; distill key sections into routing index |\n\n**Initialization workflow**:\n1. **Detect**: Flush detects target index or sub-directory does not exist\n2. **Gather**: Extract project name, topic, participants from known sources (`group_names.json`, conversation context, MEMORY.md)\n3. **Create**: Write minimal viable index + first sub-file from gathered info\n4. **Flush**: Continue normal flush into the newly initialized structure\n5. **Report**: Inform user that a new memory system was initialized\n\n\n**Initialization is not overwriting**: existing files are never overwritten during init — only created when completely absent.\n\n## File Structure\n\n```\nmemory/groups/\n├── {group_name}.md          # L0: Entry gate + throttle (mandatory read)\n└── {group_name}/             # Group-private memory (direct access forbidden)\n    ├── attention.md          # P0: Current focus\n    ├── project.md            # P1: Project static info\n    ├── experience.md         # P2: Experience / decision log\n    ├── people.md             # P3: People profiles\n    └── conventions/          # L3: Detailed specifications\n        ├── api.md\n        ├── db.md\n        └── ...\n```\n\n> **Naming convention**: All files and directories use friendly names `{group_name}`. Matrix room IDs (e.g., `!xxx:matrix.example.com`) are **never** used directly. Use `memory/group_names.json` for ID → name mapping.\n\n## Priority Definitions\n\n| Priority | File | Content | When to Load |\n|----------|------|---------|--------------|\n| P0 | `attention.md` | Active tasks, blockers, environment snapshot | Any conversation related to current work |\n| P1 | `project.md` | Tech stack, architecture constraints, spec index | Technical decisions, architecture discussion, onboarding |\n| P2 | `experience.md` | Historical decisions, lessons learned, retrospectives | memory_search hit + append load |\n| P3 | `people.md` | Team roles, approval chains, contact info | When you need to find someone |\n\n## Anti-Pattern Quick Reference\n\n```\n❌ Load all index-referenced files at once        → ✅ Load only one at a time\n❌ Skip index, read sub-files directly            → ✅ Load index first\n❌ Load two group chats simultaneously             → ✅ Clear old, then reload from Step 1\n❌ Load full experience.md                        → ✅ Load fragments on search hit\n```\n\n---\n\n## Main Session (DM) Progressive Disclosure Layout\n\n> This section defines the progressive memory layout for **private chat (DM / main session)** scenarios.\n> Completely independent from the group chat system — the two structures do not interfere.\n\n### Design Principles\n\n1. **Non-destructive to original mechanism** — `MEMORY.md` stays in place, AGENTS.md still loads it directly\n2. **Survives skill uninstall** — All memory files exist independently in `memory/main/` and `MEMORY.md`, not dependent on the skill\n3. **Synergy with daily notes** — Daily notes are raw logs; `memory/main/` is the curated distillation layer\n4. **DM-exclusive structure** — Does not reuse `memory/groups/`, avoiding confusion with group chat memory\n\n### File Structure\n\n```\nmemory/main/                    # DM progressive disclosure (parallel to groups/)\n├── index.md                # L0: DM entry index (loaded first in every DM session)\n├── attention.md            # P0: Current tasks, blockers, environment snapshot\n├── longterm.md             # P1: Curated distillation of MEMORY.md (with original references)\n├── daily-synced.md         # P2: Flush-merged daily notes summary\n└── projects/               # P3: Project-level context\n    ├── NFP.md\n    ├── PanCpar.md\n    └── ...\n\nMEMORY.md                     # Original long-term memory (workspace root)\nmemory/YYYY-MM-DD.md          # Raw daily logs (memory/ directory)\n```\n\n### Relationship with AGENTS.md\n\n```\nAGENTS.md loading order (with APM installed):\n  SOUL.md → USER.md → MEMORY.md → daily notes\n                        ↑\n                   APM injects: for DM sessions, also loads\n                   memory/main/index.md → loads sub-files on demand\n\nAfter skill uninstall:\n  AGENTS.md still loads MEMORY.md + daily notes in original order, unaffected\n```\n\n### DM Entry Loading Rules\n\nWhen `chat_type === \"direct\"` (DM), **append** these steps to the AGENTS.md Every Session flow:\n\n```markdown\n## Every Session\n\n1. Read `SOUL.md` — this is who you are\n2. Read `USER.md` — this is who you're helping\n3. **If in MAIN SESSION** (DM): Load progressive disclosure index:\n   - Read `memory/main/index.md` — DM progressive disclosure index\n   - Based on index routing, load up to 2 P0-P2 files (attention.md / longterm.md / daily-synced.md / projects/)\n   - Report `上次 flush: YYYY-MM-DD HH:mm` to user (from `flush-state.json` → `main_session.last_flush_time`)\n4. Read `memory/YYYY-MM-DD.md` (today + yesterday) for recent context\n5. **If in MAIN SESSION** (DM): Also read `MEMORY.md` — original long-term memory (unchanged, APM does not modify it)\n```\n\n> 📌 **Installer note**: The steps above are manually added to AGENTS.md by the installer, or injected by the skill install script.\n> APM does NOT modify SOUL.md. It only appends DM progressive loading steps to AGENTS.md.\n\nFinal load budget: **full MEMORY.md + index.md + up to 2 P0-P2 sub-files**\n\n### DM Routing Index (index.md Template)\n\n```markdown\n---\ntype: main-session-index\nlast_updated: YYYY-MM-DD\nstatus: active\nmemory_budget: 8000\n---\n\n# Main Session Memory Index\n\n> This file is the **only entry point** for DM progressive disclosure.\n> Only used in private chat / main session contexts.\n> This file **references** but does **not copy** MEMORY.md content, preserving the original as authoritative.\n\n## Reference Declarations\n\n- **Authoritative long-term memory**: `MEMORY.md` (workspace root)\n- **Raw daily logs**: `memory/YYYY-MM-DD.md`\n- **This file's role**: Index + curated distillation + navigation\n\n## Routing Index\n\n| Trigger Scenario | Load File | Priority | Notes |\n|-----------------|-----------|----------|-------|\n| Current tasks, blockers | `attention.md` | P0 | Syncs with MEMORY.md current tasks |\n| MEMORY.md curated summary | `longterm.md` | P1 | Thematic summary with original reference links |\n| Daily notes summary | `daily-synced.md` | P2 | Flush-merged daily logs |\n| Project context | `projects/{name}.md` | P3 | Deep context per project |\n\n## Relationship with MEMORY.md\n\n> ⚠️ **MEMORY.md is the authoritative original. It stays completely unchanged.**\n> APM's `longterm.md` serves as MEMORY.md's **experience summary + detail supplement layer**:\n> - **Summary**: distill key entries from MEMORY.md into an index (format: topic → MEMORY.md location)\n> - **Supplement**: record details, context, and decision background not covered in MEMORY.md\n> - **Reference**: keep \"See MEMORY.md §X\" links for traceback to original\n>\n> After skill uninstall, `MEMORY.md` remains fully functional; `longterm.md` reference links become stale (harmless).\n\n## Last Flush Time\n\nSee `flush-state.json` → `main_session.last_flush_time`.\nAfter loading index.md, report to user: `上次 flush: YYYY-MM-DD HH:mm`\n```\n\n### attention.md (DM)\n\n```markdown\n# Main Session — Current Focus\n\n## Active Tasks\n\n| Task | Status | Notes |\n|------|--------|-------|\n| ... | ... | ... |\n\n## Blockers\n\n- ...\n\n## Environment Snapshot\n\n- Last session: YYYY-MM-DD\n- Pending items: N\n```\n\n### longterm.md (DM)\n\n```markdown\n# Long-Term Memory — Experience Summary\n\n> This file is MEMORY.md's **experience summary + detail supplement layer**.\n> MEMORY.md is the authoritative original; this file provides distilled index and context not recorded in MEMORY.md.\n\n## MEMORY.md Experience Index\n\n| Topic | MEMORY.md Location | Summary |\n|-------|-------------------|---------|\n| OpenClaw exec mechanism | §Technical Lessons | exec is ephemeral, nohup is persistent |\n| SFTP credentials | TOOLS.md (not in MEMORY) | PUMCH server 172.24.195.51:2022 |\n| PUMCH project structure | §Workspace Structure | /PROJ/PUMCH/USERS/bot/ |\n\n## Detail Supplements (not in MEMORY.md)\n\n| Entry | Detail | Source Date |\n|-------|--------|------------|\n| ... | ... | YYYY-MM-DD |\n\n## Decision Log\n\n- [YYYY-MM-DD] Decision: ... → MEMORY.md §... |\n```\n\n---\n\n## Index File Template\n\n```markdown\n---\ngroup_name: your-group    # From group_names.json mapping\nlast_updated: YYYY-MM-DD\nstatus: active\nmemory_budget: 6000\n---\n\n# {Group Name} — Progressive Disclosure Index\n\n> ⚠️ This file is the **only legal entry point** for accessing this group's memory.\n\n## Hard Rules\n\n- rule 1\n- rule 2\n\n## Routing Index\n\n| Trigger Scenario | Load File | Priority |\n|-----------------|-----------|----------|\n| Current tasks, Sprint, blockers | `attention.md` | P0 |\n| Tech stack, architecture constraints | `project.md` | P1 |\n| Historical decisions, lessons learned | `experience.md` | P2 |\n| Team roles, contacts | `people.md` | P3 |\n| API development details | `conventions/api.md` | P2-L3 |\n```\n\n---\n\n## 5. Memory Flush — Periodic Memory Sweep ⭐\n\n> Protocol rule 4 defines \"manual updates\". This extension defines **automatic periodic flushing**.\n\nProgressive disclosure solves \"what to read\". This extension solves \"when to write, what to write\".\n\n### 5.1 Flush Trigger Schedule\n\n| Priority | Trigger | Condition | Action |\n|----------|---------|-----------|--------|\n| P0 | **Manual: `/remem`** 🪝 | User sends `/remem` in any chat | Manual flush with full context |\n| P1 | **Pre-compact flush** ⚡ | Context tokens near limit, about to compact | Automatic flush before context loss |\n| P2 | **Idle timeout** ⏸ | Session idle 30min + no flush since last run | One-time automatic flush (no repeat) |\n\n### Flush Conditions\n\n- **Manual**: User explicitly triggers with `/remem`\n- **Pre-compact**: When session is about to be compacted, flush first to preserve context\n- **Idle**: After 30min of no activity, trigger one flush (key: `flush_state.main_session.last_flush_time` must be older than 30min)\n\n### Precompact-Remem Hook\n\nAvailable via `~/.openclaw/hooks/precompact-remem/`:\n\n| Item | Config |\n|------|--------|\n| Hook event | `session:compact:before` |\n| Condition | Pre-compact trigger (context near limit) |\n| Action | Automatic flush to preserve current context |\n\n> **Key design**: `/remem` fires **while the session is still active**, so the hook receives the full session context, not an empty state.\n\n### 5.1c Precompact-Remem Hook (Auto-flush on Idle)\n\nAvailable via `~/.openclaw/hooks/precompact-remem/`:\n\n| Item | Config |\n|------|--------|\n| Hook event | `session:compact:before` |\n| Trigger condition | Session idle 30min OR tokens ≥1000 |\n| Action | Automatic flush before context compaction |\n\n**Installation**:\n```bash\ncp -r hooks/precompact-remem/ ~/.openclaw/hooks/precompact-remem/\nopenclaw hooks enable precompact-remem\n```\n\nThis provides automatic P3 flush when:\n- Session has been idle for 30 minutes\n- No flush has been performed since last run\n- Session is about to be compacted (context will be lost)\n| Execution flow | 6 steps: context usage check → discover memory groups → read old memory for deltas → apply updates → stamp timestamp → write flush-state |\n\n### ⚠️ Why Not Use `/new` Hook?\n\nThe built-in `memory-flush` hook listens to `command:new` (i.e., `/new`), but there is a fundamental conflict:\n\n1. `/new`'s semantics are **creating a new session**\n2. When the hook fires on `/new`, the new session is already created, **old session context is already lost**\n3. The hook's `previousSessionEntry` may no longer be accessible after new session creation\n4. Result: hook fires but has nothing to flush, **command is silently swallowed**\n\n**Solution**: Custom `remem-flush` hook intercepts `/remem` at the message layer via `message:received`. The session is still active, full context is available.\n\n### 5.1b remem-flush Hook Installation\n\nHook files are packaged in the skill directory. Copy to OpenClaw hooks directory on install:\n\n```bash\n# Skill internal path (after install):\n# hooks/remem-flush/\n#   ├── HOOK.md       # Metadata + documentation\n#   └── handler.js    # Processing logic\n\n# Install command (from skill directory):\ncp -r hooks/remem-flush/ ~/.openclaw/hooks/remem-flush/\n```\n\n**Post-install structure:**\n```\n~/.openclaw/hooks/remem-flush/\n├── HOOK.md\n└── handler.js\n```\n\n**Note**: Built-in `memory-flush` hook must be disabled (`enabled: false`), otherwise `/new` will be intercepted by it and fail.\n\n### 5.1c precompact-remem Hook (Optional, Recommended)\n\n**Automatically** executes memory flush before session context compaction — no manual trigger needed:\n\n| Item | Config |\n|------|--------|\n| Hook event | `session:compact:before` |\n| Hook path | `~/.openclaw/hooks/precompact-remem/` |\n| Trigger condition | Session has ≥10 messages or ≥1000 tokens |\n\n```bash\n# Install:\ncp -r hooks/precompact-remem/ ~/.openclaw/hooks/precompact-remem/\n```\n\n**Enable after install:**\n```bash\nopenclaw hooks enable precompact-remem\n```\n\nThe two hooks complement each other:\n- `remem-flush` — user manually triggers with `/remem`\n- `precompact-remem` — **automatic** trigger before context compaction\n\n### 5.2 Flush Content Decisions\n\n#### ✅ Write This\n\n| Category | Target File | Decision Criteria |\n|----------|------------|-------------------|\n| Confirmed decision | `experience.md` | User explicitly agreed/confirmed, or action was taken |\n| Task status change | `attention.md` | in-progress → completed/blocked/changed |\n| New project agreement | `project.md` | Cross-confirmed by two separate messages |\n| Personnel role change | `people.md` | Explicit role assignment or change |\n| Environment/config change | `attention.md` | Server migration, port change, key rotation |\n| Lessons learned / fix record | `experience.md` | Complete record of problem + solution |\n\n#### ❌ Don't Write\n\n| Category | Reason |\n|----------|--------|\n| Small talk, greetings, daily banter | No informational value |\n| Opinion only, not yet landed | No decision formed |\n| Repeating existing content | Matches already-recorded entries |\n| Temporary exploratory discussion | Direction undecided, may change |\n\n### 5.3 Write-Back Rules\n\n**Group chat scenarios** (`memory/groups/{group}/`):\n- **`experience.md`**: append-only, reverse chronological, each entry has `YYYY-MM-DD`, context, decision, action\n- **`attention.md`**: overwrite old state (task progress is factual, not a log)\n- **`project.md`, `people.md`**: primarily append; deletions require explicit confirmation\n- **`group_names.json`**: new members or role changes may be appended; no destructive updates\n\n**DM scenarios** (`memory/main/`):\n- **`longterm.md`**: each flush, distill MEMORY.md update content into index entries with original location references\n- **`attention.md`**: overwrite-update current tasks/blockers\n- **`daily-synced.md`**: flush-merged daily notes summary (append-only)\n- **`projects/{name}.md`**: supplement project context on demand\n- **`MEMORY.md`**: **do not touch** — remains the authoritative original\n\n### 5.4 Flush State File\n\n`memory/flush-state.json` tracks flush state. **Group and DM flush tracking are completely independent**:\n\n```json\n{\n  \"groups\": {\n    \"last_flush_time\": \"2026-05-15T07:30:00+08:00\",\n    \"attention_last_updated\": \"2026-05-15T07:00:00+08:00\",\n    \"experience_last_appended\": \"2026-05-15T06:00:00+08:00\",\n    \"session_id\": \"last-group-session-id\"\n  },\n  \"main_session\": {\n    \"last_flush_time\": \"2026-05-15T07:30:00+08:00\",\n    \"longterm_last_synced\": \"2026-05-15T07:30:00+08:00\",\n    \"attention_last_updated\": \"2026-05-15T07:00:00+08:00\",\n    \"session_id\": \"last-main-session-id\"\n  },\n  \"context_usage_at_flush\": 45,\n  \"pending_items\": [\"Confirm Zhang San is the new PM\"]\n}\n```\n\nUsage rules:\n- **`groups`** and **`main_session`** are completely independent flush tracking blocks\n- Group chat flush only updates `groups.*` fields\n- DM flush only updates `main_session.*` fields\n- `pending_items` is shared; items pending confirmation are cross-scenario\n- After skill uninstall, `main_session` section of `flush-state.json` becomes stale (harmless); `groups` section remains unaffected\n\n### 5.5 Integration with Progressive Disclosure\n\n```\n        Read: Progressive Disclosure           Write: Memory Flush\n              ↓                                      ↓\n        Index → Load on demand              Session deltas → Write to files\n              ↓                                      ↓\n         Save tokens + precise reading       No info loss + automatic maintenance\n              ↓                                      ↓\n              └── Complete memory loop ←─────────────┘\n```\n\nAfter loading a file, report the file's last flush time to the user (e.g., `attention.md last updated: 2026-05-14, current session has 2 task status changes pending flush`)\n\n## Complete Protocol Checklist\n\n1. **Entry gate** — index is the only entry, no direct subdirectory access\n2. **Five-step loading flow** — group name mapping → route to index → intent match → explicit load → sub-layer control → budget circuit-breaker\n3. **Loading discipline** — 2+1 file limit, clear on group switch\n4. **Manual write-back** — immediately write back new decisions/status changes\n5. **Memory Flush** — `/remem` manual + Pre-compact auto-flush + Idle timeout (30min, one-time)\n6. **Auto-Flush** — `precompact-remem` hook fires before session compaction\n7. **DM Progressive Disclosure** — main session DM uses independent layout (`memory/main/`), completely independent from group chats; MEMORY.md still loads normally after skill uninstall\n8. **Auto-Initialization** — during any flush, if target memory system is absent, initialize it from known info before flushing\n\nFile v1.4.3:_meta.json\n\n{\n  \"ownerId\": \"kn7dz0are44vk4ct393b9kxe4n8209wv\",\n  \"slug\": \"apm-agent-progressive-memory\",\n  \"version\": \"1.4.3\",\n  \"publishedAt\": 1779166498692\n}\n\nFile v1.4.3:hooks/precompact-remem/HOOK.md\n\n---\nname: precompact-remem\ndescription: \"Before session context compaction, trigger a memory flush to preserve current session memory.\"\nevents:\n  - session:compact:before\nrequires:\n  config:\n    - workspace.dir\ninstall:\n  - id: precompact-remem-hook\n    kind: local\n    label: \"Pre-Compaction Memory Flush\"\n---\n\n# precompact-remem Hook\n\nIntercepts `session:compact:before` event and runs a 6-step memory flush\nto preserve the current session's context before it gets summarized away.\n\n## Behavior\n\n1. Detect session context (message count, token count)\n2. Discover active memory groups\n3. Read old memory timestamps from flush-state\n4. Compute deltas (changed files since last flush)\n5. Update memory files with session context\n6. Stamp flush-state timestamp\n\n## Events\n\n- `session:compact:before` — fires just before OpenClaw compacts the transcript\n\n## Notes\n\n- This hook complements `remem-flush` which responds to `/remem` commands.\n- `precompact-remem` handles the automatic case: session is being compacted,\n  flush now so no context is lost.\n- Both hooks share the same flush logic and flush-state file.\n\nFile v1.4.3:hooks/remem-flush/HOOK.md\n\n---\nname: remem-flush\ndescription: \"Memory flush hook for /remem command. Triggers 6-step memory flush when user sends /remem in any chat.\"\nevents:\n  - message:received\nrequires:\n  config:\n    - workspace.dir\ninstall:\n  - id: remem-flush-hook\n    kind: local\n    label: \"Memory Flush Hook\"\n---\n\n# remem-flush Hook\n\nIntercept `/remem` messages and trigger a 6-step memory flush.\n\n## Events\n\n- `message:received` — listens for `/remem` command\n\n## Behavior\n\n1. Intercept messages matching `/remem` or `/remem <args>`\n2. Extract session context\n3. Detect active memory groups\n4. Compare with old memory for deltas\n5. Update memory files\n6. Stamp flush-state timestamp\n7. Return control to AI for confirmation reply\n\n## Files Modified\n\n- `memory/flush-state.json` — updated on each flush\n- `memory/groups/{group}/*.md` — updated based on deltas\n\nArchive v1.4.2: 6 files, 13578 bytes\n\nFiles: _meta.json (147b), hooks/precompact-remem/handler.js (4369b), hooks/precompact-remem/HOOK.md (1113b), hooks/remem-flush/handler.js (4829b), hooks/remem-flush/HOOK.md (847b), SKILL.md (22025b)\n\nFile v1.4.2:SKILL.md\n\n---\nname: APM-agent-progressive-memory\ndescription: \"APM Protocol (Agent Progressive Memory): Progressive disclosure protocol for group chat memory. Activated when an Agent needs to access historical memory in group/team/project collaboration scenarios. Prevents Agents from loading all memory at once or skipping the index to read subdirectories directly.\"\n---\n\n> **Skill Alias**: When users mention `APM`, they refer to this skill: `APM-agent-progressive-memory`.\n> Agents installing this skill should record this alias mapping in MEMORY.md or AGENTS.md.\n\n# APM — Progressive Disclosure Protocol\n\nAPM supports **both group chat and private (main session DM)** memory management. The two structures are completely independent and do not interfere with each other.\n\nAgent must follow the **layered disclosure protocol** when accessing memory in group chats: read the index first, then load layers on demand.\n\n## Core Rules\n\n### 1. Entry Gate\n\n- The **only legal entry point** for group chat memory is `memory/groups/{group_name}.md` (index file)\n- **Forbidden**: directly reading any sub-files under `memory/groups/{group_name}/`\n- **Forbidden**: bypassing the index to directly `memory_search` subdirectories\n- **Group name mapping rule**: Matrix room IDs (e.g., `!xxx:matrix.example.com`) must first be resolved via `memory/group_names.json` to a friendly name `{group_name}` before use\n\n### 2. Five-Step Loading Flow\n\n| Step | Action | Output |\n|------|--------|--------|\n| 0. Group name mapping | Check `memory/group_names.json`, convert Matrix room ID to `{group_name}` | Friendly name |\n| 1. Route to index | `memory_get(\"memory/groups/{group_name}.md\")` | Hard Rules + routing table |\n| 2. Intent matching | Match current message to one trigger scenario in the index | File to load |\n| 3. Explicit load | `memory_get(\"memory/groups/{group_name}/{file}.md\")` | Actual memory content |\n| 4. Sub-layer control | Load only if Step 3 file references `conventions/` | 1 sub-file max |\n| 5. Budget circuit-breaker | Stop when cumulative tokens exceed `memory_budget` | Prompt user |\n\n> Step 0 is mandatory: every time entering group chat memory, **must resolve the group name first**, converting the Matrix room ID to a friendly name before file operations.\n> `group_names.json` format: `{room_id}: {name, display_name}`\n\nOnly **one** best-matching file is loaded per session (highest priority wins).\n\n### 3. Loading Discipline\n\n- Maximum **2 P0-P2 files + 1 P3 file** per session\n- `conventions/` files: only **1** at a time\n- When `attention.md` is marked `[ARCHIVED]`, only load `project.md`\n- When switching group chats, clear old context first, then restart from Step 1\n\n### 4. Write-Back on Updates\n\n- New decision → append to `experience.md`\n- Task status change → update `attention.md`\n- Index files: append-only (mark deleted entries `[DEPRECATED]` instead of removing)\n\n### 5. Auto-Initialization on Missing Memory\n\n> When a flush is triggered for a session (group or DM) whose memory system has **not yet been initialized**, the Agent must initialize it based on available information.\n\n\n**Trigger condition**: During `/remem`, Cron, or precompact flush, the Agent detects that the target group's index file (`memory/groups/{group_name}.md`) or the DM index file (`memory/main/index.md`) does not exist.\n\n**Initialization rules**:\n\n| Scenario | Condition | Action |\n|----------|-----------|--------|\n| Group chat index missing | `memory/groups/{group_name}.md` not found | Create index from `group_names.json` entry; scan conversation context for project name, participants, and topic; write Hard Rules + routing table |\n| Group sub-files missing | `memory/groups/{group_name}/` directory empty | Initialize with default attention.md + one blank project.md or experience.md based on context |\n| DM index missing | `memory/main/index.md` not found | Create from existing MEMORY.md content; distill key sections into routing index |\n\n**Initialization workflow**:\n1. **Detect**: Flush detects target index or sub-directory does not exist\n2. **Gather**: Extract project name, topic, participants from known sources (`group_names.json`, conversation context, MEMORY.md)\n3. **Create**: Write minimal viable index + first sub-file from gathered info\n4. **Flush**: Continue normal flush into the newly initialized structure\n5. **Report**: Inform user that a new memory system was initialized\n\n\n**Initialization is not overwriting**: existing files are never overwritten during init — only created when completely absent.\n\n## File Structure\n\n```\nmemory/groups/\n├── {group_name}.md          # L0: Entry gate + throttle (mandatory read)\n└── {group_name}/             # Group-private memory (direct access forbidden)\n    ├── attention.md          # P0: Current focus\n    ├── project.md            # P1: Project static info\n    ├── experience.md         # P2: Experience / decision log\n    ├── people.md             # P3: People profiles\n    └── conventions/          # L3: Detailed specifications\n        ├── api.md\n        ├── db.md\n        └── ...\n```\n\n> **Naming convention**: All files and directories use friendly names `{group_name}`. Matrix room IDs (e.g., `!xxx:matrix.example.com`) are **never** used directly. Use `memory/group_names.json` for ID → name mapping.\n\n## Priority Definitions\n\n| Priority | File | Content | When to Load |\n|----------|------|---------|--------------|\n| P0 | `attention.md` | Active tasks, blockers, environment snapshot | Any conversation related to current work |\n| P1 | `project.md` | Tech stack, architecture constraints, spec index | Technical decisions, architecture discussion, onboarding |\n| P2 | `experience.md` | Historical decisions, lessons learned, retrospectives | memory_search hit + append load |\n| P3 | `people.md` | Team roles, approval chains, contact info | When you need to find someone |\n\n## Anti-Pattern Quick Reference\n\n```\n❌ Load all index-referenced files at once        → ✅ Load only one at a time\n❌ Skip index, read sub-files directly            → ✅ Load index first\n❌ Load two group chats simultaneously             → ✅ Clear old, then reload from Step 1\n❌ Load full experience.md                        → ✅ Load fragments on search hit\n```\n\n---\n\n## Main Session (DM) Progressive Disclosure Layout\n\n> This section defines the progressive memory layout for **private chat (DM / main session)** scenarios.\n> Completely independent from the group chat system — the two structures do not interfere.\n\n### Design Principles\n\n1. **Non-destructive to original mechanism** — `MEMORY.md` stays in place, AGENTS.md still loads it directly\n2. **Survives skill uninstall** — All memory files exist independently in `memory/main/` and `MEMORY.md`, not dependent on the skill\n3. **Synergy with daily notes** — Daily notes are raw logs; `memory/main/` is the curated distillation layer\n4. **DM-exclusive structure** — Does not reuse `memory/groups/`, avoiding confusion with group chat memory\n\n### File Structure\n\n```\nmemory/main/                    # DM progressive disclosure (parallel to groups/)\n├── index.md                # L0: DM entry index (loaded first in every DM session)\n├── attention.md            # P0: Current tasks, blockers, environment snapshot\n├── longterm.md             # P1: Curated distillation of MEMORY.md (with original references)\n├── daily-synced.md         # P2: Flush-merged daily notes summary\n└── projects/               # P3: Project-level context\n    ├── NFP.md\n    ├── PanCpar.md\n    └── ...\n\nMEMORY.md                     # Original long-term memory (workspace root)\nmemory/YYYY-MM-DD.md          # Raw daily logs (memory/ directory)\n```\n\n### Relationship with AGENTS.md\n\n```\nAGENTS.md loading order (with APM installed):\n  SOUL.md → USER.md → MEMORY.md → daily notes\n                        ↑\n                   APM injects: for DM sessions, also loads\n                   memory/main/index.md → loads sub-files on demand\n\nAfter skill uninstall:\n  AGENTS.md still loads MEMORY.md + daily notes in original order, unaffected\n```\n\n### DM Entry Loading Rules\n\nWhen `chat_type === \"direct\"` (DM), **append** these steps to the AGENTS.md Every Session flow:\n\n```markdown\n## Every Session\n\n1. Read `SOUL.md` — this is who you are\n2. Read `USER.md` — this is who you're helping\n3. **If in MAIN SESSION** (DM): Load progressive disclosure index:\n   - Read `memory/main/index.md` — DM progressive disclosure index\n   - Based on index routing, load up to 2 P0-P2 files (attention.md / longterm.md / daily-synced.md / projects/)\n   - Report `上次 flush: YYYY-MM-DD HH:mm` to user (from `flush-state.json` → `main_session.last_flush_time`)\n4. Read `memory/YYYY-MM-DD.md` (today + yesterday) for recent context\n5. **If in MAIN SESSION** (DM): Also read `MEMORY.md` — original long-term memory (unchanged, APM does not modify it)\n```\n\n> 📌 **Installer note**: The steps above are manually added to AGENTS.md by the installer, or injected by the skill install script.\n> APM does NOT modify SOUL.md. It only appends DM progressive loading steps to AGENTS.md.\n\nFinal load budget: **full MEMORY.md + index.md + up to 2 P0-P2 sub-files**\n\n### DM Routing Index (index.md Template)\n\n```markdown\n---\ntype: main-session-index\nlast_updated: YYYY-MM-DD\nstatus: active\nmemory_budget: 8000\n---\n\n# Main Session Memory Index\n\n> This file is the **only entry point** for DM progressive disclosure.\n> Only used in private chat / main session contexts.\n> This file **references** but does **not copy** MEMORY.md content, preserving the original as authoritative.\n\n## Reference Declarations\n\n- **Authoritative long-term memory**: `MEMORY.md` (workspace root)\n- **Raw daily logs**: `memory/YYYY-MM-DD.md`\n- **This file's role**: Index + curated distillation + navigation\n\n## Routing Index\n\n| Trigger Scenario | Load File | Priority | Notes |\n|-----------------|-----------|----------|-------|\n| Current tasks, blockers | `attention.md` | P0 | Syncs with MEMORY.md current tasks |\n| MEMORY.md curated summary | `longterm.md` | P1 | Thematic summary with original reference links |\n| Daily notes summary | `daily-synced.md` | P2 | Flush-merged daily logs |\n| Project context | `projects/{name}.md` | P3 | Deep context per project |\n\n## Relationship with MEMORY.md\n\n> ⚠️ **MEMORY.md is the authoritative original. It stays completely unchanged.**\n> APM's `longterm.md` serves as MEMORY.md's **experience summary + detail supplement layer**:\n> - **Summary**: distill key entries from MEMORY.md into an index (format: topic → MEMORY.md location)\n> - **Supplement**: record details, context, and decision background not covered in MEMORY.md\n> - **Reference**: keep \"See MEMORY.md §X\" links for traceback to original\n>\n> After skill uninstall, `MEMORY.md` remains fully functional; `longterm.md` reference links become stale (harmless).\n\n## Last Flush Time\n\nSee `flush-state.json` → `main_session.last_flush_time`.\nAfter loading index.md, report to user: `上次 flush: YYYY-MM-DD HH:mm`\n```\n\n### attention.md (DM)\n\n```markdown\n# Main Session — Current Focus\n\n## Active Tasks\n\n| Task | Status | Notes |\n|------|--------|-------|\n| ... | ... | ... |\n\n## Blockers\n\n- ...\n\n## Environment Snapshot\n\n- Last session: YYYY-MM-DD\n- Pending items: N\n```\n\n### longterm.md (DM)\n\n```markdown\n# Long-Term Memory — Experience Summary\n\n> This file is MEMORY.md's **experience summary + detail supplement layer**.\n> MEMORY.md is the authoritative original; this file provides distilled index and context not recorded in MEMORY.md.\n\n## MEMORY.md Experience Index\n\n| Topic | MEMORY.md Location | Summary |\n|-------|-------------------|---------|\n| OpenClaw exec mechanism | §Technical Lessons | exec is ephemeral, nohup is persistent |\n| SFTP credentials | TOOLS.md (not in MEMORY) | PUMCH server 172.24.195.51:2022 |\n| PUMCH project structure | §Workspace Structure | /PROJ/PUMCH/USERS/bot/ |\n\n## Detail Supplements (not in MEMORY.md)\n\n| Entry | Detail | Source Date |\n|-------|--------|------------|\n| ... | ... | YYYY-MM-DD |\n\n## Decision Log\n\n- [YYYY-MM-DD] Decision: ... → MEMORY.md §... |\n```\n\n---\n\n## Index File Template\n\n```markdown\n---\ngroup_name: your-group    # From group_names.json mapping\nlast_updated: YYYY-MM-DD\nstatus: active\nmemory_budget: 6000\n---\n\n# {Group Name} — Progressive Disclosure Index\n\n> ⚠️ This file is the **only legal entry point** for accessing this group's memory.\n\n## Hard Rules\n\n- rule 1\n- rule 2\n\n## Routing Index\n\n| Trigger Scenario | Load File | Priority |\n|-----------------|-----------|----------|\n| Current tasks, Sprint, blockers | `attention.md` | P0 |\n| Tech stack, architecture constraints | `project.md` | P1 |\n| Historical decisions, lessons learned | `experience.md` | P2 |\n| Team roles, contacts | `people.md` | P3 |\n| API development details | `conventions/api.md` | P2-L3 |\n```\n\n---\n\n## 5. Memory Flush — Periodic Memory Sweep ⭐\n\n> Protocol rule 4 defines \"manual updates\". This extension defines **automatic periodic flushing**.\n\nProgressive disclosure solves \"what to read\". This extension solves \"when to write, what to write\".\n\n### 5.1 Flush Trigger Schedule\n\n| Priority | Trigger | Condition | Action |\n|----------|---------|-----------|--------|\n| P0 | **Hook: `/remem`** 🪝 | User sends `/remem` in any chat | 6-step complete flush: context detection → discover groups → compare old memory → update files → stamp timestamp → write flush-state |\n| P1 | **Cron scheduled** ⏰ | Daily at 06:17 and 18:17 Asia/Shanghai | Two scheduled flushes via cron job (see format below) |\n| P2 | **Manual trigger** ✋ | Agent detects important decision or status change | Immediately write back to memory files |\n| P3 | **Auto-flush on idle** ⏸ | Session idle 30min + no flush since last run | Automatic flush before session compaction (via precompact-remem hook) |\n\n> **Cron job format** (tested and working):\n```bash\nopenclaw cron add \\\n  --name \"APM Memory Flush\" \\\n  --cron \"17 10 * * *\" \\\n  --tz \"Asia/Hong_Kong\" \\\n  --session isolated \\\n  --announce \\\n  --to \"matrix:!{room_id}\" \\\n  --message \"/remem\" \\\n  --expect-final \\\n  --delete-after-run\n```\n- Schedule: `17 10 * * *` = 10:17 daily (UTC 02:17 = 10:17 CST-8)\n- Use Evening cron format: `--session isolated` + `--announce` + `--message /remem`\n\n> **Key design**: `/remem` fires **while the session is still active**, so the hook receives the full session context, not an empty state.\n\n### 5.1c Precompact-Remem Hook (Auto-flush on Idle)\n\nAvailable via `~/.openclaw/hooks/precompact-remem/`:\n\n| Item | Config |\n|------|--------|\n| Hook event | `session:compact:before` |\n| Trigger condition | Session idle 30min OR tokens ≥1000 |\n| Action | Automatic flush before context compaction |\n\n**Installation**:\n```bash\ncp -r hooks/precompact-remem/ ~/.openclaw/hooks/precompact-remem/\nopenclaw hooks enable precompact-remem\n```\n\nThis provides automatic P3 flush when:\n- Session has been idle for 30 minutes\n- No flush has been performed since last run\n- Session is about to be compacted (context will be lost)\n| Execution flow | 6 steps: context usage check → discover memory groups → read old memory for deltas → apply updates → stamp timestamp → write flush-state |\n\n### ⚠️ Why Not Use `/new` Hook?\n\nThe built-in `memory-flush` hook listens to `command:new` (i.e., `/new`), but there is a fundamental conflict:\n\n1. `/new`'s semantics are **creating a new session**\n2. When the hook fires on `/new`, the new session is already created, **old session context is already lost**\n3. The hook's `previousSessionEntry` may no longer be accessible after new session creation\n4. Result: hook fires but has nothing to flush, **command is silently swallowed**\n\n**Solution**: Custom `remem-flush` hook intercepts `/remem` at the message layer via `message:received`. The session is still active, full context is available.\n\n### 5.1b remem-flush Hook Installation\n\nHook files are packaged in the skill directory. Copy to OpenClaw hooks directory on install:\n\n```bash\n# Skill internal path (after install):\n# hooks/remem-flush/\n#   ├── HOOK.md       # Metadata + documentation\n#   └── handler.js    # Processing logic\n\n# Install command (from skill directory):\ncp -r hooks/remem-flush/ ~/.openclaw/hooks/remem-flush/\n```\n\n**Post-install structure:**\n```\n~/.openclaw/hooks/remem-flush/\n├── HOOK.md\n└── handler.js\n```\n\n**Note**: Built-in `memory-flush` hook must be disabled (`enabled: false`), otherwise `/new` will be intercepted by it and fail.\n\n### 5.1c precompact-remem Hook (Optional, Recommended)\n\n**Automatically** executes memory flush before session context compaction — no manual trigger needed:\n\n| Item | Config |\n|------|--------|\n| Hook event | `session:compact:before` |\n| Hook path | `~/.openclaw/hooks/precompact-remem/` |\n| Trigger condition | Session has ≥10 messages or ≥1000 tokens |\n\n```bash\n# Install:\ncp -r hooks/precompact-remem/ ~/.openclaw/hooks/precompact-remem/\n```\n\n**Enable after install:**\n```bash\nopenclaw hooks enable precompact-remem\n```\n\nThe two hooks complement each other:\n- `remem-flush` — user manually triggers with `/remem`\n- `precompact-remem` — **automatic** trigger before context compaction (recommended to enable)\n\n### 5.2 Flush Content Decisions\n\n#### ✅ Write This\n\n| Category | Target File | Decision Criteria |\n|----------|------------|-------------------|\n| Confirmed decision | `experience.md` | User explicitly agreed/confirmed, or action was taken |\n| Task status change | `attention.md` | in-progress → completed/blocked/changed |\n| New project agreement | `project.md` | Cross-confirmed by two separate messages |\n| Personnel role change | `people.md` | Explicit role assignment or change |\n| Environment/config change | `attention.md` | Server migration, port change, key rotation |\n| Lessons learned / fix record | `experience.md` | Complete record of problem + solution |\n\n#### ❌ Don't Write\n\n| Category | Reason |\n|----------|--------|\n| Small talk, greetings, daily banter | No informational value |\n| Opinion only, not yet landed | No decision formed |\n| Repeating existing content | Matches already-recorded entries |\n| Temporary exploratory discussion | Direction undecided, may change |\n\n### 5.3 Write-Back Rules\n\n**Group chat scenarios** (`memory/groups/{group}/`):\n- **`experience.md`**: append-only, reverse chronological, each entry has `YYYY-MM-DD`, context, decision, action\n- **`attention.md`**: overwrite old state (task progress is factual, not a log)\n- **`project.md`, `people.md`**: primarily append; deletions require explicit confirmation\n- **`group_names.json`**: new members or role changes may be appended; no destructive updates\n\n**DM scenarios** (`memory/main/`):\n- **`longterm.md`**: each flush, distill MEMORY.md update content into index entries with original location references\n- **`attention.md`**: overwrite-update current tasks/blockers\n- **`daily-synced.md`**: flush-merged daily notes summary (append-only)\n- **`projects/{name}.md`**: supplement project context on demand\n- **`MEMORY.md`**: **do not touch** — remains the authoritative original\n\n### 5.4 Flush State File\n\n`memory/flush-state.json` tracks flush state. **Group and DM flush tracking are completely independent**:\n\n```json\n{\n  \"groups\": {\n    \"last_flush_time\": \"2026-05-15T07:30:00+08:00\",\n    \"attention_last_updated\": \"2026-05-15T07:00:00+08:00\",\n    \"experience_last_appended\": \"2026-05-15T06:00:00+08:00\",\n    \"session_id\": \"last-group-session-id\"\n  },\n  \"main_session\": {\n    \"last_flush_time\": \"2026-05-15T07:30:00+08:00\",\n    \"longterm_last_synced\": \"2026-05-15T07:30:00+08:00\",\n    \"attention_last_updated\": \"2026-05-15T07:00:00+08:00\",\n    \"session_id\": \"last-main-session-id\"\n  },\n  \"context_usage_at_flush\": 45,\n  \"pending_items\": [\"Confirm Zhang San is the new PM\"]\n}\n```\n\nUsage rules:\n- **`groups`** and **`main_session`** are completely independent flush tracking blocks\n- Group chat flush only updates `groups.*` fields\n- DM flush only updates `main_session.*` fields\n- `pending_items` is shared; items pending confirmation are cross-scenario\n- After skill uninstall, `main_session` section of `flush-state.json` becomes stale (harmless); `groups` section remains unaffected\n\n### 5.5 Integration with Progressive Disclosure\n\n```\n        Read: Progressive Disclosure           Write: Memory Flush\n              ↓                                      ↓\n        Index → Load on demand              Session deltas → Write to files\n              ↓                                      ↓\n         Save tokens + precise reading       No info loss + automatic maintenance\n              ↓                                      ↓\n              └── Complete memory loop ←─────────────┘\n```\n\nAfter loading a file, report the file's last flush time to the user (e.g., `attention.md last updated: 2026-05-14, current session has 2 task status changes pending flush`)\n\n## Complete Protocol Checklist\n\n1. **Entry gate** — index is the only entry, no direct subdirectory access\n2. **Five-step loading flow** — group name mapping → route to index → intent match → explicit load → sub-layer control → budget circuit-breaker\n3. **Loading discipline** — 2+1 file limit, clear on group switch\n4. **Manual write-back** — immediately write back new decisions/status changes\n5. **Memory Flush** — `/remem` trigger (recommended) + Cron (tested format: Evening cron style: --session isolated + --announce + --message /remem)\n6. **Auto-Flush** — `precompact-remem` hook fires before session compaction\n7. **DM Progressive Disclosure** — main session DM uses independent layout (`memory/main/`), completely independent from group chats; MEMORY.md still loads normally after skill uninstall\n8. **Auto-Initialization** — during any flush, if target memory system is absent, initialize it from known info before flushing\n\nFile v1.4.2:_meta.json\n\n{\n  \"ownerId\": \"kn7dz0are44vk4ct393b9kxe4n8209wv\",\n  \"slug\": \"apm-agent-progressive-memory\",\n  \"version\": \"1.4.2\",\n  \"publishedAt\": 1779166208443\n}\n\nFile v1.4.2:hooks/precompact-remem/HOOK.md\n\n---\nname: precompact-remem\ndescription: \"Before session context compaction, trigger a memory flush to preserve current session memory.\"\nevents:\n  - session:compact:before\nrequires:\n  config:\n    - workspace.dir\ninstall:\n  - id: precompact-remem-hook\n    kind: local\n    label: \"Pre-Compaction Memory Flush\"\n---\n\n# precompact-remem Hook\n\nIntercepts `session:compact:before` event and runs a 6-step memory flush\nto preserve the current session's context before it gets summarized away.\n\n## Behavior\n\n1. Detect session context (message count, token count)\n2. Discover active memory groups\n3. Read old memory timestamps from flush-state\n4. Compute deltas (changed files since last flush)\n5. Update memory files with session context\n6. Stamp flush-state timestamp\n\n## Events\n\n- `session:compact:before` — fires just before OpenClaw compacts the transcript\n\n## Notes\n\n- This hook complements `remem-flush` which responds to `/remem` commands.\n- `precompact-remem` handles the automatic case: session is being compacted,\n  flush now so no context is lost.\n- Both hooks share the same flush logic and flush-state file.\n\nFile v1.4.2:hooks/remem-flush/HOOK.md\n\n---\nname: remem-flush\ndescription: \"Memory flush hook for /remem command. Triggers 6-step memory flush when user sends /remem in any chat.\"\nevents:\n  - message:received\nrequires:\n  config:\n    - workspace.dir\ninstall:\n  - id: remem-flush-hook\n    kind: local\n    label: \"Memory Flush Hook\"\n---\n\n# remem-flush Hook\n\nIntercept `/remem` messages and trigger a 6-step memory flush.\n\n## Events\n\n- `message:received` — listens for `/remem` command\n\n## Behavior\n\n1. Intercept messages matching `/remem` or `/remem <args>`\n2. Extract session context\n3. Detect active memory groups\n4. Compare with old memory for deltas\n5. Update memory files\n6. Stamp flush-state timestamp\n7. Return control to AI for confirmation reply\n\n## Files Modified\n\n- `memory/flush-state.json` — updated on each flush\n- `memory/groups/{group}/*.md` — updated based on deltas\n\nArchive v1.4.1: 6 files, 12849 bytes\n\nFiles: _meta.json (147b), hooks/precompact-remem/handler.js (4369b), hooks/precompact-remem/HOOK.md (1113b), hooks/remem-flush/handler.js (4829b), hooks/remem-flush/HOOK.md (847b), SKILL.md (17969b)\n\nFile v1.4.1:SKILL.md\n\n---\nname: APM-agent-progressive-memory\ndescription: \"APM 协议（Agent Progressive Memory）：群聊渐进式记忆披露协议。当 Agent 需要在群聊/团队/项目协作场景中访问历史记忆时启用。避免 Agent 一次性加载所有记忆或跳过索引直接读子目录。\"\n---\n\n> **Skill Alias**: 当用户提及 `APM` 时，即指本 skill `APM-agent-progressive-memory`。\n> 安装本 skill 的 Agent 应在 MEMORY.md 或 AGENTS.md 中记录此别名映射。\n\n# APM — 渐进式披露协议\n\nAPM 同时支持**群聊**和**私聊（主会话 DM）**两种场景的记忆管理，两套结构完全独立，互不干扰。\n\nAgent 在群聊中访问记忆时必须遵守的**分层披露协议**：先读索引，再按需逐层加载。\n\n## 核心规则\n\n### 1. 入口管制\n- 群聊记忆的唯一入口是 `memory/groups/{group_name}.md`（索引文件）\n- **禁止**直接读取 `memory/groups/{group_name}/` 下的任何子文件\n- 禁止绕过索引直接 `memory_search` 子目录\n- **群名映射规则**：Matrix room ID（如 `!xxx:matrix.example.com`）需先查 `memory/group_names.json` 映射为友好名称 `{group_name}` 后再用\n\n### 2. 五步加载流程\n\n| 步骤 | 动作 | 产出 |\n|------|------|------|\n| 0. 群名映射 | 查 `memory/group_names.json`，将 Matrix room ID 转为 `{group_name}` | 友好名称 |\n| 1. 路由定位 | `memory_get(\"memory/groups/{group_name}.md\")` | Hard Rules + 路由索引表 |\n| 2. 意图匹配 | 匹配当前消息到索引表中一个触发场景 | 确定要加载的文件 |\n| 3. 显式加载 | `memory_get(\"memory/groups/{group_name}/{文件}.md\")` | 实际记忆内容 |\n| 4. 子层控制 | 仅当 Step 3 文件引用了 `conventions/` 时才加载 | 1 个子文件 |\n| 5. 预算熔断 | 累计超过 `memory_budget` 时停止，提示用户 | 预算保护 |\n\n> Step 0 是新增步骤：每次进入群聊记忆时，**必须先执行群名映射**，将 Matrix 原始 room ID 转为友好名称，再进行后续文件操作。\n> 群名映射文件 `group_names.json` 格式：`{room_id}: {name, display_name}`\n\n每次只匹配**一个**最匹配的文件（优先级最高）。\n\n### 3. 加载纪律\n- 单会话最多 **2 个 P0-P2 文件 + 1 个 P3 文件**\n- `conventions/` 一次只加载 **1 个**\n- `attention.md` 标记「已归档」时，只加载 `project.md`\n- 切换群聊时先清理旧上下文，再重新走 Step 1\n\n### 4. 更新回写\n- 新决策 → 追加 `experience.md`\n- 任务状态变化 → 更新 `attention.md`\n- 索引文件只增不删（删除时标记 `[DEPRECATED]`）\n\n## 文件结构\n\n```\nmemory/groups/\n├── {group_name}.md          # L0: 入口+阀门（必读）\n└── {group_name}/            # 群聊私有记忆（禁止直接访问）\n    ├── attention.md       # P0: 当前聚焦\n    ├── project.md         # P1: 项目静态信息\n    ├── experience.md      # P2: 经验/决策日志\n    ├── people.md         # P3: 人员画像\n    └── conventions/       # L3: 细分规范\n        ├── api.md\n        ├── db.md\n        └── ...\n```\n\n> **命名规范**：所有文件和目录一律使用友好名称 `{group_name}`，禁止直接使用 Matrix room ID（如 `!xxx:matrix.example.com`）。通过 `memory/group_names.json` 做 ID → 名称映射。\n\n## 优先级定义\n\n| 优先级 | 文件 | 内容 | 加载时机 |\n|--------|------|------|----------|\n| P0 | `attention.md` | 活跃任务、阻断项、环境快照 | 任何与当前工作相关的对话 |\n| P1 | `project.md` | 技术栈、架构约束、规范索引 | 技术选型、架构讨论、新人 onboarding |\n| P2 | `experience.md` | 历史决策、踩坑记录、复盘 | memory_search 命中后追加加载 |\n| P3 | `people.md` | 人员角色、审批流程、联系方式 | 需要找人的时候 |\n\n## 反模式速查\n\n```\n❌ 一次加载索引所有引用文件     → ✅ 每次只加载一个\n❌ 跳过索引直接读子文件         → ✅ 先加载索引\n❌ 同时加载两个群聊            → ✅ 切换时清理再重载\n❌ 全文加载 experience.md      → ✅ 搜索命中后片段加载\n```\n\n## 主会话（DM）渐进披露布局\n\n> 本节规定**私聊主会话**（DM）场景下的渐进式记忆布局。\n> 与群聊系统**完全独立**，两套结构互不干扰。\n\n### 设计原则\n\n1. **不破坏原机制** — `MEMORY.md` 位置不变，AGENTS.md 仍直接加载它\n2. **skill 卸载后仍可读** — 所有记忆文件独立存在于 `memory/main/` 和 `MEMORY.md`，不依赖 skill 存在\n3. **与 daily notes 协同** — daily notes 是原始日志，`memory/main/` 是精选提炼层\n4. **DM 专属结构** — 不复用 `memory/groups/`，避免与群聊记忆混淆\n\n### 文件结构\n\n```\nmemory/main/                      # DM 渐进披露专用（与 groups/ 平级）\n├── index.md                    # L0: DM 入口索引（每次 DM 会话优先加载）\n├── attention.md               # P0: 当前任务、阻断项、环境快照\n├── longterm.md                # P1: MEMORY.md 的精选提炼版（保留原始引用）\n├── daily-synced.md            # P2: 已冲刷的 daily notes 摘要合并\n└── projects/                  # P3: 项目级上下文\n    ├── NFP.md\n    ├── PanCpar.md\n    └── ...\n\nMEMORY.md                        # 原版长期记忆（位于 workspace 根目录）\nmemory/YYYY-MM-DD.md           # 原始 daily 日志（位于 memory/ 目录）\n```\n\n### 与 AGENTS.md 的关系\n\n```\nAGENTS.md 加载顺序（APM 安装后）：\n  SOUL.md → USER.md → MEMORY.md → daily notes\n                        ↑\n                   APM 插入：DM 时额外加载\n                   memory/main/index.md → 按需加载子文件\n\nskill 卸载后：\n  AGENTS.md 仍按原顺序加载 MEMORY.md + daily notes，完全不受影响\n```\n\n### 入口加载规则（DM 场景）\n\n当 `chat_type === \"direct\"`（私聊 DM）时，在 AGENTS.md 的 Every Session 流程中**追加**以下步骤：\n\n```markdown\n## Every Session\n\n1. Read `SOUL.md` — this is who you are\n2. Read `USER.md` — this is who you're helping\n3. **If in MAIN SESSION** (DM): Load progressive disclosure index:\n   - Read `memory/main/index.md` — DM entry index with routing table\n   - Based on index routing, load up to 2 P0-P2 files (attention.md / longterm.md / projects/)\n   - Report `上次 flush: YYYY-MM-DD HH:mm` to user\n4. Read `memory/YYYY-MM-DD.md` (today + yesterday) for recent context\n5. **If in MAIN SESSION** (DM): Also read `MEMORY.md` — original long-term memory (unchanged)\n```\n\n> 📌 **安装须知**：以上步骤由 skill 安装者在 AGENTS.md 中手动添加，或由 skill 安装脚本自动注入。\n> APM 不修改 SOUL.md，仅在 AGENTS.md 中追加 DM 渐进加载步骤。\n\n最终加载量：**MEMORY.md 完整 + index.md + 最多 2 个 P0-P2 子文件**\n\n### DM 路由索引（index.md 内容模板）\n\n```markdown\n---\ntype: main-session-index\nlast_updated: YYYY-MM-DD\nstatus: active\nmemory_budget: 8000\n---\n\n# 主会话记忆索引\n\n> 本文件是 DM 渐进披露的**唯一入口**，仅在私聊主会话中使用。\n> 本文件**引用**而非**复制** MEMORY.md 内容，保留原始文件的权威性。\n\n## 引用声明\n\n- **长期记忆权威版本**：`MEMORY.md`（workspace 根目录）\n- **每日日志原始版本**：`memory/YYYY-MM-DD.md`\n- **本文件角色**：索引 + 精选提炼 + 导航\n\n## 路由索引\n\n| 触发场景 | 加载文件 | 优先级 | 说明 |\n|---------|---------|--------|------|\n| 当前任务、阻断项 | `attention.md` | P0 | 与 MEMORY.md 中的当前任务联动 |\n| MEMORY.md 精炼引用 | `longterm.md` | P1 | MEMORY.md 的分主题摘要，保留原始引用链接 |\n| 每日日志摘要 | `daily-synced.md` | P2 | 已冲刷的 daily notes 合并 |\n| 项目上下文 | `projects/{name}.md` | P3 | 各项目的深度上下文 |\n\n## 与 MEMORY.md 的关系\n\n> ⚠️ **MEMORY.md 是原版长期记忆，保持完全不变。**\n> APM 的 `longterm.md` 是 MEMORY.md 的**经验总结 + 细节补充层**：\n> - **总结**：将 MEMORY.md 的关键条目提炼为索引（格式：主题 → MEMORY.md 位置）\n> - **补充**：在 MEMORY.md 未展开的细节、上下文、决策背景，在 `longterm.md` 中补充记录\n> - **引用**：保留「原始内容见 MEMORY.md §X」链接，方便回溯原文\n>\n> skill 卸载后，`MEMORY.md` 仍然完整可用，`longterm.md` 引用链失效（无影响）。\n\n## 最后冲刷时间\n\n- `flush-state.json` 中的 `main_session_last_flush` 记录本索引的冲刷时间\n- 每次加载 index.md 后，向用户说明：`上次 flush: YYYY-MM-DD HH:mm`\n```\n\n### attention.md（DM 专用）\n\n```markdown\n# 主会话当前聚焦\n\n## 活跃任务\n\n| 任务 | 状态 | 备注 |\n|------|------|------|\n| ... | ... | ... |\n\n## 阻断项\n\n- ...\n\n## 环境快照\n\n- 最新 session: YYYY-MM-DD\n- 待处理事项: N 项\n```\n\n### longterm.md（DM 专用）\n\n```markdown\n# 长期记忆经验总结\n\n> 本文件是 MEMORY.md 的**经验总结 + 细节补充层**。\n> MEMORY.md 是权威原版，本文件提供提炼索引和未载入 MEMORY.md 的上下文细节。\n\n## MEMORY.md 经验索引\n\n| 主题 | MEMORY.md 位置 | 提炼摘要 |\n|------|--------------|---------|\n| OpenClaw exec 机制 | MEMORY.md §Technical Lessons | exec是临时的，nohup才是持久的 |\n| SFTP 凭据 | TOOLS.md（不在MEMORY） | PUMCH服务器172.24.195.51:2022 |\n| PUMCH 项目结构 | MEMORY.md §Workspace | /PROJ/PUMCH/USERS/bot/ |\n\n## 细节补充（MEMORY.md 未记录）\n\n| 条目 | 细节内容 | 来源日期 |\n|------|---------|---------|\n| ... | ... | YYYY-MM-DD |\n\n## 决策日志\n\n- [YYYY-MM-DD] 决策: ... → MEMORY.md §... |\n```\n\n---\n\n## 索引文件模板\n\n```markdown\n---\ngroup_name: your-group    # 来自 group_names.json 的映射名称\nlast_updated: YYYY-MM-DD\nstatus: active\nmemory_budget: 6000\n---\n\n# {Group Name} — 渐进式披露索引\n\n> ⚠️ 本文件是访问此群聊记忆的**唯一合法入口**。\n\n## Hard Rules\n\n- 规则1\n- 规则2\n\n## 路由索引\n\n| 触发场景 | 加载文件 | 优先级 |\n|---------|---------|--------|\n| 当前任务、Sprint、阻断项 | `attention.md` | P0 |\n| 技术栈、架构约束 | `project.md` | P1 |\n| 历史决策、踩坑记录 | `experience.md` | P2 |\n| 人员分工、联系方式 | `people.md` | P3 |\n| API 开发细节 | `conventions/api.md` | P2-L3 |\n```\n\n---\n\n## 5. Memory Flush — 周期性记忆冲刷 ⭐\n\n> 本协议的第四条规定了\"手动更新\"，本扩展规定了**自动周期性冲刷**。\n\n渐进式披露解决了\"读什么\"，这个扩展解决\"什么时候写、写什么\"。\n\n### 5.1 冲刷触发时序\n\n| 优先级 | 触发器 | 触发条件 | 动作 |\n|--------|--------|---------|------|\n\n\nArchive v1.4.0: 6 files, 12143 bytes\n\nFiles: _meta.json (147b), hooks/precompact-remem/handler.js (4369b), hooks/precompact-remem/HOOK.md (1113b), hooks/remem-flush/handler.js (4829b), hooks/remem-flush/HOOK.md (847b), SKILL.md (15958b)\n\nArchive v1.3.2: 6 files, 10385 bytes\n\nFiles: _meta.json (147b), hooks/precompact-remem/handler.js (4369b), hooks/precompact-remem/HOOK.md (1113b), hooks/remem-flush/handler.js (4829b), hooks/remem-flush/HOOK.md (847b), SKILL.md (11092b)\n\nArchive v1.3.1: 6 files, 10290 bytes\n\nFiles: _meta.json (147b), hooks/precompact-remem/handler.js (4369b), hooks/precompact-remem/HOOK.md (1113b), hooks/remem-flush/handler.js (4829b), hooks/remem-flush/HOOK.md (847b), SKILL.md (10910b)\n\nArchive v1.3.0: 6 files, 10296 bytes\n\nFiles: _meta.json (147b), hooks/precompact-remem/handler.js (4369b), hooks/precompact-remem/HOOK.md (1113b), hooks/remem-flush/handler.js (4829b), hooks/remem-flush/HOOK.md (847b), SKILL.md (10896b)","readmeExcerpt":"Skill: Apm Agent Progressive Memory Owner: biociao Summary: APM Protocol (Agent Progressive Memory): Progressive disclosure protocol for group chat AND DM (main session) memory. Tags: latest:1.6.1 Version history: v1.6.1 | 2026-06-20T16:25:14.508Z | user **Summary:** Introduced dedicated session start hook and improved group name mapping. - Added new apm_session_start hook for memory initialization and entry handling","codeSnippets":[],"executableExamples":[{"language":"text","snippet":"memory/groups/\n├── {group_name}.md          # L0: Entry gate (mandatory read)\n└── {group_name}/             # Group memory (direct access forbidden)\n    ├── attention.md          # P0: Current focus\n    ├── project.md            # P1: Project static info\n    ├── experience.md         # P2: Experience / decision log\n    ├── people.md             # P3: People profiles\n    └── conventions/          # L3: Detailed specifications\n        ├── api.md\n        └── ...\n\nmemory/main/                    # DM progressive disclosure\n├── index.md                # L0: DM entry index\n├── attention.md            # P0: Current tasks, blockers\n├── longterm.md             # P1: MEMORY.md distilled summary\n├── daily-synced.md         # P2: Daily notes summary\n└── projects/               # P3: Project context\n    └── {name}.md"},{"language":"text","snippet":"❌ 95 lines of \"long-term memory\" with project details\n❌ Tool lists that `which` can answer\n❌ Temporary fix notes lingering in MEMORY.md a month later\n❌ Group names listed directly\n❌ Event outcomes with specific samples or measurements\n\n✅ 30-line identity + index\n✅ Project index table → projects/{name}.md\n✅ Key events → daily notes + longterm index\n✅ Group chats → memory/groups/{name}.md"},{"language":"markdown","snippet":"## Every Session\n\n1. Read `SOUL.md` → USER.md → MEMORY.md\n2. **If in MAIN SESSION** (DM):\n   - Read `memory/main/index.md` — DM progressive index\n   - Based on routing, load up to 2 files\n   - Report `last flush: YYYY-MM-DD HH:mm` (from `memory/flush-state.json` — DM-only)\n3. Read `memory/YYYY-MM-DD.md` (today + yesterday)"},{"language":"json","snippet":"{\n  \"last_flush_time\": \"2026-06-20T17:20:23+08:00\",\n  \"flush_number\": 6,\n  \"context_usage_at_flush\": null,\n  \"pending_items\": [],\n  \"<file>_mtime\": \"ISO-8601\"  \n}"},{"language":"text","snippet":"❌ Load all at once        → ✅ Load only one at a time\n❌ Skip index           → ✅ Read index first\n❌ Load two groups      → ✅ Clear old, reload from Step 1"},{"language":"markdown","snippet":"# MEMORY.md — Long-term Memory (Authoritative Source)\n\n> ⚠️ This file only stores **high-level identity + index**.\n> Project details go to `memory/main/projects/`.\n> Event logs go to `memory/YYYY-MM-DD.md`.\n\n## Identity\n- **Me**: {agent name}, {role}, {style}\n- **Principles**: {3-5 max}\n\n## User\n- **Name**: {user name} / {aliases}\n- **Timezone**: {tz}\n- **Stack**: {languages/tools}\n\n## Servers\n- **Host**: {hostname}\n- **Access**: {ssh/sftp url}\n\n## Key Databases\n- **{db name}**: {path}\n\n## Project Index (see `memory/main/projects/`)\n\n| Project | Path | Detail File |\n|---------|------|-------------|\n| {name} | {path} | `projects/{name}.md` |\n| ... | ... | ... |\n\n## Other Memory Entries\n- Current tasks: `memory/main/attention.md`\n- Experience index: `memory/main/longterm.md`\n- Daily logs: `memory/YYYY-MM-DD.md`\n- Group chats: `memory/groups/` (APM 5-step)\n- DVC / data: {path}"}],"parameters":null,"dependencies":[],"permissions":[],"extractedFiles":[{"path":"SKILL.md","content":"---\nname: APM-agent-progressive-memory\ndescription: \"APM Protocol (Agent Progressive Memory): Progressive disclosure protocol for group chat AND DM (main session) memory.\"\n---\n\n# APM — Progressive Disclosure Protocol\n\nAPM supports **both group chat and private (main session DM)** memory management. The two structures are completely independent and do not interfere with each other.\n\n## Group vs DM: Strategy Comparison\n\n| Aspect | Group Chat | DM (Main Session) |\n|-------|-----------|-------------------|\n| **Memory path** | `memory/groups/{group_name}/` | `memory/main/` |\n| **Loading** | 5-step progressive (index → P0 → P1 → P2 → P3) | 3-layer progressive (index → attention → longterm) |\n| **Index file** | `memory/groups/{group_name}.md` | `memory/main/index.md` |\n| **Priority files** | attention.md, project.md, experience.md, people.md | attention.md, longterm.md |\n| **Entry rule** | Must read index first, no subdirectory bypass | Must read index first |\n| **Flush trigger** | Per-group flush on `/remem` | Full-session flush on `/remem` |\n\n**Key differences**:\n- Group uses **5-step loading** with budget controls; DM uses simpler **3-layer**\n- Group has **conventions/** sub-directory; DM does not\n- DM reuses existing **MEMORY.md**; Group uses dedicated files\n- Uninstaller: Group loses memory access; DM retains MEMORY.md\n\nAgent must follow the **layered disclosure protocol** when accessing memory in group chats: read the index first, then load layers on demand.\n\n## Core Rules\n\n### 1. Entry Gate\n\n- The **only legal entry point** for group chat memory is `memory/groups/{group_name}.md` (index file)\n- **Forbidden**: directly reading any sub-files under `memory/groups/{group_name}/`\n- **Forbidden**: bypassing the index to directly `memory_search` subdirectories\n- **Group name mapping rule**: group chat room IDs must first be resolved via `memory/groups/group_names.json` to a friendly name `{group_name}` before use\n\n### 2. Five-Step Loading Flow\n\n| Step | Action | Output |\n|------|--------|--------|\n| 0. Group name mapping | Check `memory/groups/group_names.json`, convert room ID to `{group_name}` | Friendly name |\n| 1. Route to index | `memory_get(\"memory/groups/{group_name}.md\")` | Hard Rules + routing table |\n| 2. Intent matching | Match current message to trigger scenario | File to load |\n| 3. Explicit load | `memory_get(\"memory/groups/{group_name}/{file}.md\")` | Actual memory content |\n| 4. Sub-layer control | Load only if Step 3 file references `conventions/` | 1 sub-file max |\n| 5. Budget circuit-breaker | Stop when cumulative tokens exceed `memory_budget` | Stop loading |\n\nOnly **one** best-matching file is loaded per session (highest priority wins).\n\n### 3. Loading Discipline\n\n- **Per group chat (5-step flow)**:\n  - Step 3 loads **1 P-file** (highest-priority match) per session\n  - Step 4 may load **1 sub-file** under `conventions/` (only if Step 3 referenced it)\n  - **Total ceiling**: 2 P0–P2 files + 1 P3 file (per AGENTS.md layering)\n- **Per DM"},{"path":"_meta.json","content":"{\n  \"ownerId\": \"kn7dz0are44vk4ct393b9kxe4n8209wv\",\n  \"slug\": \"apm-agent-progressive-memory\",\n  \"version\": \"1.6.1\",\n  \"publishedAt\": 1781972714508\n}"},{"path":"ADDENDUM.md","content":"# APM — ADDENDUM (Technical Details)\n\n## File Templates (v1.6.0)\n\n### MEMORY.md Template (lean, ≤ 50 lines)\n\n```markdown\n# MEMORY.md — Long-term Memory (Authoritative Source)\n\n> ⚠️ This file only stores **high-level identity + index**.\n> Project details go to `memory/main/projects/`.\n> Event logs go to `memory/YYYY-MM-DD.md`.\n\n## Identity\n- **Me**: {agent name}, {role}, {style}\n- **Principles**: {3-5 max}\n\n## User\n- **Name**: {user name} / {aliases}\n- **Timezone**: {tz}\n- **Stack**: {languages/tools}\n\n## Servers\n- **Host**: {hostname}\n- **Access**: {ssh/sftp url}\n\n## Key Databases\n- **{db name}**: {path}\n\n## Project Index (see `memory/main/projects/`)\n\n| Project | Path | Detail File |\n|---------|------|-------------|\n| {name} | {path} | `projects/{name}.md` |\n| ... | ... | ... |\n\n## Other Memory Entries\n- Current tasks: `memory/main/attention.md`\n- Experience index: `memory/main/longterm.md`\n- Daily logs: `memory/YYYY-MM-DD.md`\n- Group chats: `memory/groups/` (APM 5-step)\n- DVC / data: {path}\n```\n\n### projects/{name}.md Template\n\n```markdown\n# {Project Name}\n\n**Status**: {one-line state, e.g. \"Stage3 analysis, batch1 138/140 done\"}\n\n## Project Info\n- **Path**: {absolute path}\n- **Description**: {one-liner}\n- **Group**: {group chat name, if any}\n\n## Progress / Milestones\n- ✅ {milestone 1}\n- ✅ {milestone 2}\n- ⏳ {current}\n\n## Key Findings / Notes\n- {decision, gotcha, or constraint}\n\n## References\n- Source repo: {path}\n- Data storage: {path}\n- Project report: {path}\n\n## See Also\n- `memory/main/attention.md` (current task tracking)\n```\n\n### longterm.md Template (DM experience index)\n\n```markdown\n# Long-term Memory (APM DM Summary)\n\n> Experience index layer for MEMORY.md.\n> Project details → `memory/main/projects/{name}.md`.\n> Current tasks → `memory/main/attention.md`.\n\n## Project Status Index\n\n| Project | Detail File | Current Stage |\n|---------|-------------|---------------|\n| {name} | `projects/{name}.md` | {stage} |\n\n## Key Events Index\n\n| Event | Date | Location |\n|-------|------|----------|\n| {event} | YYYY-MM-DD | {file path} |\n\n## Server Resources\n- Host: {hostname}\n- DVC: {path}\n- Key DBs: {path list}\n```\n\n## Group Index File Template\n\n```markdown\n---\ngroup_name: {group_name}\nlast_updated: YYYY-MM-DD\nstatus: active\nmemory_budget: 6000\n---\n\n# {Group Name} — Progressive Disclosure Index\n\n> ⚠️ This file is the **only legal entry point** for accessing this group's memory.\n\n## Hard Rules\n\n- rule 1\n- rule 2\n\n## Routing Index\n\n| Trigger Scenario | Load File | Priority |\n|-----------------|-----------|----------|\n| Current tasks, Sprint, blockers | `attention.md` | P0 |\n| Tech stack, architecture constraints | `project.md` | P1 |\n| Historical decisions, lessons learned | `experience.md` | P2 |\n| Team roles, contacts | `people.md` | P3 |\n| API development details | `conventions/api.md` | P2-L3 |\n```\n\n## DM Index File Template\n\n```markdown\n---\ntype: main-session-index\nlast_updated: YYYY-MM-DD\nstatus: active\nmemory_budget: 8000\n---\n\n# Main Session Memor"},{"path":"CHANGELOG.md","content":"# APM Skill — Changelog\n\n## 1.6.0 (2026-06-20)\n\n### Added\n\n- **New hook**: `apm_session_start` — auto-injects APM context per chat\n  type on every agent run.\n  - Chat-type aware: DM gets `APM_SESSION_START.md`; groups get\n    `APM_GROUP_SESSION_START.md` with privacy gate.\n  - Channel-agnostic sessionKey parsing (Matrix / Telegram / Slack / Discord).\n  - Group-name resolution via `memory/groups/group_names.json` (full\n    key match + Matrix-specific room-only fallback).\n  - Idempotent per session (cached via `bootstrapFiles`).\n- **New chapter in SKILL.md**: `MEMORY.md Discipline` — explicit\n  allowed/forbidden rules for what belongs in `MEMORY.md` vs other\n  memory layers.\n- **New chapter in SKILL.md**: `MEMORY.md Audit Checklist` — quick\n  mental check whenever editing `MEMORY.md`.\n- **New chapter in ADDENDUM.md**: `File Templates` — three canonical\n  templates: `MEMORY.md` (lean, ≤ 50 lines), `projects/{name}.md`,\n  `longterm.md` (experience index).\n- **New chapter in ADDENDUM.md**: `MEMORY.md Size Audit` — line-count\n  rating table and a quick-extract script (grep) for finding\n  bloat candidates.\n- **New chapter in HOOKS.md**: `Hook Interaction` flow diagram and\n  shared conventions (mtime-based deltas, idempotency, flush-state shape).\n- **Shipped hook code**: `hooks/apm_session_start/{HOOK.md,handler.js}`\n  in this skill (operators can `cp -r` to install).\n- **Shipped hook code**: synced `hooks/remem-flush/` and\n  `hooks/precompact-remem/` from deployed state (catch up to current\n  `~/.openclaw/hooks/` versions).\n- **CHANGELOG.md** — this file.\n\n### Changed\n\n- `SKILL.md` — added new chapters; existing content unchanged.\n- `ADDENDUM.md` — added new templates and audit section; existing\n  content unchanged.\n- `HOOKS.md` — restructured as pure overview + links (was duplicating\n  per-hook content); install instructions consolidated.\n- `_meta.json` — version bumped 1.5.0 → 1.6.0.\n\n### Privacy / Channel Improvements\n\n- All skill documentation **stripped of personal references** (agent\n  name, project names, server paths, specific room IDs).\n- `apm_session_start` hook explicitly documents channel support matrix\n  (Matrix primary, others compatible) and Matrix-specific fallbacks\n  (room-only key match) are noted as such.\n- All non-English references in `apm_session_start` translated\n  to English (e.g. \"Progressive Disclosure Protocol\",\n  \"Entry Gate\", \"First-Join Flow\") to keep the skill monolingual.\n\n### Known Limitations (unchanged)\n\n- `MEMORY.md` is still injected by OpenClaw as a workspace bootstrap\n  file in group sessions; the privacy gate is enforced by agent\n  discipline until OpenClaw adds filtering.\n- `chatType === 'unknown'` falls back to DM protocol + warning.\n\n## 1.5.0 (2026-05-19)\n\n- Initial published version.\n- Two hooks: `remem-flush`, `precompact-remem`.\n- Group 5-step + DM 3-layer loading protocol.\n- File templates in ADDENDUM.md (group index, attention, experience).\n\n---\n\n## Versioning\n\n- **Major** (1.x → 2.x) — breaking protocol c"},{"path":"HOOKS.md","content":"# APM — Hooks Overview\n\nThis skill ships **three OpenClaw hooks** that automate the APM memory\nlifecycle. Each hook has its own `HOOK.md` with full details; this file is\nthe entry point and contains only the overview, shared conventions, and\ninstallation instructions.\n\n## Hook Index\n\n| Hook | Event | Purpose | Full docs |\n|------|-------|---------|-----------|\n| `apm_session_start` | `agent:bootstrap` | Auto-inject APM context per chat type (DM vs group, channel-agnostic) | [`hooks/apm_session_start/HOOK.md`](hooks/apm_session_start/HOOK.md) |\n| `remem-flush` | `message:received`, `system:event` | Manual flush on `/remem` (user or cron) | [`hooks/remem-flush/HOOK.md`](hooks/remem-flush/HOOK.md) |\n| `precompact-remem` | `session:compact:before` | Auto-flush before context is lost | [`hooks/precompact-remem/HOOK.md`](hooks/precompact-remem/HOOK.md) |\n\n## Shipped Files\n\n```\nhooks/\n├── apm_session_start/\n│   ├── HOOK.md\n│   └── handler.js\n├── remem-flush/\n│   ├── HOOK.md\n│   └── handler.js\n└── precompact-remem/\n    ├── HOOK.md\n    └── handler.js\n```\n\n## Channel Compatibility\n\nAll three hooks are **channel-agnostic at the chat-type level** (DM vs\ngroup). `apm_session_start` additionally detects multiple channel\nsessionKey patterns:\n\n| Channel  | DM | Group | Notes |\n|----------|----|----|-------|\n| Matrix   | ✅ | ✅ | First-class; full + room-only key matching |\n| Telegram | ✅ | ✅ | chat_id as key (negative for groups) |\n| Slack    | ✅ | ✅ | channel_id snowflake as key |\n| Discord  | ✅ | ✅ | channel_id snowflake as key |\n\nTo add a new channel, update `detectChatTypeFromSessionKey` in\n`hooks/apm_session_start/handler.js` and document the key format in\n`hooks/apm_session_start/HOOK.md`.\n\n## Installation\n\nInstall all three hooks in one go:\n\n```bash\nSKILL_DIR=~/.openclaw/workspace/skills/apm-agent-progressive-memory\nHOOKS_DIR=~/.openclaw/hooks\n\ncp -r \"$SKILL_DIR/hooks/apm_session_start/\"   \"$HOOKS_DIR/\"\ncp -r \"$SKILL_DIR/hooks/remem-flush/\"          \"$HOOKS_DIR/\"\ncp -r \"$SKILL_DIR/hooks/precompact-remem/\"     \"$HOOKS_DIR/\"\n\n# Avoid double-flush with the built-in memory-flush hook\nopenclaw hooks disable memory-flush\n\n# Enable precompact (apm_session_start and remem-flush are auto-loaded)\nopenclaw hooks enable precompact-remem\n```\n\n## Verification\n\nAfter installation, verify all three handlers load:\n\n```bash\n# Each handler should parse and export { handler } without error\nfor hook in apm_session_start remem-flush precompact-remem; do\n  node -e \"require('./hooks/$hook/handler.js'); console.log('$hook OK')\"\ndone\n```\n\n## Hook Interaction\n\n```\nagent run start\n   │\n   ▼\nagent:bootstrap event\n   │\n   ├─► apm_session_start  ──► injects APM_SESSION_START.md (DM)\n   │                       or APM_GROUP_SESSION_START.md (group)\n   │\n   ▼\nagent responds to user\n   │\n   ▼\nuser sends /remem (or cron fires /remem)\n   │\n   ├─► remem-flush        ──► records mtime deltas in\n   │                          memory/flush-state.json (DM) OR\n   │                          memory/gr"}],"languages":[],"docsSourceLabel":"CLAWHUB","editorialOverview":null,"editorialQuality":{"score":100,"threshold":65,"status":"thin","wordCount":1330,"uniquenessScore":43,"reasons":["uniqueness-below-45"]}},"media":{"evidence":{"source":"no-media","verified":false,"confidence":"low","updatedAt":"2026-10-11T04:21:34.523Z","emptyReason":"No screenshots, media assets, or demo links are available."},"primaryImageUrl":null,"mediaAssetCount":0,"assets":[],"demoUrl":null},"ownerResources":{"evidence":{"source":"unclaimed","verified":false,"confidence":"low","updatedAt":"2026-10-11T04:21:34.523Z","emptyReason":"This page has not been claimed by the agent owner."},"hasCustomPage":false,"customPageUpdatedAt":null,"customLinks":[],"structuredLinks":{"docsUrl":null,"demoUrl":null,"supportUrl":null,"pricingUrl":null,"statusUrl":null},"customPage":null},"relatedAgents":{"evidence":{"source":"protocol-neighbors","verified":false,"confidence":"medium","updatedAt":"2026-10-11T07:40:11.762Z","emptyReason":null},"items":[{"id":"8ebccd8e-3863-4187-8355-c3f14e1f9edf","entityType":"agent","canonicalPath":"/agent/iofficeai-aionui","slug":"iofficeai-aionui","name":"AionUi","description":"Free, local, open-source 24/7 Cowork app and OpenClaw for Gemini CLI, Claude Code, Codex, OpenCode, Qwen Code, Goose CLI, Auggie, and more | 🌟 Star if you like it!","url":"https://github.com/iOfficeAI/AionUi","homepage":"https://www.aionui.com","source":"GITHUB_REPOS","protocols":["MCP","OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-10-09T19:11:12.944Z","createdAt":"2026-02-25T03:38:16.584Z","downloads":null},{"id":"b917f68a-ebff-438e-84f8-3f4b2494c0bc","entityType":"agent","canonicalPath":"/agent/activepieces-activepieces","slug":"activepieces-activepieces","name":"activepieces","description":"AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents","url":"https://github.com/activepieces/activepieces","homepage":"https://www.activepieces.com","source":"GITHUB_REPOS","protocols":["OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-04-15T02:22:12.426Z","createdAt":"2026-02-25T03:38:12.412Z","downloads":null},{"id":"5cb26759-3a39-483f-94cf-276a98c13bb8","entityType":"agent","canonicalPath":"/agent/cherryhq-cherry-studio","slug":"cherryhq-cherry-studio","name":"cherry-studio","description":"AI productivity studio with smart chat, autonomous agents, and 300+ assistants. Unified access to frontier LLMs","url":"https://github.com/CherryHQ/cherry-studio","homepage":"https://cherry-ai.com","source":"GITHUB_REPOS","protocols":["MCP","OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-04-11T14:38:40.986Z","createdAt":"2026-02-25T03:38:19.379Z","downloads":null},{"id":"6f6582d0-5d76-4f0f-b81d-86520247950b","entityType":"agent","canonicalPath":"/agent/copilotkit-copilotkit","slug":"copilotkit-copilotkit","name":"CopilotKit","description":"The Frontend for Agents & Generative UI. React + Angular","url":"https://github.com/CopilotKit/CopilotKit","homepage":"https://docs.copilotkit.ai","source":"GITHUB_REPOS","protocols":["OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-03-25T09:50:57.846Z","createdAt":"2026-02-25T03:39:14.617Z","downloads":null}],"links":{"hub":"/agent","source":"/agent/source/clawhub","protocols":[{"label":"OpenClaw","href":"/agent/protocol/openclew"}]}}}