mio-agent-runtime 0.5.17 → 0.5.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,25 +1,25 @@
1
- # mio-agent-runtime
2
-
3
- Mio Agent Runtime 的可发布 CLI 包。
4
-
5
- 安装一次,所有 Agent 自动接入 Mio。
6
-
7
- ## Install
8
-
9
- ```bash
10
- npm install -g mio-agent-runtime
11
- ```
12
-
13
- > 新机器 / 升级:请安装 `>=0.3.6`(Codex + OpenCode + Hermes 被动观察)。
14
- > 旧版本只有主动 MCP 规则注入,没有「无感存/取」。安装后执行一次
15
- > `mio init && mio install <host>`。
16
-
1
+ # mio-agent-runtime
2
+
3
+ Mio Agent Runtime 的可发布 CLI 包。
4
+
5
+ 安装一次,所有 Agent 自动接入 Mio。
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ npm install -g mio-agent-runtime
11
+ ```
12
+
13
+ > 新机器 / 升级:请安装 `>=0.5.22`(5 host 被动观察 + trace 查询 + digest 价值管线)。
14
+ > 旧版本只有主动 MCP 规则注入,没有「无感存/取」。安装后执行一次
15
+ > `mio init && mio install <host>`。
16
+
17
17
  ## Commands
18
18
 
19
19
  ```text
20
- mio init Initialize MIO_HOME
21
- mio mcp Start Mio MCP server (stdio)
22
- mio install <host> Install Mio into a host (codex|opencode|workbuddy|hermes)
20
+ mio init Initialize MIO_HOME
21
+ mio mcp Start Mio MCP server (stdio)
22
+ mio install <host> Install Mio into a host (codex|opencode|workbuddy|hermes|claude)
23
23
  mio status Show runtime and adapter status
24
24
  mio agents List installed agents
25
25
  mio evolution status Show composed evolution module health
@@ -31,11 +31,180 @@ mio evolution migration plan Preview state migration diffs
31
31
  mio evolution cutover apply --dry-run Dry-run a cutover plan without switching authority
32
32
  mio observe Watch WorkBuddy transcripts and auto-ingest task outcomes (foreground)
33
33
  mio observe --start|--stop|--status|--once Manage the background observer daemon
34
+ mio recall "<query>" Search Mio memory from the terminal (--project/--scope/--kind/--tags/--limit)
35
+ mio traces Show recent observer traces (--type/--outcome/--agent/--since/--limit/--compact)
36
+ mio prune --days 30 Trim old traces/queries/reuse records and observe.log (--dry-run to preview; --memory needs --yes)
37
+ mio digest --days 7 Aggregate traces/memory/reuse into an actionable report (--write-back feeds agent context files; --json)
38
+ mio remember "<content>" Write a memory record from the terminal (--kind/--tags/--scope/--project)
34
39
  mio --json status Machine-readable status
35
40
  mio --json agents Machine-readable agents
36
41
  mio --json evolution status Machine-readable evolution module health
37
42
  ```
38
43
 
44
+ ## MCP Tools
45
+
46
+ MCP server exposes 46 tools across 5 domains:
47
+
48
+ ### Memory (9)
49
+ `mio.memory.query` · `mio.memory.record` · `mio.memory.archive` · `mio.memory.migrate` · `mio.memory.analyze` · `mio.experience.list` · `mio.experience.confirm` · `mio.experience.reuse` · `mio.policy.check`
50
+
51
+ ### Observer Pipeline (14)
52
+ `mio.observer.world_model` · `mio.observer.trends` · `mio.observer.research` · `mio.observer.insights` · `mio.observer.status` · `mio.observer.collect` · `mio.observer.ferment` · `mio.observer.essays` · `mio.observer.dag` · `mio.observer.ingest` · `mio.observer.subscribe` · `mio.observer.digest`
53
+ `mio.trace.query` — query the trace log (task outcomes, tool errors) by type/outcome/agent/project/time window; also available as `mio traces` on the CLI
54
+ `mio.digest.generate` — aggregate recent data into an actionable digest (agent success rates, project activity, error hotspots, reuse evidence, suggestions); also available as `mio digest` on the CLI
55
+
56
+ ### Insight Self-Observation (4)
57
+ `mio.insight.status` · `mio.insight.list` · `mio.insight.mark_reported` · `mio.insight.generate`
58
+
59
+ ### Creativity Engine (4)
60
+ `mio.creativity.generate` · `mio.creativity.ferment` · `mio.creativity.list` · `mio.creativity.status`
61
+
62
+ ### Task, Agent & Evolution (15)
63
+ `mio.task.route` · `mio.task.record_outcome` · `mio.agent.register` · `mio.agent.list` · `mio.agent.report` · `mio.host.capabilities` · `mio.evolution.status` · `mio.evolution.report` · `mio.evolution.shadow.record` · `mio.evolution.dual_write.record` · `mio.evolution.cutover.readiness` · `mio.evolution.cutover.apply` · `mio.evolution.migration.plan` · `mio.evolution.authority.plan` · `mio.phase0.report`
64
+
65
+ ## Packages
66
+
67
+ Published to npm under `@akemi-mio` scope:
68
+
69
+ | Package | Description |
70
+ |---|---|
71
+ | `@akemi-mio/core` | Electron lifecycle, config, logging, EventBus, patterns, schemas |
72
+ | `@akemi-mio/cli` | CLI helpers |
73
+ | `@akemi-mio/runtime-contracts` | Shared type definitions |
74
+ | `@akemi-mio/runtime-foundation` | Logging, EventBus, memory schemas |
75
+ | `@akemi-mio/experience-memory` | Experience recording and retrieval |
76
+ | `@akemi-mio/evolution-learning` | Evolution learning engine |
77
+ | `@akemi-mio/evolution-strategy` | Evolution strategy engine |
78
+ | `@akemi-mio/evolution-safety` | Safety guardrails |
79
+ | `@akemi-mio/evolution-scheduler` | Evolution scheduler |
80
+ | `@akemi-mio/analysis` | ModuleScanner — static analysis of package source trees (zero deps) |
81
+ | `@akemi-mio/messaging` | ExternalMessageGateway — inbound message routing + notification dispatch via injected renderer/outbox (zero deps; telegram adapters stay host-side) |
82
+ | `@akemi-mio/reasoning` | Reasoning planner — pure-function scoring for reasoning directives (injectable logger) |
83
+ | `@akemi-mio/resource-control` | Resource budgets, background task runner, budget rebalancing (injectable runtime) |
84
+ | `@akemi-mio/agent-persona` | Persona drift control, content classification, user behavior analysis (injectable logger) |
85
+ | `@akemi-mio/creativity` | CreativityService — LLM-powered concept generation, conflict detection, merging, fermentation (TypeScript, depends on `@akemi-mio/core`) |
86
+ | `@akemi-mio/observer` | ObserverService — multi-source data collection, trend analysis, deep research, world model, fermentation, DAG state machine, self-evolution engine (zero npm deps) |
87
+ | `@akemi-mio/insight` | InsightService — LLM-based insight generation, conflict/drift/repetition/stalled-goal/friction detectors, presence service, insight scoring (zero npm deps) |
88
+ | `mio-agent-runtime` | This package — CLI + MCP server |
89
+
90
+ ## Host notes
91
+
92
+ - OpenCode uses `~/.config/opencode/opencode.json` for MCP registration and
93
+ `~/.config/opencode/AGENTS.md` for global instructions. `mio install opencode`
94
+ writes both files and injects Mio usage rules into `AGENTS.md` so OpenCode
95
+ calls Mio memory/observer/policy automatically. If OpenCode is already
96
+ running, restart it once so it reloads both files. `mio observe` also
97
+ passively tails the OpenCode session database (`opencode db`) without
98
+ requiring the model to call Mio tools.
99
+ - Hermes uses `hermes mcp add mio-intelligence --command node --args <server>`
100
+ to register the Mio MCP server. Hermes has native memory and reads
101
+ AGENTS.md Context Files, so retrieval works without Mio rule injection.
102
+ - Claude Code: `mio install claude` registers the Mio MCP server at user
103
+ scope in `~/.claude.json` (`mcpServers`) — no interactive approval needed,
104
+ unlike project-scope `.mcp.json` — and injects Mio usage rules into
105
+ `~/.claude/CLAUDE.md` (auto-loaded user memory) plus `<workspace>/CLAUDE.md`
106
+ (project memory). Restart running Claude Code sessions to reload both.
107
+ `mio observe` passively tails `<config-dir>/projects/<munged-cwd>/*.jsonl`
108
+ session transcripts: sidechain (subagent) lines are skipped, each user
109
+ prompt closes the previous turn, `tool_result.is_error` lines are recorded
110
+ as error traces, and successful turn summaries are written back into the
111
+ workspace `CLAUDE.md` MIO_CONTEXT block so the next session retrieves them
112
+ passively. Set `CLAUDE_CONFIG_DIR` to override the config dir.
113
+ - WorkBuddy uses `~/.workbuddy/mcp.json` and requires each custom MCP server to
114
+ be approved in `~/.workbuddy/mcp-approvals.json`. `mio install workbuddy`
115
+ writes both files and injects Mio usage rules into
116
+ `~/.workbuddy/CODEBUDDY.md` (user-level memory rules, auto-loaded by
117
+ WorkBuddy into every session; the CLI hardcodes the CodeBuddy product name, so the file is CODEBUDDY.md not WORKBUDDY.md) plus `<workspace>/AGENTS.md` (project-level).
118
+ If WorkBuddy is already running, restart it once so it reloads the approval
119
+ and memory rule files.
120
+
121
+ ## Passive observer (`mio observe`)
122
+
123
+ WorkBuddy 的默认模型不一定会主动调用 Mio MCP 工具,即使规则已注入
124
+ (`CODEBUDDY.md` / `AGENTS.md`)。`mio observe` 是一个不依赖模型自觉的
125
+ 兜底:它持续监听 `~/.workbuddy/projects/**/*.jsonl` 会话记录,把每个任务的
126
+ 结果(`task_outcome`)、工具调用错误(`error`)以及完成任务的摘要自动写入
127
+ `MIO_HOME/traces.jsonl` 和 `MIO_HOME/memory.jsonl`(与 MCP 服务同一套
128
+ schema,`source=workbuddy-observer`)。
129
+
130
+ - `mio install <host>` 会自动执行一次回填并启动后台观察器。
131
+
132
+ - 除了写入 `MIO_HOME`,观察器还会把任务摘要**写回 WorkBuddy 自己的记忆文件**
133
+ (`<workspace>/.workbuddy/memory/YYYY-MM-DD.md`,标为 `## Mio 自动摘要`)。
134
+ WorkBuddy 的系统提示要求模型每次会话维护并阅读这些文件,所以下一次会话
135
+ WorkBuddy 会**被动取到** Mio 记录的内容——单 Agent 的「存 + 取」闭环不依赖
136
+ 模型调用 Mio 工具。
137
+ - 已处理的文件偏移记录在 `MIO_HOME/observe-state.json`,不会重复写入。
138
+ - 只回填最近 24h 内更新的会话,避免把历史记录灌入记忆库。
139
+
140
+ ### Context 块的写入范围(`MIO_CONTEXT`)
141
+
142
+ `<workspace>/AGENTS.md`(或 `CLAUDE.md`)里的 `MIO_CONTEXT` 块最多保留
143
+ 6 条(`CONTEXT_MAX`),按时间倒序。两条规则保证真实历史不被挤掉:
144
+
145
+ - **同一条内容只占一个位置**。重复写入只把它移到最前。旧版本会把同一行
146
+ 反复插入,占满全部 6 个位置,把真实任务摘要整体挤出(存量
147
+ `observe-state.json` 里的重复条目会在下次写入时自动清理)。
148
+ - **`mio digest --write-back` 只写回有数据的项目**。写回的是一行项目维度
149
+ 摘要(`digest(7d): <项目> N 任务 M% 成功`),不是全局统计;`observe-state`
150
+ 里没有对应 digest 数据的 workspace 会被直接跳过,不会被写入。旧版本把
151
+ 同一条全局 headline 广播给所有历史项目,导致无关仓库(如 ComfyUI)被污染。
152
+
153
+ 需要强制指定目标时用 `--cwd <path>` 或 `--project <name>`;`--cwd` 优先。
154
+
155
+ OpenCode 会话不依赖模型自觉:`mio observe` 通过 `opencode db` 增量读取
156
+ `~/.local/share/opencode/opencode.db`(Windows 下该文件被 OpenCode 独占锁定,
157
+ 必须经 opencode 自带 CLI 读取),按 `part` 表的 rowid 做增量游标,只传输
158
+ `text`/`tool` 两种 part,把每个用户回合的 `task_outcome` 与工具错误写入
159
+ `MIO_HOME/traces.jsonl` / `memory.jsonl`(`source=opencode-observer`),并同样
160
+ 把摘要写回 `<workspace>/AGENTS.md` 的 `MIO_CONTEXT` 块,供 OpenCode 下一会话
161
+ 被动取用。首次启动只回填最近 24h 的 part,避免历史会话灌入记忆库。
162
+
163
+ Hermes(Nous hermes-agent)同理:`mio observe` 以只读方式增量读取
164
+ `<LocalAppData>/hermes/state.db`(`messages.id` 自增游标,无需调用 hermes CLI),
165
+ 把每个用户回合的 `task_outcome` 写入 `MIO_HOME`(`source=hermes-observer`)。
166
+ Hermes 本身有原生记忆,Mio 只负责让 Hermes 经验进入跨 Agent 生态;仅当会话
167
+ 发生在真实 git 仓库时才写回该仓库的 `AGENTS.md`,避免污染用户主目录。
168
+
169
+ ## MIO_HOME
170
+
171
+ 默认 `~/.mio-intelligence`,可通过环境变量 `MIO_HOME` 覆盖。
172
+
173
+ ## Package layout
174
+
175
+ ```text
176
+ packages/mio-cli
177
+ ├── bin/mio.js
178
+ ├── adapters/
179
+ │ ├── codex.js
180
+ │ ├── hermes.js
181
+ │ ├── opencode.js
182
+ │ ├── workbuddy.js
183
+ │ └── claude-code.js
184
+ ├── observe/
185
+ │ └── observer.js
186
+ ├── server/
187
+ │ ├── host-capabilities.js
188
+ │ ├── evolution-cutover.js
189
+ │ ├── runtime-modules.js
190
+ │ ├── creativity-engine.js
191
+ │ ├── memory-store.js
192
+ │ ├── retention.js
193
+ │ ├── digest.js
194
+ │ └── mio-intelligence-mcp/index.js
195
+ └── package.json
196
+ ```
197
+
198
+ `server/memory-store.js` is the single implementation of memory
199
+ query/record ranking (Latin token + CJK bigram scoring, project/global
200
+ scope layers, reuse-evidence weighting). Both the MCP server
201
+ (`mio.memory.query` / `mio.memory.record`) and the CLI
202
+ (`mio recall` / `mio remember`) go through it, so rankings are identical
203
+ across entry points. `server/digest.js` aggregates traces/memory/reuse
204
+ into actionable reports (also exposed as `mio.digest.generate`), and
205
+ `server/retention.js` powers `mio prune` (age/expiry trimming with
206
+ backups; `memory.jsonl` is never touched without explicit `--memory --yes`).
207
+
39
208
  ## Release verification
40
209
 
41
210
  Before publishing the runtime packages, run:
@@ -71,91 +240,3 @@ node packages/mio-cli/scripts/verify-packed-runtime.js \
71
240
  --install-dir ./dist/mio-pack-install \
72
241
  --report-path ./dist/mio-pack-report.json
73
242
  ```
74
-
75
- This packs all seven `@akemi-mio/*` runtime modules plus `mio-agent-runtime`, installs
76
- the local tarballs into a clean temporary npm project, and runs installed CLI
77
- smoke checks for `mio --json evolution status`, shadow sample recording,
78
- dual-write sample recording, cutover readiness, and dry-run cutover apply. The
79
- JSON output includes each packed tarball path, size, and SHA-512 digest for
80
- release evidence. When `MIO_PACK_REPORT_PATH` or `--report-path` is set, the
81
- same JSON is written to that file; existing report files are not overwritten. It
82
- fails closed if any runtime module is missing, unloaded, or unhealthy, if
83
- shadow/dual-write parity fails, or if cutover apply stops behaving as a dry run.
84
- It does not publish packages or switch authority.
85
-
86
- ## Host notes
87
-
88
- - OpenCode uses `~/.config/opencode/opencode.json` for MCP registration and
89
- `~/.config/opencode/AGENTS.md` for global instructions. `mio install opencode`
90
- writes both files and injects Mio usage rules into `AGENTS.md` so OpenCode
91
- calls Mio memory/observer/policy automatically. If OpenCode is already
92
- running, restart it once so it reloads both files. `mio observe` also
93
- passively tails the OpenCode session database (`opencode db`) without
94
- requiring the model to call Mio tools.
95
- - Hermes uses `hermes mcp add mio-intelligence --command node --args <server>`
96
- to register the Mio MCP server. Hermes has native memory and reads
97
- AGENTS.md Context Files, so retrieval works without Mio rule injection.
98
- - WorkBuddy uses `~/.workbuddy/mcp.json` and requires each custom MCP server to
99
- be approved in `~/.workbuddy/mcp-approvals.json`. `mio install workbuddy`
100
- writes both files and injects Mio usage rules into
101
- `~/.workbuddy/CODEBUDDY.md` (user-level memory rules, auto-loaded by
102
- WorkBuddy into every session; the CLI hardcodes the CodeBuddy product name, so the file is CODEBUDDY.md not WORKBUDDY.md) plus `<workspace>/AGENTS.md` (project-level).
103
- If WorkBuddy is already running, restart it once so it reloads the approval
104
- and memory rule files.
105
-
106
- ## Passive observer (`mio observe`)
107
-
108
- WorkBuddy 的默认模型不一定会主动调用 Mio MCP 工具,即使规则已注入
109
- (`CODEBUDDY.md` / `AGENTS.md`)。`mio observe` 是一个不依赖模型自觉的
110
- 兜底:它持续监听 `~/.workbuddy/projects/**/*.jsonl` 会话记录,把每个任务的
111
- 结果(`task_outcome`)、工具调用错误(`error`)以及完成任务的摘要自动写入
112
- `MIO_HOME/traces.jsonl` 和 `MIO_HOME/memory.jsonl`(与 MCP 服务同一套
113
- schema,`source=workbuddy-observer`)。
114
-
115
- - `mio install <host>` 会自动执行一次回填并启动后台观察器。
116
-
117
- - 除了写入 `MIO_HOME`,观察器还会把任务摘要**写回 WorkBuddy 自己的记忆文件**
118
- (`<workspace>/.workbuddy/memory/YYYY-MM-DD.md`,标为 `## Mio 自动摘要`)。
119
- WorkBuddy 的系统提示要求模型每次会话维护并阅读这些文件,所以下一次会话
120
- WorkBuddy 会**被动取到** Mio 记录的内容——单 Agent 的「存 + 取」闭环不依赖
121
- 模型调用 Mio 工具。
122
- - 已处理的文件偏移记录在 `MIO_HOME/observe-state.json`,不会重复写入。
123
- - 只回填最近 24h 内更新的会话,避免把历史记录灌入记忆库。
124
-
125
- OpenCode 会话不依赖模型自觉:`mio observe` 通过 `opencode db` 增量读取
126
- `~/.local/share/opencode/opencode.db`(Windows 下该文件被 OpenCode 独占锁定,
127
- 必须经 opencode 自带 CLI 读取),按 `part` 表的 rowid 做增量游标,只传输
128
- `text`/`tool` 两种 part,把每个用户回合的 `task_outcome` 与工具错误写入
129
- `MIO_HOME/traces.jsonl` / `memory.jsonl`(`source=opencode-observer`),并同样
130
- 把摘要写回 `<workspace>/AGENTS.md` 的 `MIO_CONTEXT` 块,供 OpenCode 下一会话
131
- 被动取用。首次启动只回填最近 24h 的 part,避免历史会话灌入记忆库。
132
-
133
- Hermes(Nous hermes-agent)同理:`mio observe` 以只读方式增量读取
134
- `<LocalAppData>/hermes/state.db`(`messages.id` 自增游标,无需调用 hermes CLI),
135
- 把每个用户回合的 `task_outcome` 写入 `MIO_HOME`(`source=hermes-observer`)。
136
- Hermes 本身有原生记忆,Mio 只负责让 Hermes 经验进入跨 Agent 生态;仅当会话
137
- 发生在真实 git 仓库时才写回该仓库的 `AGENTS.md`,避免污染用户主目录。
138
-
139
- ## MIO_HOME
140
-
141
- 默认 `~/.mio-intelligence`,可通过环境变量 `MIO_HOME` 覆盖。
142
-
143
- ## Package layout
144
-
145
- ```text
146
- packages/mio-cli
147
- ├── bin/mio.js
148
- ├── adapters/
149
- │ ├── codex.js
150
- │ ├── hermes.js
151
- │ ├── opencode.js
152
- │ └── workbuddy.js
153
- ├── observe/
154
- │ └── observer.js
155
- ├── server/
156
- │ ├── host-capabilities.js
157
- │ ├── evolution-cutover.js
158
- │ ├── runtime-modules.js
159
- │ └── mio-intelligence-mcp/index.js
160
- └── package.json
161
- ```
@@ -0,0 +1,141 @@
1
+ 'use strict'
2
+
3
+ const fs = require('fs')
4
+ const path = require('path')
5
+ const os = require('os')
6
+
7
+ function configDir() {
8
+ return process.env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), '.claude')
9
+ }
10
+
11
+ // Claude Code keeps user-scope MCP servers in the top-level ~/.claude.json
12
+ // (moved to $CLAUDE_CONFIG_DIR/.claude.json when CLAUDE_CONFIG_DIR is set).
13
+ // Project-scope .mcp.json files require interactive approval, so we install
14
+ // at user scope only.
15
+ function configPath() {
16
+ if (process.env.CLAUDE_CONFIG_DIR) {
17
+ return path.join(process.env.CLAUDE_CONFIG_DIR, '.claude.json')
18
+ }
19
+ return path.join(os.homedir(), '.claude.json')
20
+ }
21
+
22
+ // User-level memory file. Claude Code auto-loads ~/.claude/CLAUDE.md into
23
+ // every session, which gives the Mio usage rules a guaranteed retrieval path.
24
+ function memoryRulesPath() {
25
+ return path.join(configDir(), 'CLAUDE.md')
26
+ }
27
+
28
+ // Project-level memory. Claude Code auto-loads <workspace>/CLAUDE.md.
29
+ function projectInstructionsPath(workspace) {
30
+ return path.join(workspace || process.cwd(), 'CLAUDE.md')
31
+ }
32
+
33
+ function readJson(file) {
34
+ if (!fs.existsSync(file)) return null
35
+ try {
36
+ return JSON.parse(fs.readFileSync(file, 'utf8'))
37
+ } catch (_) {
38
+ return null
39
+ }
40
+ }
41
+
42
+ const MEMORY_BEGIN = '<!-- MIO_INTELLIGENCE_BEGIN -->'
43
+ const MEMORY_END = '<!-- MIO_INTELLIGENCE_END -->'
44
+ const MEMORY_BLOCK = `${MEMORY_BEGIN}
45
+ ## Mio Intelligence Layer
46
+
47
+ Mio MCP tools are available. Treat these as mandatory runtime rules for every workspace.
48
+
49
+ - Before designing or implementing a solution, or when unsure about prior decisions, call \`mio-intelligence_mio.memory.query\` first. Omit \`project\` unless a specific project is required; Mio derives it from the current Git repository.
50
+ - After a decision affecting architecture, deployment, dependencies, or long-term behavior, call \`mio-intelligence_mio.memory.record\` with \`kind\`: \`decision\`, \`context\`, \`problem\`, or \`note\`.
51
+ - When a tool call fails, retries, or returns an error, call \`mio-intelligence_mio.observer.ingest\` with a stable \`trace_id\`, relevant \`event_type\`, \`payload\`, and \`outcome\`.
52
+ - Before a high-risk operation such as deletion, migration, credential change, or production change, call \`mio-intelligence_mio.policy.check\` and follow its suggestion when available.
53
+ - At the end of every task, before producing the final answer, call \`mio-intelligence_mio.observer.ingest\` with \`event_type\` = \`task_outcome\`, a stable \`trace_id\`, \`outcome\` = \`success\` / \`failure\` / \`aborted\`, and a brief non-sensitive \`payload\`. If Mio is unavailable, do not block the final answer.
54
+ - When you reuse a prior decision or experience returned by \`mio-intelligence_mio.memory.query\` and it changes your approach or outcome, call \`mio-intelligence_mio.experience.reuse\` with \`sourceAgent\`, \`targetAgent\`, \`experienceId\`, \`reuse\`, \`behaviorChanged\`, and \`outcomeImproved\`.
55
+ - If Mio MCP is unavailable, do not block the task. Continue normally and note the missed memory or observation.
56
+ - Do not store secrets, credentials, or raw sensitive content in Mio memory.
57
+ ${MEMORY_END}`
58
+
59
+ function ensureBlock(target) {
60
+ let content = fs.existsSync(target) ? fs.readFileSync(target, 'utf8') : ''
61
+ const original = content
62
+ const start = content.indexOf(MEMORY_BEGIN)
63
+ if (start !== -1) {
64
+ const end = content.indexOf(MEMORY_END, start)
65
+ content = end === -1 ? content.slice(0, start) : content.slice(0, start) + content.slice(end + MEMORY_END.length)
66
+ content = content.trimEnd()
67
+ }
68
+ if (content) content += '\n\n'
69
+ content += MEMORY_BLOCK + '\n'
70
+ if (content === original) return { changed: false, target, backup: null }
71
+ const backup = `${target}.bak-mio-${Date.now()}`
72
+ if (fs.existsSync(target)) fs.copyFileSync(target, backup)
73
+ fs.mkdirSync(path.dirname(target), { recursive: true })
74
+ fs.writeFileSync(target, content, 'utf8')
75
+ return { changed: true, target, backup }
76
+ }
77
+
78
+ function isInstalled() {
79
+ const config = readJson(configPath())
80
+ const entry = config && config.mcpServers && config.mcpServers['mio-intelligence']
81
+ if (!entry) return false
82
+ const memory = fs.existsSync(memoryRulesPath()) ? fs.readFileSync(memoryRulesPath(), 'utf8') : ''
83
+ return Boolean(memory.includes(MEMORY_BEGIN) && memory.includes(MEMORY_END))
84
+ }
85
+
86
+ function install({ node, serverScript, home, workspace, project }) {
87
+ const target = configPath()
88
+ const config = readJson(target) || {}
89
+ const servers =
90
+ config.mcpServers && typeof config.mcpServers === 'object' ? config.mcpServers : {}
91
+
92
+ const context = JSON.stringify({
93
+ agentId: 'claude-code',
94
+ project: project || path.basename(workspace || process.cwd()),
95
+ workspace: workspace || process.cwd(),
96
+ sessionId: 'claude-code-session',
97
+ })
98
+
99
+ config.mcpServers = {
100
+ ...servers,
101
+ 'mio-intelligence': {
102
+ command: node,
103
+ args: [serverScript],
104
+ env: {
105
+ MIO_DATA_DIR: home,
106
+ MIO_CONTEXT: context,
107
+ },
108
+ },
109
+ }
110
+
111
+ const backup = `${target}.bak-mio-${Date.now()}`
112
+ if (fs.existsSync(target)) {
113
+ fs.copyFileSync(target, backup)
114
+ }
115
+
116
+ fs.mkdirSync(path.dirname(target), { recursive: true })
117
+ fs.writeFileSync(target, `${JSON.stringify(config, null, 2)}\n`, 'utf8')
118
+
119
+ const userRules = ensureBlock(memoryRulesPath())
120
+ let projectRules = null
121
+ const workspaceDir = workspace || process.cwd()
122
+ if (workspaceDir && path.isAbsolute(workspaceDir)) {
123
+ projectRules = ensureBlock(projectInstructionsPath(workspaceDir))
124
+ }
125
+
126
+ const changed = userRules.changed || Boolean(projectRules && projectRules.changed)
127
+
128
+ return {
129
+ changed,
130
+ configPath: target,
131
+ memoryRulesPath: userRules.target,
132
+ projectInstructionsPath: projectRules ? projectRules.target : null,
133
+ userRulesChanged: userRules.changed,
134
+ projectRulesChanged: projectRules ? projectRules.changed : false,
135
+ backup,
136
+ message:
137
+ 'Claude Code Mio MCP installed at user scope and Mio rules injected into ~/.claude/CLAUDE.md (auto-loaded user memory) and the workspace CLAUDE.md. Restart Claude Code sessions to load them.',
138
+ }
139
+ }
140
+
141
+ module.exports = { configDir, configPath, memoryRulesPath, projectInstructionsPath, isInstalled, install }