mocode-ai 1.1.7 → 1.1.8

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.
Files changed (51) hide show
  1. package/README.md +23 -37
  2. package/README.zh-CN.md +46 -38
  3. package/dist/agent/core.js +100 -446
  4. package/dist/agent/index.js +2 -21
  5. package/dist/agent/spawn.js +3 -5
  6. package/dist/agent/work-discipline.js +16 -70
  7. package/dist/config/index.js +6 -7
  8. package/dist/context/age-aware.js +18 -48
  9. package/dist/context/artifacts.js +19 -17
  10. package/dist/context/budget.js +27 -28
  11. package/dist/context/classifier.js +0 -1
  12. package/dist/context/encoders/index.js +4 -11
  13. package/dist/context/index.js +4 -7
  14. package/dist/context/lifecycle.js +115 -483
  15. package/dist/context/pipeline.js +8 -15
  16. package/dist/context/relevance.js +77 -55
  17. package/dist/host/stdio.js +0 -6
  18. package/dist/i18n/index.js +0 -6
  19. package/dist/index.js +11 -1
  20. package/dist/llm/index.js +72 -3
  21. package/dist/mcp/index.js +0 -1
  22. package/dist/repl/index.js +21 -15
  23. package/dist/runtime/browser-manager.js +299 -0
  24. package/dist/runtime/dev-server-manager.js +354 -0
  25. package/dist/runtime/shutdown.js +26 -0
  26. package/dist/session/compact.js +86 -102
  27. package/dist/session/index.js +0 -1
  28. package/dist/session/scheduler.js +88 -92
  29. package/dist/session/trace-metrics.js +5 -92
  30. package/dist/session/trace.js +1 -10
  31. package/dist/tools/builtins/browser.js +199 -0
  32. package/dist/tools/builtins/dev-server.js +99 -0
  33. package/dist/tools/builtins/index.js +28 -19
  34. package/dist/tools/builtins/screenshot.js +173 -0
  35. package/dist/tools/builtins/view-image.js +49 -0
  36. package/dist/tools/constants.js +3 -0
  37. package/dist/tools/registry.js +5 -29
  38. package/dist/ui/layout.js +28 -5
  39. package/dist/ui/render.js +11 -0
  40. package/package.json +2 -2
  41. package/dist/agent/middleware/checklist.js +0 -59
  42. package/dist/session/drop.d.ts +0 -19
  43. package/dist/session/drop.js +0 -93
  44. package/dist/tools/builtins/drop-context.d.ts +0 -18
  45. package/dist/tools/builtins/drop-context.js +0 -68
  46. package/dist/verification/diagnostics.js +0 -108
  47. package/dist/verification/fingerprint.js +0 -54
  48. package/dist/verification/index.js +0 -333
  49. package/dist/verification/postconditions.js +0 -98
  50. package/dist/verification/targeted-tests.js +0 -96
  51. package/dist/verification/types.js +0 -1
package/README.md CHANGED
@@ -12,14 +12,12 @@ MoCode explores your code, reads/writes/edits files, runs shell commands, and se
12
12
 
13
13
  ## Engineering discipline
14
14
 
15
- MoCode encodes "how to take coding seriously" into the agent's own behavior, not just into the prompt:
15
+ MoCode keeps code-level control light and leaves task strategy to the agent:
16
16
 
17
- - **Plan Build → Verify → Fix four-phase discipline** — Injected fresh each turn into `buildBasePrompt`, with per-model-family light adaptation. The agent must restate the task, plan, and acceptance signal before touching anything; changes must pass an automatic validation gate; on failure the agent enters a Fix phase and feeds real command output back as a fresh observation. Evidence: `src/agent/work-discipline.ts` + `evals/work-discipline.ts` (6 assertions). Basis: [`docs/coding-harness-quality-roadmap.md` §4.1 PROMPT-01](docs/coding-harness-quality-roadmap.md).
18
- - **Pre-Completion Checklist middleware** — `finish`/`stop` is blocked when `mutation > 0 && no tool call && validation !== 'passed'`. Simple read-only tasks deliberately bypass it to avoid noise. Evidence: `src/agent/middleware/checklist.ts` + `evals/checklist.ts` (6 assertions).
19
- - **Reflective retry + thrash throttling** — Errors are classified into 6 categories (`retry-classifier`); the same tool with the same args ≥3 times appends a hint to switch strategy; failed traces stay in context but receive a targeted reflection prompt instead of a blind retry. Evidence: `src/tools/retry.ts` + `src/agent/retry-classifier.ts` + `evals/retry-classifier.ts` (9 assertions).
20
- - **`ask_human` as a deliberate de-escalation** — No blind guessing. On whitelisted scenarios (sandbox deviation, ambiguous params, conflicting user instructions) the agent prefers "disclose rather than guess" and will explicitly call `ask_human` to pop a panel for your decision (with a call budget). Evidence: ASK_WHITELIST_SECTION in `src/agent/work-discipline.ts` + `evals/ask-budget.ts` (6 assertions).
21
- - **Verification cascade V0 → V3 with content fingerprint cache** — Changes pass through file post-conditions → scoped tsc/eslint → targeted unit tests → affected npm scripts, in that order; the first actionable failure stops the cascade; a SHA-256 content cache skips repeated work on unchanged files. Evidence: `src/validators/` plus the VER chapters in the main roadmap.
22
- - **Five-zone context controls + token self-calibration** — Five independent dials (`autoCompact` / `contextOptimize` / `contextRelprune` / `contextLifecycle` / `contextBudget`), each with its own `MOCODE_*=false` kill switch; even with all five off, observations still age through the lifecycle. Token estimation uses EWMA to self-calibrate against real provider usage rather than trusting the estimator. Evidence: the five modules under `src/context/` plus the `MOCODE_*` switches in `src/config/index.ts`.
17
+ - **Advisory working discipline** — The system prompt asks the agent to make focused changes, avoid redundant retrieval, and decide for itself whether validation is useful. Validation is optional and is never a completion gate.
18
+ - **Transparent tool failures** — Each tool call runs once and returns its raw structured failure to the agent, which decides whether and how to recover.
19
+ - **`ask_human` for user-owned decisions** — The agent asks only when repository evidence cannot resolve a high-impact choice; implementation details remain autonomous.
20
+ - **Five-zone context controls + token self-calibration** — Five independent dials (`autoCompact` / `contextOptimize` / `contextRelprune` / `contextLifecycle` / `contextBudget`) manage context pressure. Token estimation self-calibrates against provider usage.
23
21
 
24
22
  ## Architecture
25
23
 
@@ -29,19 +27,19 @@ MoCode is organized as a layered runtime: the terminal experience drives an auto
29
27
 
30
28
  ### Autonomous execution loop
31
29
 
32
- Each model response is one step in a closed loop. Tool calls are classified by declared capabilities, safe reads can run in parallel, writes acquire canonical resource locks, observations are encoded before returning to context, and code changes pass through automatic validation.
30
+ Each model response is one step in a closed loop. Tool calls are classified by declared capabilities, safe reads can run in parallel, and writes acquire canonical resource locks. Tool evidence returns to history unchanged apart from a hard per-result safety cap. When the agent has no more tools to call, its response completes immediately; the framework does not run hidden validation or force another model turn.
33
31
 
34
32
  <p align="center"><img src="./assets/architecture/agent-loop.svg" alt="MoCode autonomous agent execution loop" width="100%"></p>
35
33
 
36
- ### Context that ages instead of exploding
34
+ ### Context compression only under real pressure
37
35
 
38
- Tool output does not accumulate as an undifferentiated transcript. Typed encoders, relevance pruning, an observation lifecycle, age-aware compression, and a five-zone budget scheduler continuously reshape the active working set while sessions, snapshots, skills, notes, and memory retain durable knowledge.
36
+ Normal sessions retain full tool evidence and structured freshness/provenance metadata. At 80% of the model window, one scheduler event runs enabled exact-supersession, stale-artifact, and old-log/search cleanup, then always compacts history. Lifecycle tracking never ages content by tool-call count.
39
37
 
40
38
  <p align="center"><img src="./assets/architecture/context-engine.svg" alt="MoCode context engineering and durable memory architecture" width="100%"></p>
41
39
 
42
40
  ### Multi-agent work without unsafe shared writes
43
41
 
44
- Read-only sub-agents fan out concurrently. Writer agents work inside private filesystem overlays and return structured ChangeSets; the coordinator checks expected hashes, acquires canonical locks, performs conflict-safe merges, and runs one unified verification gate in the main workspace.
42
+ Read-only sub-agents fan out concurrently. Writer agents work inside private filesystem overlays and return structured ChangeSets; the coordinator checks expected hashes, acquires canonical locks, and performs conflict-safe merges. Validation remains an explicit agent choice in the shared workspace.
45
43
 
46
44
  <p align="center"><img src="./assets/architecture/multi-agent.svg" alt="MoCode multi-agent overlay and ChangeSet coordination" width="100%"></p>
47
45
 
@@ -51,21 +49,19 @@ Every mutating tool calls into a permission layer before it runs. Tools are clas
51
49
 
52
50
  <p align="center"><img src="./assets/architecture/permission-model.svg" alt="MoCode permission model: tool classes, four-tier grants, fingerprinting, durable storage" width="100%"></p>
53
51
 
54
- ### Verification cascade: cheap checks first, expensive checks only on demand
52
+ ### Agent-directed validation
55
53
 
56
- Code changes go through V0 (file post-conditions) V1 (scoped tsc/eslint markers) → V2 (targeted unit tests) → V3 (affected package scripts). The first actionable failure stops the cascade and is fed back to the agent as a fresh observation; a SHA-256 content cache skips repeated work on unchanged files.
57
-
58
- <p align="center"><img src="./assets/architecture/verification-cascade.svg" alt="MoCode verification cascade V0 to V3 with content fingerprint cache" width="100%"></p>
54
+ MoCode does not run a hidden validation cascade when a task ends. The agent can explicitly call `run_command` for a focused test, typecheck, or build when it judges that evidence useful; otherwise it may finish without an extra framework-controlled round trip.
59
55
 
60
56
  ### Rollback timeline: per-mutation snapshots, restore by turn
61
57
 
62
- A clean undo point is saved before every mutating tool. `/rollback <turnId>` restores file buffers in reverse-chronological order under canonical resource locks, then reruns V0+V1 to confirm a clean state never re-runs the model. Read tools, network effects, and binary changes are explicitly out of scope, kept honest in the contract.
58
+ A clean undo point is saved before every mutating tool. `/rollback <turnId>` restores file buffers in reverse-chronological order under canonical resource locks it does not re-run the model or launch automatic tests. Read tools, network effects, and binary changes are explicitly out of scope, kept honest in the contract.
63
59
 
64
60
  <p align="center"><img src="./assets/architecture/rollback-flow.svg" alt="MoCode rollback timeline and per-turn snapshot flow" width="100%"></p>
65
61
 
66
- ### Context controls: five independent dials, not one big toggle
62
+ ### Context controls: one pressure gate, independently optional stages
67
63
 
68
- `autoCompact` / `contextOptimize` / `contextRelprune` / `contextLifecycle` / `contextBudget` each gate a different knob (push-time compression, encoders, superseded-read pruning, observation lifecycle, five-zone scheduler). Each is independently killable via a `MOCODE_*=false` env var; the observation lifecycle runs even with all toggles off, so context still ages instead of exploding. An EWMA self-calibrates the token estimator against real provider usage.
64
+ The controls remain independently configurable, but automatic rewriting has exactly one trigger: corrected or raw request occupancy reaching 80%. That event runs every enabled pressure cleanup and then always compacts history. `contextLifecycle` only tracks provenance metadata, while EWMA calibration keeps the estimate aligned with provider usage.
69
65
 
70
66
  <p align="center"><img src="./assets/architecture/context-controls.svg" alt="MoCode context controls: five independent toggles, observation lifecycle, token self-calibration" width="100%"></p>
71
67
 
@@ -83,7 +79,7 @@ MoCode isn't a chat box with a coat of paint — it's an agent that actually get
83
79
  - **Parallel read-only tools** — Consecutive read-only operations in a turn (reading files, grep, glob, codegraph, web search/fetch) run concurrently, so total time is roughly the slowest single call instead of the sum of all of them. Operations with side effects (writing/editing files) stay sequential to preserve snapshot ordering and data safety.
84
80
  - **Sub-agents divide and conquer** — Complex tasks can spawn independent sub-agents with isolated histories and scoped toolsets. Read-only workers can fan out concurrently; writer workers run in private filesystem overlays and return ChangeSets that are merged under expected-hash checks and canonical resource locks. Only structured findings return to the main thread.
85
81
  - **Plan / Auto dual mode** — In `plan` mode the agent is read-only (reads code, queries indexes, searches — never writes to disk, runs commands, or spawns sub-agents) and produces a plan; `auto` mode unlocks the full toolset. The agent can switch between the two on its own — scope out an unfamiliar codebase first, then start making changes.
86
- - **Automatic context compression** — As the context window fills up, a three-tier compression kicks in (trim individual results compact older tool results in place summarize older turns), so long sessions never overflow. `/context` shows live token usage; `/compact` triggers manual compression (optionally with a focus hint to preserve what matters).
82
+ - **Pressure-driven context compression** — Normal history keeps full tool evidence. At 80% occupancy, one scheduler event runs all enabled cleanup and always follows with a history summary. `/context` shows live usage and `/compact` remains an explicit manual override.
87
83
  - **Cross-session long-term memory** — The agent can save project architecture, conventions, and lessons learned as long-term memory, auto-loaded in future sessions. A background process periodically reflects on conversations to mine things worth remembering. Memories can be created, searched, updated, and forgotten, with recall-based decay.
88
84
  - **Project context (`MOCODE.md`)** — A single project-level memory file at `MOCODE.md` captures both static facts (project description, commands, module list, directory tree) and human/AI-written insights (conventions, architectural decisions, pitfalls). Generate it once with `/init`, then keep it up to date by hand or by asking the agent to refresh it. Loaded automatically into the system prompt on every turn.
89
85
  - **Session notepad (notes.md)** — For complex multi-step tasks (≥3 file changes / ≥5 tool calls), the agent maintains a working notepad at `.mocode/sessions/<sessionId>/notes.md` (file-based, survives context compression). It can record intermediate findings, design decisions, open questions, and structured plans. A live progress chip in the TUI status bar shows `plan: [title] (3/7) ▸ [current step]` when a `## Plan:` section is present. The agent manages the file directly with write_file/edit_file/read_file.
@@ -168,17 +164,17 @@ Common backend `base_url` values:
168
164
  | Environment variable | Description | Default |
169
165
  | --------------------------- | ---------------------------------------------------------------------- | --------------------------- |
170
166
  | `MAX_TOKENS` | Max tokens per response | unlimited |
171
- | `CONTEXT_WINDOW_TOKENS` | Model context window; must match the real model | `128000` |
172
- | `COMPACT_THRESHOLD` | Auto-compaction trigger threshold (fraction of window) | `0.85` |
167
+ | `CONTEXT_WINDOW_TOKENS` | Model context window; must match the real model | `256000` |
173
168
  | `LLM_STREAM_USAGE` | Include `stream_options.include_usage` on streaming requests for real usage | `true` |
174
- | `AUTO_COMPACT` | Auto-compaction master switch | `true` |
175
- | `MOCODE_AUTO_VALIDATE` | Auto-run the lowest-cost discovered validation command after code changes; feed failures back to the agent | `true` |
176
- | `AUTO_REFLECT` | Background reflection pass master switch (periodically mines memories from conversations) | `true` |
169
+ | `AUTO_COMPACT` | Final history-compaction safety fallback | `true` |
170
+ | `AUTO_REFLECT` | Background reflection pass (opt-in; periodically mines memories from conversations) | `false` |
177
171
  | `REFLECT_EVERY_N` | Trigger a background reflection every N turns (runs alongside the agent, non-blocking) | `5` |
178
172
  | `ANYSEARCH_API_KEY` | Web search API key (falls back to anonymous free quota if unset) | none |
179
173
  | `ANYSEARCH_BASE_URL` | Search API endpoint | `https://api.anysearch.com` |
180
174
  | `SKILLS_DIRS` | Override the default skill scan directories (platform path separator) | three default directories |
181
- | `MOCODE_CONTEXT_OPTIMIZE` | Typed encoding of tool results before they reach the LLM (tree/search/log…); disable for raw passthrough (length trimming only) | `true` |
175
+ | `MOCODE_CONTEXT_OPTIMIZE` | Opt-in typed encoding of Cold logs/searches, only under real pressure | `false` |
176
+ | `MOCODE_CONTEXT_RELPRUNE` | Opt-in exact superseded-evidence pruning, only under real pressure | `false` |
177
+ | `MOCODE_LIFECYCLE` | Provenance metadata tracking; never ages or rewrites content | `true` |
182
178
  | `MAX_STEPS` | Max agent loop steps per turn (infinite-loop safety only) | `1000` |
183
179
  | `SUB_AGENT_MAX_STEPS` | Sub-agent loop safety ceiling; defaults to the main-agent value | `1000` |
184
180
  | `SANDBOX_ROOT` | Sandbox root directory (file operation boundary; falls back to cwd if unset) | none |
@@ -215,7 +211,6 @@ The agent operates in **the working directory it was launched from** — to have
215
211
  | `use_skill` | Load the full SKILL.md instructions for a given skill |
216
212
  | `ask_human` | Pop up a Q&A panel at decision points; user picks a preset or types freely (blocks until answered) |
217
213
  | `switch_mode` | Switch between `plan` (read-only planning) and `auto` (full execution); the agent can call this itself to explore before acting |
218
- | `drop_context` | Replace irrelevant old tool results in history with stubs to free up context (preserves tool_call_id pairing, leaves system prompt and current turn untouched, idempotent) |
219
214
  | `sub-agent` | Spawn a capable isolated worker; read tasks can run concurrently and writes use overlay + ChangeSet safe merge |
220
215
 
221
216
  | `memory_save` | Save a piece of cross-session long-term memory (title indexed, body fetched on demand) |
@@ -275,18 +270,9 @@ MoCode automatically scans the following directories for skills (each skill is a
275
270
 
276
271
  A skill's `description` is injected into the system prompt (progressive disclosure, tier 1); the model calls `use_skill` to load the full body (tier 2) only when the task is relevant. Use `/skills` to see discovered skills.
277
272
 
278
- ## Working discipline (Build-and-Self-Verify)
279
-
280
- Every coding task runs through four sequential phases. Skipping or merging them is a failure mode — the system prompt injects this discipline on every turn (see `src/agent/work-discipline.ts`):
281
-
282
- 1. **Plan & Discover** — restate the goal, identify the acceptance signal, read the relevant code, and surface ambiguities via `ask_human` before implementing.
283
- 2. **Build** — make the smallest change that satisfies the spec; tests for new/changed behavior are an obligation, not a "should" aspiration.
284
- 3. **Verify** — run a real, executable verification (typecheck, the project's test command, or a focused reproducer). Read the full output. Compare the result to the **spec**, not to your own diff.
285
- 4. **Fix** — any failure → return to the spec, not to the diff. Re-derive what the spec requires; after a fix, re-run Phase 3 end-to-end. Cap blind retries at three identical failed attempts before changing approach.
286
-
287
- Hard rule: *"I read the code and it looks right" is not a completion signal.* A task is complete only when executable verification against the spec has run, its full output has been read, and the result matches the spec — and the final reply names the command, the output, and the spec line it satisfied.
273
+ ## Working discipline
288
274
 
289
- The section adapts lightly per `model_family` (anthropic / openai / qwen) so the wording matches each base model's instruction-following style. All four variants share the same 4-phase English body; only the opener sentence and the `[model: X]` tag differ. User language preference is handled by the existing i18n block.
275
+ The system prompt provides lightweight guidance rather than a framework gate: inspect only what matters, make focused changes, avoid repeated stale reads, and report uncertainty honestly. The agent decides whether validation is useful for the task and chooses the scope itself. Broad test/build suites are not run by default, and lack of validation never blocks completion or triggers an extra model turn.
290
276
 
291
277
  ## Project memory (MOCODE.md)
292
278
 
package/README.zh-CN.md CHANGED
@@ -16,19 +16,19 @@ MoCode 是一个分层的自治运行时:终端交互层驱动 Agent 内核,
16
16
 
17
17
  ### 自治执行循环
18
18
 
19
- 每次模型响应都是闭环中的一步。工具调用按能力声明分类,安全读取可以并行,写操作获取规范化资源锁,观察结果编码后才回到上下文,代码改动最终经过自动验证门。
19
+ 每次模型响应都是闭环中的一步。工具调用按能力声明分类,安全读取可以并行,写操作获取规范化资源锁。工具证据除单条 hard cap 外原样进入 history,用户与模型看到同一事实。agent 没有更多工具调用时立即完成;框架不会暗中运行验证,也不会强迫追加一轮模型调用。
20
20
 
21
21
  <p align="center"><img src="./assets/architecture/agent-loop-zh-CN.svg" alt="MoCode 自治 Agent 执行循环" width="100%"></p>
22
22
 
23
- ### 会衰减、不会膨胀的上下文
23
+ ### 只在真实 Context Pressure 下压缩
24
24
 
25
- 工具输出不会作为无差别日志无限堆积。类型化编码、相关性裁剪、观察生命周期、年龄感知压缩和五区预算调度持续重塑活跃工作集;会话、SnapshotSkill、notes.md 与长期记忆负责保留耐久知识。
25
+ 正常会话保留完整工具证据,只维护 freshness / provenance 元数据。总上下文达到 80% 时,统一调度事件会执行已启用的 supersededstale artifact、旧日志/搜索清理,然后始终继续 history compact;Lifecycle 不再按工具调用次数老化正文。
26
26
 
27
27
  <p align="center"><img src="./assets/architecture/context-engine-zh-CN.svg" alt="MoCode 上下文工程与持久化记忆架构" width="100%"></p>
28
28
 
29
29
  ### 多 Agent 并行,但不冒险共享写入
30
30
 
31
- 只读子 Agent 可以并行扇出;写任务在私有文件系统 overlay 中完成并返回结构化 ChangeSet。协调器校验 expected hash、获取规范化资源锁、安全合并冲突,最后由主工作区统一执行验证。
31
+ 只读子 Agent 可以并行扇出;写任务在私有文件系统 overlay 中完成并返回结构化 ChangeSet。协调器校验 expected hash、获取规范化资源锁并安全合并冲突;是否验证以及验证范围由 agent 在主工作区自行决定。
32
32
 
33
33
  <p align="center"><img src="./assets/architecture/multi-agent-zh-CN.svg" alt="MoCode 多 Agent overlay 与 ChangeSet 协调" width="100%"></p>
34
34
 
@@ -38,21 +38,19 @@ MoCode 是一个分层的自治运行时:终端交互层驱动 Agent 内核,
38
38
 
39
39
  <p align="center"><img src="./assets/architecture/permission-model-zh-CN.svg" alt="MoCode 权限模型:工具分级、四档授权、指纹、持久化" width="100%"></p>
40
40
 
41
- ### 验证瀑布:便宜检查先做,贵检查按需上场
41
+ ### Agent 自主验证
42
42
 
43
- 代码改动按 V0(文件级后置条件)→ V1(限范围的 tsc/eslint)→ V2(定向单元测试)→ V3(受影响 package 的脚本)由低到高执行。首个可操作失败立即停止,作为新的观察反馈给 Agent;SHA-256 文件指纹缓存避免对未改动文件重复劳动。
44
-
45
- <p align="center"><img src="./assets/architecture/verification-cascade-zh-CN.svg" alt="MoCode 自动验证瀑布 V0 到 V3,带文件指纹缓存" width="100%"></p>
43
+ mocode 不会在任务结束时暗中启动验证瀑布。agent 可以根据任务风险自行调用 `run_command` 跑聚焦测试、typecheck build;也可以在无需额外证据时直接结束,不产生框架强制的额外轮次。
46
44
 
47
45
  ### 回滚时间线:每次写入都留干净撤销点
48
46
 
49
- 每次写入工具执行前先存一份 undo 快照。`/rollback <turnId>` 按时间逆序在 canonical 资源锁下恢复文件缓冲,然后重跑 V0+V1 验证状态干净——完全不重跑模型。读取类工具、网络副作用、二进制改动明确不在截图范围,契约里写死。
47
+ 每次写入工具执行前先存一份 undo 快照。`/rollback <turnId>` 按时间逆序在 canonical 资源锁下恢复文件缓冲,不重跑模型,也不自动启动测试。读取类工具、网络副作用、二进制改动明确不在截图范围,契约里写死。
50
48
 
51
49
  <p align="center"><img src="./assets/architecture/rollback-flow-zh-CN.svg" alt="MoCode 回滚时间线和每轮快照流" width="100%"></p>
52
50
 
53
- ### 上下文控制:五个独立开关,不是一锅端
51
+ ### 上下文控制:一个真实压力线,阶段独立可选
54
52
 
55
- `autoCompact` / `contextOptimize` / `contextRelprune` / `contextLifecycle` / `contextBudget` 各自把控一个旋钮(push 压缩、编码器、被取代读取的剪裁、观察生命周期、五区调度器)。每个都能用 `MOCODE_*=false` 单独关;即使五个全关,观察结果仍按生命周期老化。token 估算带 EWMA 自动校准真实 provider 用量。
53
+ 这些控制项仍可独立配置,但自动改写只有一个触发条件:校正后或原始请求占用达到 80%。该事件会运行所有已启用的 pressure 清理,然后始终继续压缩历史。`contextLifecycle` 只维护 provenance 元数据,EWMA 则让估算持续对齐 provider 实测用量。
56
54
 
57
55
  <p align="center"><img src="./assets/architecture/context-controls-zh-CN.svg" alt="MoCode 上下文控制:五个独立开关、观察生命周期、token 自校准" width="100%"></p>
58
56
 
@@ -66,14 +64,12 @@ MoCode 是一个分层的自治运行时:终端交互层驱动 Agent 内核,
66
64
 
67
65
  ## 工程化纪律
68
66
 
69
- mocode 把"如何认真写代码"这件事也写进了 agent 自身的行为准则,而不是只靠 prompt 教:
67
+ mocode 把代码层控制保持得尽量轻,把任务策略交给 agent
70
68
 
71
- - **Plan → Build → Verify → Fix 四阶段纪律** 每轮 prompt 现拼现读注入 `buildBasePrompt`,并按模型家族做轻量适配;agent 必须先复述任务、规划与验收信号,再动手,改动必经自动验证门,失败时进入修复阶段并把真实命令输出当新观察反馈。证据:`src/agent/work-discipline.ts` + `evals/work-discipline.ts`(6 块断言)。依据:[`docs/coding-harness-quality-roadmap.md` §4.1 PROMPT-01](docs/coding-harness-quality-roadmap.md)。
72
- - **Pre-Completion Checklist 硬关卡** `mutation > 0 && no tool call && validation !== 'passed'` 三个条件同时成立前,`finish`/`stop` 不会被放行;简单无改动的任务刻意不触发,避免噪音。证据:`src/agent/middleware/checklist.ts` + `evals/checklist.ts`(6 块断言)。
73
- - **反思式重试 + thrash 节流** 错误按 6 类分类(`retry-classifier`),同一工具同参数 ≥3 次追加 hint 提醒换策略;失败 trace 留在上下文中但有针对性反思 prompt 注入,而不是盲目重试。证据:`src/tools/retry.ts` + `src/agent/retry-classifier.ts` + `evals/retry-classifier.ts`(9 块断言)。
74
- - **ask_human 卡点降级** 不盲猜:遇到 sandbox 偏差、参数二义、用户指令冲突等白名单场景时,agent 倾向"披露而不是瞎猜",必要时显式调用 `ask_human` 弹面板让你拍板(带调用预算)。证据:`src/agent/work-discipline.ts` 的 ASK_WHITELIST_SECTION + `evals/ask-budget.ts`(6 块断言)。
75
- - **验证瀑布 V0 → V3 + 内容指纹缓存** — 改动先走文件后置条件 → 受限 tsc/eslint → 定向单测 → 受影响 npm 脚本,首个可操作失败立刻停;SHA-256 文件指纹缓存保证未改动文件不重复劳动。证据:`src/validators/` + 主路线图 VER 章节。
76
- - **五区上下文控制 + token 自校准** — 五个独立开关各自把控一档(`autoCompact` / `contextOptimize` / `contextRelprune` / `contextLifecycle` / `contextBudget`),即使全关观察结果也按生命周期老化;token 估算走 EWMA 自动校准真实 provider 用量,而不是死信估算函数。证据:`src/context/` 五模块 + `src/config/index.ts` 的 `MOCODE_*` 开关。
69
+ - **建议式工作纪律**system prompt 只要求聚焦改动、避免重复检索、诚实报告不确定性;是否验证及验证范围由 agent 自主决定,不是完成硬门。
70
+ - **透明工具失败**每个工具调用只执行一次,原始结构化错误直接交给 agent,由 agent 自主决定是否以及如何恢复。
71
+ - **ask_human 卡点降级**仅高影响且属于用户所有权的选择才询问,其余实现细节由 agent 自主推进。
72
+ - **五区上下文控制 + token 自校准** 独立旋钮管理上下文压力,token 估算根据真实 provider 用量校准。
77
73
 
78
74
  ## 为什么用 mocode
79
75
 
@@ -83,7 +79,7 @@ mocode 不是一个套壳聊天框,而是一个能真正动手干活的 agent:
83
79
  - **只读工具并行执行** — 一轮里连续的只读操作(读文件、grep、glob、codegraph、联网搜索/抓取)自动并发跑,总耗时 ≈ 最慢一个,而不是逐个排队。写文件 / 改文件这类有副作用的操作仍串行,保快照顺序与数据安全。
84
80
  - **子 agent 分而治之** — 复杂任务可派生拥有独立历史与受限工具集的子 agent。只读 worker 可并行扇出;写 worker 在私有文件系统 overlay 中运行,返回的 ChangeSet 经过 expected hash 校验与规范化资源锁后才合并。主线只接收结构化发现,不接收过程噪声。
85
81
  - **计划 / 执行双模式** — `plan` 模式下只读探查(读代码、查索引、搜索,绝不写盘、不跑命令、不派生子 agent),产出计划;`auto` 模式全量工具放开。agent 还能在两者间自切换——先把陌生代码库摸清,再动手改。
86
- - **上下文自动压缩**接近窗口上限时三层压缩(单条结果裁剪 旧工具结果原地微压缩 旧对话摘要),长会话也不爆窗口;`/context` 实时显示 token 用量,`/compact` 可手动压缩(能带焦点指令聚焦保留)。
82
+ - **统一压力驱动压缩**正常 history 保留完整工具证据;达到 80% 后由一次调度事件运行所有已启用的清理,并始终继续 history 摘要。`/context` 显示实时用量,`/compact` 仍是用户显式覆盖。
87
83
  - **跨会话长期记忆** — agent 能把项目架构、约定、踩过的坑存成长期记忆,下次会话自动加载;后台还会定期从对话里反思挖掘值得记住的事。记忆可增删改、带召回衰减。
88
84
  - **会话记事本(notes.md)** — 复杂多步任务(≥3 处文件改动 / ≥5 步工具调用)时,agent 在 `.mocode/sessions/<sessionId>/notes.md` 维护一个工作记事本(落盘抗压缩),可记录中间发现、设计决策、待验证问题和结构化计划。TUI 状态栏实时显示进度 chip:`plan: [标题] (3/7) ▸ [当前步]`(当存在 `## Plan:` 段时)。agent 直接用 write_file/edit_file/read_file 管理此文件。
89
85
  - **可中断、可回滚** — Ctrl+C 随时打断当前轮次(树杀子进程,历史还原到本轮开始前,不留残半的工具调用);`/rollback` 按轮次快照恢复文件改动,逐个文件「保留/撤销」,不依赖 git。
@@ -167,16 +163,17 @@ LLM_MODEL=glm-4.6 # 换成你的模型名
167
163
  | 环境变量 | 说明 | 默认值 |
168
164
  | ----------------------- | ------------------------------------------ | --------------------------- |
169
165
  | `MAX_TOKENS` | 单次回复最大 token | 不限 |
170
- | `CONTEXT_WINDOW_TOKENS` | 模型上下文窗口,须对齐真实模型 | `128000` |
171
- | `COMPACT_THRESHOLD` | 自动压缩触发阈值(占窗口比例) | `0.85` |
166
+ | `CONTEXT_WINDOW_TOKENS` | 模型上下文窗口,须对齐真实模型 | `256000` |
172
167
  | `LLM_STREAM_USAGE` | 流式请求带 `stream_options.include_usage` 拿真实用量 | `true` |
173
- | `AUTO_COMPACT` | 自动压缩总开关 | `true` |
174
- | `AUTO_REFLECT` | 后台反思 pass 总开关(定期从会话挖掘记忆) | `true` |
168
+ | `AUTO_COMPACT` | 最终 history compact 安全保护 | `true` |
169
+ | `AUTO_REFLECT` | 后台反思 pass(默认关闭,需要时显式开启) | `false` |
175
170
  | `REFLECT_EVERY_N` | 每 N 轮触发一次后台反思(与 agent 并发,不阻塞) | `5` |
176
171
  | `ANYSEARCH_API_KEY` | 联网搜索 API key(不配走匿名免费额度) | 无 |
177
172
  | `ANYSEARCH_BASE_URL` | 搜索 API 端点 | `https://api.anysearch.com` |
178
173
  | `SKILLS_DIRS` | 覆盖默认 skill 扫描目录(平台分隔符) | 三目录自动扫描 |
179
- | `MOCODE_CONTEXT_OPTIMIZE` | 工具结果进 LLM 前的类型化编码(树/搜索/日志…),关掉则原样进(仅长度裁剪) | `true` |
174
+ | `MOCODE_CONTEXT_OPTIMIZE` | 仅在真实 pressure 下编码 Cold 日志/搜索(显式开启) | `false` |
175
+ | `MOCODE_CONTEXT_RELPRUNE` | 仅在真实 pressure 下裁剪精确 superseded 证据(显式开启) | `false` |
176
+ | `MOCODE_LIFECYCLE` | 只维护 provenance 元数据,不按次数改写正文 | `true` |
180
177
  | `MAX_STEPS` | 每轮 Agent 循环最大步数(仅防无限循环) | `1000` |
181
178
  | `SUB_AGENT_MAX_STEPS` | 子 Agent 循环安全上限,默认与主 Agent 一致 | `1000` |
182
179
  | `SANDBOX_ROOT` | 沙箱根目录(文件操作边界;未配则用 cwd 兜底) | 无 |
@@ -201,10 +198,14 @@ agent 工作在**启动时所在的工作目录**——想让它操作某个项
201
198
 
202
199
  | 工具 | 作用 |
203
200
  | --------------- | -------------------------------------------------------- |
204
- | `read_file` | 读文件,带行号,支持 `offset` / `limit` |
201
+ | `read_file` | 读文本文件,带行号,支持 `offset` / `limit` |
202
+ | `view_image` | 读取已有 PNG/JPEG/GIF/WebP 图片并作为视觉输入回灌模型(最大 4 MiB) |
203
+ | `screenshot` | 经用户确认后截取主显示器或整个桌面,保存 PNG 并立即交给视觉模型分析 |
205
204
  | `write_file` | 创建/覆盖文件,自动建父目录 |
206
205
  | `edit_file` | 精确字符串替换(`old_string` 须唯一匹配) |
207
206
  | `run_command` | 执行 shell 命令,合并 stdout+stderr,默认 120s 超时 |
207
+ | `dev_server` | 启动/查看/读日志/停止常驻后台进程(dev server),跨工具调用存活 |
208
+ | `browser` | Playwright 驱动真实 Chromium:导航 / 点击 / 填表 / 取文本 / 截图 / 控制台诊断 |
208
209
  | `glob` | 按 glob 模式找文件(排除 node\_modules/.git) |
209
210
  | `grep` | 内容正则搜索,纯 JS 实现,不依赖 `rg` |
210
211
  | `codegraph` | 已建 `.codegraph/` 索引时,查代码符号源码与调用链(比 read\_file/grep 更准更省) |
@@ -213,7 +214,6 @@ agent 工作在**启动时所在的工作目录**——想让它操作某个项
213
214
  | `use_skill` | 加载某 skill 的完整 SKILL.md 指令 |
214
215
  | `ask_human` | 决策点弹终端问答面板,用户选预设项或自由输入(阻塞至回应) |
215
216
  | `switch_mode` | 在 `plan`(只读规划)与 `auto`(全量执行)间切换;agent 可自行调用,先探查再动手 |
216
- | `drop_context` | 把历史里无关的旧工具结果替换为存根释放上下文(保 tool_call_id 配对,不动 system 与当前轮;幂等) |
217
217
  | `sub-agent` | 派生具备完整能力的隔离子 Agent;只读任务可并发,写任务通过 overlay + ChangeSet 安全合并 |
218
218
 
219
219
  | `memory_save` | 存一条跨会话长期记忆(标题进索引,正文按需取) |
@@ -222,6 +222,22 @@ agent 工作在**启动时所在的工作目录**——想让它操作某个项
222
222
  | `memory_update` | 原地改一条记忆(id 不变;纠正过时事实 / 改摘要 / 改 pin) |
223
223
  | `memory_forget` | 遗忘记忆:默认归档(可复活),`mode=delete` 硬删(pinned 拒删) |
224
224
 
225
+ ### 前端 / UI 闭环
226
+
227
+ `dev_server` + `browser` 组成「跑起来 → 打开页面 → 看渲染结果」的闭环:
228
+
229
+ ```
230
+ dev_server start command="npm run dev" readyUrl="http://localhost:5173"
231
+ browser open → navigate → click / fill → screenshot
232
+ dev_server stop id=srv-xxxx
233
+ ```
234
+
235
+ - `dev_server` 的进程跨工具调用存活(`run_command` 做不到:它会在超时或本轮中断时树杀)。就绪等待支持 `readyUrl`(仅回环地址)或 `readyPattern`(匹配启动日志),日志写在 `.mocode/dev-servers/<id>.log`,支持按 `offset` 增量读取。
236
+ - `browser` 的页面会话同样跨调用存活,截图经多模态通道回灌给模型,顺带返回最近的 console、页面报错和失败请求。
237
+ - 安全默认:`browser` 只允许 `http/https` 的 `localhost / 127.0.0.1 / ::1`,拒绝 `file:` 与带凭据的 URL;需要访问远端时显式设 `MOCODE_BROWSER_ALLOW_REMOTE=true`。`dev_server` 执行任意命令,风险等级与 `run_command` 同为 dangerous,执行前需用户确认。
238
+ - 两者在 plan 模式下均被禁用;mocode 退出时会树杀后台进程并关闭浏览器。
239
+ - 浏览器二进制不随 npm 包分发,首次使用前需 `npx playwright install chromium`。
240
+
225
241
  5 个 `memory_*` 工具受启动时 `MEMORY_ENABLED=true` 总开关控制;运行时切换用 `/memory_switch`(需重启 REPL,刻意为之,见下「项目记忆」小节区分 Tier-1 / Tier-2)。
226
242
 
227
243
  ## 斜杠命令
@@ -230,6 +246,7 @@ agent 工作在**启动时所在的工作目录**——想让它操作某个项
230
246
  | --------------- | -------------------------------------------------- |
231
247
  | `/exit` `/quit` | 退出 mocode |
232
248
  | `/clear` | 清空历史(保留系统提示)+ 清屏 |
249
+ | `/image` | 附加本地图片到下一条消息;支持 `list` / `clear` |
233
250
  | `/context` | 显示上下文用量条(token / 消息数 / 估算或实测) |
234
251
  | `/skills` | 列出已发现的 skill |
235
252
  | `/compact` | 压缩历史(可带焦点 `/compact …`) |
@@ -273,18 +290,9 @@ mocode 自动扫描以下目录的 skill(每个 skill 是 `<name>/SKILL.md`,带
273
290
 
274
291
  skill 的 `description` 注入系统提示(渐进式披露第①层),模型只在任务相关时调 `use_skill` 加载完整正文(第②层)。用 `/skills` 查看已发现的 skill。
275
292
 
276
- ## 工作纪律(4 阶段 — Build-and-Self-Verify)
277
-
278
- 每个 coding 任务必须按顺序走完 4 个阶段。跳过/合并 = 失败模式 —— system prompt 每轮注入这段纪律(见 `src/agent/work-discipline.ts`):
279
-
280
- 1. **Plan & Discover** — 用一句话复述目标,明确验收信号(测试名/命令输出/文件存在/行为变化);写代码前先读相关代码;不可逆选择(删除/公开 API/权限)用 `ask_human` 主动澄清。
281
- 2. **Build** — 用最小改动满足 spec,不夹带无关重构;新/改行为必须有对应测试 —— 目标里的 "should" 是义务。
282
- 3. **Verify** — 跑**真实**可执行验证(typecheck/项目 test 命令/聚焦 reproducer),读完整输出,与 **spec** 对比,不是与自己的 diff 对比。
283
- 4. **Fix** — 任何失败 → 回 spec,不是回 diff;修完重跑 Phase 3 全程;同工具同参数 3 次连续失败后**换思路**(换工具/换不变量/`ask_human`)。
284
-
285
- **硬规则:** "我读代码觉得对"不是完成信号。任务完成的唯一判据:对 spec 的可执行验证已跑过、完整输出已读、结果与 spec 匹配 —— 最终回复里**显式给出证据**(哪个命令、哪段输出、对应 spec 哪一行)。
293
+ ## 工作纪律
286
294
 
287
- 段内措辞按 `model_family`(anthropic / openai / qwen)轻量适配,贴合各 base model 的指令遵从习惯。4 份共用同一套 4 阶段结构 + 英文纪律文本,只在首句与 `[model: X]` 标签上区分;用户语言偏好由现有 i18n 段负责。
295
+ system prompt 提供轻量建议而不是框架硬门:只检查支持下一步决策的内容,做最小完整改动,避免重复读取,并诚实说明不确定性。agent 自主决定是否需要验证以及验证范围;框架不会因为未验证阻止完成或追加模型轮次。
288
296
 
289
297
  ## 项目记忆(MOCODE.md)
290
298
 
@@ -301,4 +309,4 @@ npm run typecheck # tsc --noEmit
301
309
 
302
310
  ## 可后续扩展
303
311
 
304
- MCP 工具集成、更细粒度的 capability 资源锁、真·worktree 隔离的子 agent 模式。当前版本已是流式、思考可见、可回滚的终端编码 agent:20 个工具、工作记事本规划、跨会话记忆、能力感知工具调度、共享工作区串行子 agent、可选桌宠。
312
+ MCP 工具集成、更细粒度的 capability 资源锁、真·worktree 隔离的子 agent 模式。当前版本已是流式、思考可见、可回滚的终端编码 agent:内置文本与视觉工具集、工作记事本规划、跨会话记忆、能力感知工具调度、共享工作区串行子 agent、可选桌宠。