Repository navigation
v1.0.0
1.0.0 - 2026-11-01
MWF 1.0 是从零重写的版本(v1 分支,PR #36–#49),相对 0.3.1 / 0.4.0 有破坏性变更,见下。 / MWF 1.0 is a ground-up rewrite (the v1 branch, PRs #36–#49) with breaking changes against 0.3.1 / 0.4.0, listed below.
范围 / Scope (PR #36–#49):core 层(#36、#37)、CLI 层(#38、#40)、MCP 层(#39)、hooks 层与 Codex / Claude Code 适配器(#41、#42)、recall 相关度阈值(#43)、mwf install|uninstall --harness codex(#44)、--harness claude(#45)、锁测试时序修复(#46)、--harness pi(#47)、安全写入目标 F1/F2/F4(#48)、Codex /hooks 信任提示(#49)。 / Scope: core (#36, #37), CLI (#38, #40), MCP (#39), hooks and the Codex / Claude Code adapters (#41, #42), recall relevance threshold (#43), mwf install|uninstall --harness codex (#44), --harness claude (#45), lock-test timing fix (#46), --harness pi (#47), safe write targets F1/F2/F4 (#48), Codex /hooks trust hint (#49).
要求 / Requirements:Node ≥ 22.19.0(node:sqlite;package.json 的 engines)。 / Node >= 22.19.0 (node:sqlite; engines in package.json).
破坏性变更 / Breaking
- 相对 0.3.1(及 0.4.0):包的根入口
.(dist/core.js)被移除,exports改为./core、./cli、./mcp、./hooks,mwf可执行文件由dist/cli.js改为dist/bin/mwf.js;0.x 的.mwf/数据、receipt 与集成不会被迁移;1.0 没有mwf update(推迟到 1.1):更新时安装新包后重新运行mwf install --harness …。 / Against 0.3.1 (and 0.4.0): the root entry.(dist/core.js) is removed andexportsis now./core,./cli,./mcp,./hooks; themwfexecutable moves fromdist/cli.jstodist/bin/mwf.js; 0.x.mwf/data, receipts and integrations are not migrated; there is nomwf updatein 1.0 (deferred to 1.1): install the new package and runmwf install --harness …again. - 从零重写,不复用也不迁移 0.x 代码、
.mwf/数据或集成回执。新的分层目录为src/core、src/cli、src/mcp、src/hooks(另有纯文本的src/skills);目前已实现src/core、src/cli、src/mcp、src/hooks与src/lifecycle(Codex、Claude Code 与 Pi 的 install / uninstall)。 - Rewritten from scratch: no 0.x code, data or receipt migration. Layered layout
src/core,src/cli,src/mcp,src/hooks;core,cli,mcp,hooksandlifecycle(Codex, Claude Code and Pi install / uninstall) are implemented so far.
新增 / Added
-
PR4b
mwf install|uninstall --harness codex(新增src/lifecycle层;yubai 批准计划与 D1–D6,Aegis 补充项 A1–A6):mwf install --harness codex [--dry-run] [--json] [--force-skills]只写用户级配置:①<CODEX_HOME 或 ~/.codex>/hooks.json里的三个 command hook(SessionStart,matcherstartup|resume|clear|fork;UserPromptSubmit;Stop;timeout: 5,Codex 默认 600 秒;compact不注册);② 技能(mwf、mwf-save、mwf-handoff、mwf-tidy)写到~/.agents/skills/<name>/SKILL.md(Codex 官方文档的用户级技能目录,在 HOME 下而不是 CODEX_HOME 下;~/.codex/skills已被官方标为遗留路径,不再使用——这与计划原文的<home>/skills不同,原因见 PR 说明),每个文件末尾带<!-- mwf-managed:<版本>:<sha256> -->标记;③ MCP 只通过codex mcp add mwf -- <node> <mwf.js> mcp/codex mcp remove mwf注册(用execFile传参数数组,不经 shell),mwf 从不直接编辑 config.toml。顺序:技能 → hooks.json → MCP;任一步失败不回滚已完成的步骤,报告会列出每一步状态并给出需用户自己执行的命令;卸载无状态,凭标记与 hook 命令的形状识别自己写的内容,只删这些,保留项目记忆.mwf/与所有备份。D3:--dry-run无需终端,不写任何东西、不运行会改动的 codex 命令。D4:不写任何 Codex 信任状态,安装后提示用户在 Codex 里运行/hooks审核并信任(信任按 hook 定义记录,hook 变更后需重新信任;Codex 在信任前不会执行这些 hook)。D6:要求 Codex ≥ 0.165.0。真实安装/卸载要求 stdin 与 stdout 同时是终端(CONFIRM_REQUIRES_TTY,没有任何标志或环境变量可绕过)。共享安全写入(src/lifecycle/safe-write.ts,4b' Claude 安装复用):realpath后只接受自己拥有的普通文件,且其目录归自己所有、非全局可写;临时文件O_EXCL|O_NOFOLLOW创建于真实文件同目录,fsync 后 rename,目录 fsync;写入前备份为唯一的<名>.mwf-bak-<UTC 时间>-<8 位十六进制>;读入时记录 dev/ino/大小/纳秒 mtime/sha256,rename 前再核对一次,变化即中止并保留对方写入的文件(CONCURRENT_MODIFICATION);hooks.json 必须是严格 JSON(注释、BOM、尾逗号、重复键一律拒绝并给出行列号,不做修复),只增删 mwf 自己的 handler,未知字段原样保留,并用“去掉 mwf 之后新旧文档深度相等”的差异守卫证明没有改动别的内容;幂等,重复安装不产生新备份。Aegis:A1 运行codex mcp add|remove前先备份 config.toml,运行后重新解析并核对只有mcp_servers.mwf变化(否则报CONFIG_CHANGED_UNEXPECTEDLY,不自动回滚,只给出备份路径);config.toml 无法解析时不运行 codex;features.hooks=false与内联[hooks]只警告。A2 所有备份均为 0600(与 umask 无关)。A3 属于他人的文件或目录、悬空链接、目录、FIFO、全局可写目录一律拒绝;符号链接(如 dotfiles 管理器)原样保留,改动写入链接指向的真实文件所在目录,备份也在那里。A4 技能文件记录 sha256,卸载时哈希不符(用户改过)或无标记的文件保留并在报告里说明,--force-skills才会在备份后覆盖/删除。A5 取不到或解析不了codex --version一律拒绝安装(不写任何东西),低于 0.165.0 也拒绝。A6 诚实说明:终端检查只能防止误操作(例如 agent 的 shell 工具或管道),不是安全边界——script之类的伪终端可以伪造 TTY。已知限制:重新序列化 hooks.json 会规范化排版(数字写法如1.0、单行数组会被展开),但内容经深度比较保证不变;只含 mwf handler 的 hooks.json 卸载后会删除文件(备份保留;无状态,无法知道文件是否由 mwf 创建);Codex 信任哈希的存储未验证;Codex ≥ 0.165 的真实宿主行为未在真机验证(本机只有 0.163.0,测试使用假的codex脚本并只用临时 CODEX_HOME / HOME);源码树运行(mwf.ts)会被 install 拒绝,必须用构建后的mwf.js。测试tests/lifecycle-*.test.ts(76 项)。 / PR4bmwf install|uninstall --harness codex(newsrc/lifecyclelayer; plan and D1–D6 approved by yubai, Aegis additions A1–A6): writes user-level config only: (1) three command hooks in<CODEX_HOME or ~/.codex>/hooks.json(SessionStart with matcherstartup|resume|clear|fork, UserPromptSubmit, Stop;timeout: 5against Codex's 600 s default;compactis not registered); (2) the skills (mwf,mwf-save,mwf-handoff,mwf-tidy) at~/.agents/skills/<name>/SKILL.md, Codex's documented user skills directory, which lives under HOME, not CODEX_HOME;~/.codex/skillsis marked legacy by the docs and is not used (this differs from the plan's<home>/skills; see the PR description), each file ending in a<!-- mwf-managed:<version>:<sha256> -->marker; (3) MCP only throughcodex mcp add mwf -- <node> <mwf.js> mcp/codex mcp remove mwf(execFilewith an argument array, no shell); mwf never edits config.toml itself. Order: skills, hooks.json, MCP; a failed step does not undo finished ones, the report lists every step and any command you must run yourself; uninstall is stateless, recognising what mwf wrote by marker and hook-command shape, removing only that and keeping project memory (.mwf/) and every backup. D3:--dry-runneeds no terminal, writes nothing and runs no codex command that changes anything. D4: no Codex trust state is written; after install you are told to review and trust the hooks with/hooksin Codex (trust is recorded per hook definition, a changed hook needs trusting again, and Codex does not run them before). D6: Codex 0.165.0 or newer. A real install or uninstall needs stdin AND stdout to be terminals (CONFIRM_REQUIRES_TTY; no flag or environment variable overrides it). Shared safe write (src/lifecycle/safe-write.ts, reused by the 4b' Claude install):realpath, only regular files owned by the current user in a directory owned by the user and not world-writable; temp file createdO_EXCL|O_NOFOLLOWin the real file's directory, fsynced, renamed, directory fsynced; a unique backup<name>.mwf-bak-<UTC time>-<8 hex>before any change; dev/ino/size/nanosecond mtime/sha256 are recorded at read time and checked again right before the rename, a change aborts and keeps the other writer's file (CONCURRENT_MODIFICATION); hooks.json must be strict JSON (comments, BOM, trailing commas, duplicate keys are refused with line and column, never repaired); only mwf's own handlers are added or removed, unknown fields are kept, and a difference guard (the old and new documents must be deeply equal once mwf's handlers are stripped) proves nothing else changed; idempotent, a repeat install makes no new backup. Aegis: A1 config.toml is backed up beforecodex mcp add|remove, re-parsed afterwards and checked to differ only inmcp_servers.mwf(otherwiseCONFIG_CHANGED_UNEXPECTEDLY, not auto-reverted, the backup path is printed); codex is not run when config.toml cannot be parsed;features.hooks=falseand inline[hooks]only warn. A2 every backup is 0600 whatever the umask. A3 files or directories owned by someone else, dangling links, directories, FIFOs and world-writable directories are refused; a symlink (e.g. a dotfiles manager's) is left as it is, the change goes to the real file's directory and so does the backup. A4 skill files carry a sha256; uninstall keeps and reports a file whose hash no longer matches (or has no marker),--force-skillsoverwrites or removes after a backup. A5 install is refused, writing nothing, whencodex --versioncannot be run or parsed, and below 0.165.0. A6 stated honestly: the terminal check only prevents accidents (an agent's shell tool, a pipe); it is NOT a security boundary, a pseudo-terminal such asscriptcan fake a TTY. Known limits: re-serialising hooks.json normalises layout (number spellings like1.0, one-line arrays are expanded) while the content is proven unchanged by deep comparison; a hooks.json that holds only mwf handlers is deleted on uninstall (backup kept; being stateless it cannot know who created the file); where Codex stores hook trust hashes is unverified; behaviour on a real Codex 0.165+ is unverified (this machine has 0.163.0; tests use a fakecodexscript and temporary CODEX_HOME / HOME only); a source-tree run (mwf.ts) is refused by install, the builtmwf.jsis required. Tests:tests/lifecycle-*.test.ts(76). -
PR4b'
mwf install|uninstall --harness claude(沿用 4b 的src/lifecycle;yubai 批准计划与 D1–D10,Aegis 条件 1–5):mwf install --harness claude [--dry-run] [--json] [--force-skills]只写用户级配置,路径以CLAUDE_CONFIG_DIR为准(设了就用它,没设才用~/.claude):①<配置目录>/settings.json的hooks里三个 exec 形式的 command hook(command为 node、args为[<mwf.js>, hook, <事件>, --host, claude],不经 shell;SessionStart matcherstartup|resume|clear|fork、UserPromptSubmit、Stop;timeout: 5;compact不注册);② 技能(mwf、mwf-save、mwf-handoff、mwf-tidy,工具名渲染为mcp__mwf__mwf_…)写到<配置目录>/skills/<name>/SKILL.md(Claude Code 自己的个人技能目录,不是共享的~/.agents/skills),带与 Codex 相同的mwf-managed哈希标记;③ MCP 只通过claude mcp add --transport stdio --scope user mwf -- <node> <mwf.js> mcp/claude mcp remove mwf --scope user(execFile参数数组,不经 shell),mwf 从不直接编辑.claude.json(只读它来判断 user 级mwf服务是否存在、是否是自己的;同名但不是 mwf 的服务不覆盖、不删除)。顺序与失败处理、--dry-run无需终端、TTY 门槛(CONFIRM_REQUIRES_TTY,不是安全边界)、--force-skills、卸载无状态且不删.mwf/与备份,均与 Codex 相同;安全写入、备份(0600)、符号链接、并发检测直接复用 4b 的safe-write/json-edit/skills-files,未改动。Aegis 条件:1)路径与 Codex 的CODEX_HOME一致,CLAUDE_CONFIG_DIR设了就整体(settings、skills、.claude.json)都在它下面,开源 issue #48448 报告在自定义CLAUDE_CONFIG_DIR下 user 级 MCP 服务可能显示但起不来,安装时给出警告,需在真机上用/mcp核实;2)A1 备份并核对的是 CLI 真正写入的那个文件(默认~/.claude.json,在~/.claude旁边而不是里面;设了CLAUDE_CONFIG_DIR则是$CLAUDE_CONFIG_DIR/.claude.json),运行claude mcp前备份(0600),运行后重新解析,只允许 user 级mcpServers.mwf变化,否则CONFIG_CHANGED_UNEXPECTEDLY、不自动回滚、给出备份路径;该文件不是严格 JSON 时不运行 claude;运行中的 Claude Code 会话也会改写这个文件,请先关闭;3)hook 身份要求args恰为[…/mwf.js, hook, session-start|prompt|stop, --host, claude](--host claude是硬条件),Codex 形式的 shell 命令 hook 或缺少--host claude的一律不认、不碰;4)settings.json必须是严格 JSON,拿掉 mwf 的 hook 之后新旧文档深度相等,其余键(permissions、env、未知键、他人的 hook)原样保留,永不写permissions(更不会有permissions.allow)与任何信任设置,"disableAllHooks": true只警告;卸载后即使只剩空对象也不删除settings.json(保留{},旧内容在备份里);5)claude --version取不到、没有输出、输出无法解析(要求形如2.1.314 (Claude Code))或低于 2.1.314 一律拒绝安装,不写任何东西,也不运行--version之外的 claude 命令(卸载不检查版本)。信任:Claude Code 在你于某个项目接受工作区信任提示后才会运行用户级 hook,安装后请开新会话。顺带说明(低优先级):Codex 技能所在的~/.agents/skills是共享的 agent-skills 目录,遵循同一约定的其他工具也能读到 mwf 的技能(技能文本里是 Codex 的工具名);Claude Code 不用这个目录。已知限制:未在真机验证 Claude Code(测试用假的claude脚本并只用临时 HOME / CLAUDE*CONFIG_DIR;测试服务器是 2.1.314,本机没有claude)、claude --version的确切文本只来自文档示例、2.1.314 以下的行为、CLAUDE_CONFIG_DIR下真实 CLI 的落点。claude mcp add|remove运行之后还会重读settings.json,除 mwf 自己的 hook 外有任何变化同样报CONFIG_CHANGED_UNEXPECTEDLY(不回滚,给出该文件的备份路径);所有CONFIG_CHANGED_UNEXPECTEDLY的提示文字里都带有「请先关闭所有正在运行的 Claude Code 会话」的说明。测试tests/lifecycle-claude.test.ts。 / PR4b'mwf install|uninstall --harness claude(reuses the 4bsrc/lifecyclelayer; plan and D1–D10 approved by yubai, Aegis conditions 1–5):mwf install --harness claude [--dry-run] [--json] [--force-skills]writes user-level config only, rooted atCLAUDE_CONFIG_DIR(used when set, else~/.claude): (1) three exec-form command hooks underhooksin<config dir>/settings.json(commandis node,argsis[<mwf.js>, hook, <event>, --host, claude], no shell; SessionStart matcherstartup|resume|clear|fork, UserPromptSubmit, Stop;timeout: 5;compactis not registered); (2) the skills (mwf,mwf-save,mwf-handoff,mwf-tidy, tool names rendered asmcp**mwf**mwf*…) at<config dir>/skills/<name>/SKILL.md, Claude Code's own personal skills directory, not the shared~/.agents/skills, with the samemwf-managedhash marker as Codex; (3) MCP only throughclaude mcp add --transport stdio --scope user mwf -- <node> <mwf.js> mcp/claude mcp remove mwf --scope user(execFilewith an argument array, no shell); mwf never edits.claude.json(it only reads it to see whether a user-scopemwfserver exists and whether it is its own; a server of that name that is not mwf is neither overwritten nor removed). Order and failure handling,--dry-runwithout a terminal, the terminal gate (CONFIRM_REQUIRES_TTY, not a security boundary),--force-skills, and a stateless uninstall that keeps.mwf/and all backups are the same as for Codex; safe writes, 0600 backups, symlink handling and concurrent-change detection reuse the 4bsafe-write/json-edit/skills-filesunchanged. Aegis conditions: 1) likeCODEX_HOMEfor Codex,CLAUDE_CONFIG_DIRwins when set and then everything (settings, skills,.claude.json) lives under it; open Claude Code issue #48448 reports that user-scope MCP servers under a customCLAUDE_CONFIG_DIRmay be listed but never started, so the install warns and/mcpmust be checked on a real machine; 2) A1 backs up and checks the very file the CLI writes (default~/.claude.json, beside~/.clauderather than in it;$CLAUDE_CONFIG_DIR/.claude.jsonwhen that is set): backed up (0600) beforeclaude mcpruns, re-parsed afterwards, and allowed to differ only in the user-scopemcpServers.mwfentry, otherwiseCONFIG_CHANGED_UNEXPECTEDLY, no automatic revert, the backup path printed; claude is not run when that file is not strict JSON; a running Claude Code session also rewrites it, so close sessions first; 3) hook identity requiresargsto be exactly[…/mwf.js, hook, session-start|prompt|stop, --host, claude](--host claudeis a hard condition), so a Codex-style shell-command hook or one without--host claudeis never recognised or touched; 4)settings.jsonmust be strict JSON and, once mwf's hooks are taken out, old and new documents must be deeply equal; every other key (permissions,env, unknown keys, other tools' hooks) is kept, mwf never writespermissions(let alonepermissions.allow) or any trust setting, and"disableAllHooks": trueis only a warning; uninstall never deletessettings.json, even when only an empty object is left (it keeps{}, the old text is in the backup); 5) install is refused, writing nothing and running no claude command except--version, whenclaude --versioncannot be run, prints nothing, prints something unparseable (it must look like2.1.314 (Claude Code)) or is below 2.1.314 (uninstall has no version check). Trust: Claude Code runs user-level hooks in a project after you accept its workspace trust prompt; start a new session after installing. Also (low priority):~/.agents/skills, where the Codex skills go, is the shared agent-skills directory, so other tools following the same convention can read the mwf skills too (their text names Codex tools); Claude Code does not use that directory. Known limits: Claude Code is unverified on a real machine (tests use a fakeclaudescript and temporary HOME / CLAUDE_CONFIG_DIR only; the test server has 2.1.314, this machine has noclaude), the exactclaude --versiontext comes from documentation examples, behaviour below 2.1.314, and where the real CLI writes underCLAUDE_CONFIG_DIR. Afterclaude mcp add|removeran,settings.jsonis re-read too and any change other than mwf's own hooks is likewiseCONFIG_CHANGED_UNEXPECTEDLY(not reverted, the file's backup path printed); everyCONFIG_CHANGED_UNEXPECTEDLYmessage tells the user to close running Claude Code sessions first. Tests:tests/lifecycle-claude.test.ts. -
PR4c
mwf install|uninstall --harness pi(沿用src/lifecycle;yubai 批准计划,D4=薄壳扩展、D15=1.0 不做mwf update、其余按计划,加 Aegis 条件 1–6 与两条细化):mwf install --harness pi [--dry-run] [--json] [--force-skills]只写用户级配置,路径以PI_CODING_AGENT_DIR为准(设了就用它,没设才用~/.pi/agent):① 生成的扩展<目录>/extensions/mwf.js(首行// mwf-managed:<版本>:<sha256>,路径以 JSON 字符串字面量写入且模板只做一次替换,路径里的引号、${}、占位符不会注入代码)是薄壳:不在进程内调用 mwf 代码,只用node:child_process.spawn(参数数组、不经 shell)运行mwf hook <session-start|prompt|stop> --host pi;Pi 的session_start(reason→startup/clear/resume/fork)、input(记录原始输入行,所以/mwf …与/skill:mwf…不触发召回)、before_agent_start(首个提示先发 SessionStart 再发 prompt,注入一条display:false的自定义消息)、agent_before_settle(仅outcome=completed、非continue、canContinue不为 false、有 session id 时,每个用户提示最多让 Stop 继续一次,返回追加的custom_message条目与continue:true);每个 hook 5 秒预算,失败不注入任何东西;② 命令/mwf init|status|recall <查询>|save [文本]|handoff|tidy:status/recall运行 mwf CLI,结果用一次性的ctx.ui.notify显示(不写入会话、不进入模型),无 UI 时status退回为一条固定指令;其余命令发送固定指令让代理调用对应技能/MCP 工具;③ 技能(工具名渲染为mcp__mwf__mwf_…)写到<目录>/skills/<name>/SKILL.md(Pi 自己的目录,不是共享的~/.agents/skills);④ MCP 只通过pi mcp add mwf --exposure direct --description … -- <node> <mwf.js> mcp/pi mcp remove mwf(execFile参数数组),mwf 从不直接编辑mcp.json,也不动 Pi 的settings.json。新增src/hooks/pi.ts(Pi 适配器:Stop 用decision:block+reason,turn 键用扩展给出的prompt_id=<session>:<序号>)、src/lifecycle/pi.ts、src/lifecycle/pi-extension.ts;renderForHost对pi与claude一样渲染mcp__mwf__名(按 Pi 1.4.0 源码核实);mwf hook --host pi选择 Pi 适配器。Aegis 条件与细化:1)版本检查——pi --version的整行必须匹配^\d+\.\d+\.\d+$(可含一个结尾换行),不接受前缀/后缀(如-rc.1)/多行,低于 1.4.0 或无法解析一律拒绝且不运行--version之外的 pi 命令;2)A1 备份并核对的是 CLI 真正写入的mcp.json(PI_CODING_AGENT_DIR优先),运行pi mcp前备份(0600、放在真实文件旁),运行后重新解析,只允许mcpServers.mwf变化,否则CONFIG_CHANGED_UNEXPECTEDLY、不回滚、给出备份路径,并提示先关闭所有运行中的 Pi 会话;该文件不是严格 JSON(含 BOM,尽管 Pi 本身容忍 BOM)时不运行 pi,给出手动命令;3)MCP 条目只有在 stdio、args为[…/mwf.js, mcp]且exposure恰为"direct"时才算“我们的、已是最新”;缺少exposure(Pi 读作codemode,工具不会声明给模型)或为其他值的我们的条目走更新/替换路径(pi mcp add按名字替换);同名但不是 mwf 的条目不碰、给出手动命令;4)扩展带哈希标记,不是 mwf 写的或被用户改过的mwf.js保留并报告(--force-skills在 0600 备份后覆盖/删除),mwf 自己的旧版本直接替换;5)扩展以用户权限运行,安装与文档都明说;6)卸载只删 mwf 写的东西、不用版本检查,旧的无exposure条目也能删,保留.mwf/与备份。技能冲突(D9,细化 2):~/.agents/skills里同名的 Codex 技能(裸工具名)安装时只警告、永不修改;警告与文档都说明:Pi 的技能优先级为项目.pi/skills→ 项目及各级祖先目录的.agents/skills→~/.pi/agent/skills→~/.agents/skills,因此项目自己或祖先目录.agents/skills里同名的 mwf 技能优先级更高、会覆盖这里安装的技能(mwf 不扫描项目)。1.0 不提供mwf update(推迟到 1.1):更新就是装新包后重新运行mwf install --harness …。已知限制:未在真机验证 Pi(测试用假的pi与扩展替身,测试服务器是 1.4.0)、Pi 其他版本、多来源同名技能/扩展时真实 Pi 的行为、pi mcp add非原子写入时与运行中会话的竞争。测试tests/lifecycle-pi.test.ts、tests/pi-extension.test.ts、tests/pi-hooks.test.ts,假pi在tests/helpers/fake-pi.ts。 / PR4cmwf install|uninstall --harness pi(reusessrc/lifecycle; plan approved by yubai, D4 = thin-shell extension, D15 = nomwf updatein 1.0, the rest per the plan, plus Aegis conditions 1–6 and two refinements):mwf install --harness pi [--dry-run] [--json] [--force-skills]writes user-level config only, rooted atPI_CODING_AGENT_DIR(used when set, else~/.pi/agent): (1) a generated extension<dir>/extensions/mwf.js(first line// mwf-managed:<version>:<sha256>; paths are baked in as JSON string literals and the template is substituted in one pass, so quotes,${}or placeholders in a path cannot inject code) that is a thin shell: it never calls mwf code in-process, it only runsmwf hook <session-start|prompt|stop> --host pithroughnode:child_process.spawn(argument array, no shell); it uses Pi'ssession_start(reason→startup/clear/resume/fork),input(remembers the raw line, so/mwf …and/skill:mwf…are not recalled for),before_agent_start(the first prompt sends SessionStart and then prompt, and injects onedisplay:falsecustom message) andagent_before_settle(only foroutcome=completed, not alreadycontinue,canContinuenot false and a session id present, Stop may continue at most once per user prompt, by returning an appendedcustom_messageentry andcontinue:true); each hook has a 5 s budget and a failure injects nothing; (2) the command/mwf init|status|recall <query>|save [text]|handoff|tidy:status/recallrun the mwf CLI and show the result with a transientctx.ui.notify(never stored in the session, never sent to the model), and without a UIstatusfalls back to a fixed instruction; the others send a fixed instruction that makes the agent use the matching skill / MCP tool; (3) the skills (tool names rendered asmcp__mwf__mwf_…) at<dir>/skills/<name>/SKILL.md, Pi's own directory, not the shared~/.agents/skills; (4) MCP only throughpi mcp add mwf --exposure direct --description … -- <node> <mwf.js> mcp/pi mcp remove mwf(execFilewith an argument array); mwf never editsmcp.jsonand never touches Pi'ssettings.json. New:src/hooks/pi.ts(the Pi adapter: Stop answersdecision:block+reason, and the turn key is theprompt_idthe extension sends,<session>:<counter>),src/lifecycle/pi.ts,src/lifecycle/pi-extension.ts;renderForHostrendersmcp__mwf__names forpias forclaude(checked against the Pi 1.4.0 sources);mwf hook --host piselects the Pi adapter. Aegis conditions and refinements: 1) version check: the WHOLEpi --versionoutput must match^\d+\.\d+\.\d+$(one trailing newline allowed), no prefix, no suffix such as-rc.1, no extra lines; below 1.4.0 or unparseable is refused and no pi command other than--versionis run; 2) A1 backs up and checks the verymcp.jsonthe CLI writes (PI_CODING_AGENT_DIRwins): backed up (0600, beside the real file) beforepi mcpruns, re-parsed afterwards, allowed to differ only inmcpServers.mwf, otherwiseCONFIG_CHANGED_UNEXPECTEDLY, no revert, the backup path printed, and a hint to close every running Pi session; when the file is not strict JSON (a BOM too, although Pi itself tolerates one) pi is not run and the manual command is printed; 3) an MCP entry is "ours and current" only when it is stdio, itsargsare[…/mwf.js, mcp]and itsexposureis exactly"direct"; an entry of ours with a missingexposure(Pi reads it ascodemode, so the tools are not declared to the model) or another value goes through the update/replace path (pi mcp addreplaces by name); an entry of that name that is not mwf is left alone with the manual command; 4) the extension carries a hash marker: amwf.jsmwf did not write or that was edited is kept and reported (--force-skillsoverwrites / removes it after a 0600 backup), and an older file of mwf's own is replaced; 5) the extension runs with the user's permissions, which install output and the docs say plainly; 6) uninstall removes only what mwf wrote, needs no version check, can remove an older entry withoutexposure, and keeps.mwf/and all backups. Skill conflict (D9, refinement 2): a same-named Codex skill (bare tool names) in~/.agents/skillsonly produces a warning and is never modified; the warning and the docs say that Pi's skill priority is a project's.pi/skills, then a project's and every ancestor directory's.agents/skills, then~/.pi/agent/skills, then~/.agents/skills, so a same-named mwf skill in a project's own or an ancestor's.agents/skillshas higher priority and overrides the one installed here (mwf does not scan projects). There is nomwf updatein 1.0 (deferred to 1.1): to update, install the new package and runmwf install --harness …again. Known limits: Pi is unverified on a real machine (tests use a fakepiand a stub extension host; the test server has 1.4.0), other Pi versions, how a real Pi resolves a same-named skill or extension from several sources, and the race ofpi mcp add(a non-atomic write) with a running session. Tests:tests/lifecycle-pi.test.ts,tests/pi-extension.test.ts,tests/pi-hooks.test.ts; the fakepiistests/helpers/fake-pi.ts. -
Claude Code (F4):
mwf install --harness claudetolerates exactly nine first-run keys that Claude Code itself adds to a.claude.jsonthat did not exist (only when absent before and added by the run); any changed value or deleted key, userID and machineID included, is still refused. Claude's ownbackups/.claude.json.backup.<ms>is neither checked nor removed. Claude 首次运行键白名单(F4)。 -
行为变更(F1,Aegis 非阻塞项):把
~/.agents、~/.pi(或其他宿主/技能目录)符号链接到家目录之外(例如 dotfiles 仓库)现在会被mwf install/mwf uninstall以UNSAFE_TARGET拒绝,不写任何文件;这些目录必须是家目录内的真实目录(家目录内部的符号链接仍可用)。UNSAFE_TARGET的文本与--json消息现在带一句提示:目录被符号链接到家目录之外(如 dotfiles)会被拒绝,请改为真实目录。仅文档与提示文字,无逻辑变更。 / Behaviour change (F1, Aegis non-blocking ask): symlinking~/.agents,~/.pi(or another harness or skills directory) outside the home directory, for example into a dotfiles repository, is now refused bymwf install/mwf uninstallwithUNSAFE_TARGET, and nothing is written; these must be real directories inside home (symlinks that stay inside home still work). TheUNSAFE_TARGETmessage, in text and--json, now carries a short hint: a directory symlinked outside home (such as a dotfiles repository) is refused and should be a real directory. Documentation and message text only; no logic change. -
Text output (F2): the code names (
UNSAFE_TARGET,CONFIG_CHANGED_UNEXPECTEDLY, ...) are now printed in the text report, equal to the--jsoncode. 文本输出(F2)现在也显示错误码名称。 -
Security (F1): install/uninstall now check every directory from the trust root (the user home, or the harness directory when it is outside home) down to each write target, by realpath: a symlinked skills root, an intermediate symlink, a dangling link, a link leaving the root, an other-writable ancestor, or a group-writable ancestor that is not a private group is refused with
UNSAFE_TARGETbefore anything is written (Codex, Claude Code and Pi; uninstall too). Directories above the root are not checked. 安全修复 F1:写入目标沿途的每一级目录都按 realpath 检查,不安全即以UNSAFE_TARGET拒绝。 -
Codex install hint (real-machine E4, Codex 0.166): Codex does not run newly installed hooks until the user reviews and trusts them with
/hooksin Codex, and withcodex execno hook fired at all.mwf install --harness codexnow leads its notes (textnote:line and thenotesarray of--json) with an explicit "Next step": hooks were written, but Codex requires trusting them via/hooksbefore they run, which also applies to non-interactivecodex exec;mwf install --helpand the readme say the same. Claude Code and Pi output is unchanged (tests assert the hint appears for Codex in text and--jsonand not for Claude or Pi). 真机 E4(Codex 0.166):Codex 在用户于 Codex 里运行/hooks审核并信任之前不会执行新装的 hook,codex exec下 hook 完全没有触发。mwf install --harness codex现在把明确的“下一步”放在 notes 最前(文本note:行与--json的notes):hook 已写入,但需先在 Codex 里用/hooks信任才会运行,对非交互的codex exec同样适用;mwf install --help与 readme 同步说明。Claude Code 与 Pi 输出不变(测试断言 Codex 的文本与--json含该提示,Claude 与 Pi 不含)。仅提示文字、文档与测试,无逻辑变更。 -
变更(yubai 批准,recall 相关度阈值)UserPromptSubmit 不再只因“有匹配”就注入:真机发现无关提示(“Reply with exactly the word READY…”)也会注入两条记忆(
with/the/and等停用词和短词命中记录正文)。现在 core 的recall新增可选min_relevance(整数 0..20,默认 0 = 不过滤,显式mwf_recall/mwf recall行为不变;非法值返回INVALID_ARGUMENT),CLI 与 MCP 同步;hook 读取status的hooks.recall_min_score([hooks] recall_min_score,默认 2,0 = 关闭过滤,非法值回退为 2 并由doctor报config_recall_min_score_invalid警告)后带上它。打分基于词项而非 bm25(小语料上 bm25 不可靠):内置英文停用词与少量中文疑问/口语词(为什么、怎么样……)不计分,少于 3 个字符的词不计分(白名单ai ci cd db go io ip js k8 ml os pr py qa rs tf ts ui ux vm按整词匹配,其中go io ip os pr至多计 1 分);每个不同的词,标题命中 2 分、仅正文命中 1 分;一段连续中文算一个词,且其不同的 3 字片段至少命中 2 个才计分(更严格的 CJK 规则,见 PR 说明,需 yubai 确认)。过滤发生在 scope 过滤与候选截断之前;只含停用词的查询直接返回空。已知限制:停用词表只有英文加少量中文口语词;2 个字的中文词(部署、迁移)无法单独命中(索引是 trigram);2 字符以内且不在白名单的技术词不计分;白名单内的 2 字符词(db、ci 等)不走 trigram 索引,而是对标题、正文与 scope 做子串扫描(按更新时间倒序、与其他候选共用上限,最多 200 条),因此只靠这类词匹配的记录在大型库里可能被较新的候选挤出,且这类词不参与 bm25 排序;打分时按整词匹配;只在正文出现一次的普通词(1 分)低于默认阈值 2;hook 每次提示多一次status调用(读锁,总锁等待仍不超过MAX_LOCK_WAITS)。测试tests/relevance.test.ts、tests/recall-threshold.test.ts。 / Change (approved by yubai, recall relevance threshold): UserPromptSubmit no longer injects on any match; a real-machine run injected two records for an unrelated prompt because stopwords and short words matched record bodies. Corerecallgains an optionalmin_relevance(integer 0..20, default 0 = no filter, so explicitmwf_recall/mwf recallare unchanged; invalid values areINVALID_ARGUMENT), mirrored in the CLI and MCP; the hook readshooks.recall_min_scorefromstatus([hooks] recall_min_score, default 2, 0 = filter off, an invalid value falls back to 2 anddoctorwarnsconfig_recall_min_score_invalid) and passes it. Scoring is term based, not bm25 (unreliable on small corpora): built-in English stopwords and a few Chinese question/filler words carry no weight, nor do words under 3 characters (allow-listai ci cd db go io ip js k8 ml os pr py qa rs tf ts ui ux vm, whole-token match, withgo io ip os prcapped at 1); each distinct word scores 2 for a title hit and 1 for a body-only hit; a run of Chinese counts as one word and only when at least 2 of its distinct 3-character pieces match (stricter CJK rule, flagged in the PR for yubai to confirm). The filter runs before the scope filter and the candidate cap; a query with only stopwords returns nothing. Known limits: English stopwords plus a few Chinese filler words only; 2-character Chinese words (部署, 迁移) cannot match alone (trigram index); technical words of 2 characters or fewer outside the allow-list carry no weight; allow-listed 2-character terms (db, ci, …) do not use the trigram index: they are found by a substring scan over title, body and scope (newest first, within the same 200-candidate cap as other terms), so in a large store a record that matches only such terms can be crowded out by newer candidates, and they do not take part in bm25 ranking; scoring itself matches them as whole tokens; an ordinary word found once in a body (score 1) is below the default 2; the hook makes one extrastatuscall per prompt (a read lock; total lock waits stay withinMAX_LOCK_WAITS). Tests:tests/relevance.test.ts,tests/recall-threshold.test.ts. -
变更(yubai 批准,PR #42)SessionStart
source=resume(Claude 与 Codex 适配器相同):宿主的 transcript 里已有概览,因此除非自上次为该 session 注入后记忆发生变化,否则不再重复注入(实测:两个宿主在 resume 时都会把概览多追加一份)。变化检测用概览内容的哈希(记录数与条目、handoff、trash 提示、警告的 sha256 前 32 位十六进制,不用 mtime),存入state.toml该 session 的overview字段,经现有setSession/runWrite路径原子写入(锁等待 200 ms,锁忙则不写、下次 resume 照常注入)。Aegis 要求:检测失败、state.toml缺失或损坏、无已存哈希、无有效 session id、哈希不同——一律注入(宁可重复也不跳过);startup/clear/fork/ 未知 / 缺省来源行为不变(注入、重置已召回列表并记录哈希);resume保留已召回列表;compact仍不注入。setSession新增可选overview(32 位十六进制,非法则拒绝),其他写入保留该字段。测试tests/hooks-resume.test.ts(22 项,两个宿主)。已知边角:若 resume 重新注入后写哈希失败,旧哈希保留,之后记忆恰好变回旧状态时会跳过注入(此时旧概览仍在 transcript 中)。 / Change (approved by yubai, PR #42): on SessionStartsource=resume(Claude and Codex adapters alike) the overview is no longer injected again unless memory changed since the last injection for that session (a real-machine run showed both hosts append a second copy on resume). Change detection is a content hash, not mtime: sha256 (first 32 hex) of the overview content (counts and entries, handoffs, trash note, warnings), stored asoverviewin the session'sstate.tomlentry through the existingsetSession/runWritepath (200 ms lock wait; a busy lock means nothing is stored, so the next resume injects). Aegis: a detection failure, a missing or corruptstate.toml, no stored hash, no valid session id or a different hash always injects (fail toward re-injecting);startup/clear/fork/ unknown / missing sources are unchanged (inject, reset the recalled list, store the hash);resumekeeps the recalled list;compactstill injects nothing.setSessiongains an optionaloverview(32-hex, invalid values rejected); other session writes keep it. Tests:tests/hooks-resume.test.ts(22, both hosts). Known corner: if the hash write fails after a re-inject, the older hash stays, and a later resume after memory returns exactly to that older state skips (the older overview is still in the transcript). -
PR4a.1 Claude Code hook 适配器(不含安装、不写任何用户配置)/ Claude Code hook adapter (no install, no config writes):
mwf hook <session-start|prompt|stop> --host claude,复用 4a 的 handlers;公共部分抽到src/hooks/json-host.ts,codex.ts变薄,新增claude.ts。与 Codex 的差异及处理(依据 https://code.claude.com/docs/en/hooks):① Stop 无turn_id、有prompt_id:回合键依次取prompt_id、last_assistant_message的哈希,皆无则放行;②stop_hook_active仍须恰为false且原子认领state.toml(Claude Code 自带 8 次连续上限为第三道保险);③ Stop 输出默认hookSpecificOutput.additionalContext(D2),--stop-style block切换为{decision:"block",reason};④ SessionStartsource:compact不注入,startup/clear/fork/未知/缺省注入并重置已召回列表,resume仅在概览变化时注入(见下一条)并保留已召回列表(D3);⑤ UserPromptSubmit 会收到用户键入的原始/skill args:/mwf、/mwf-…、/mwf:…直接跳过;⑥additionalContext超过 10,000 字符会被 Claude Code 改成文件路径:最坏情况低于 9,800,由测试覆盖;⑦ 工具名为mcp__mwf__mwf_<tool>(D8):新增renderForHost/CLAUDE_MCP_SERVER,renderSkillMd(skill, host?),只改写我们自己的文本(围栏内的记忆原文不改)。测试tests/claude-hooks.test.ts:各 source 夹具、stop_hook_active、prompt_id、畸形输入、输出大小、真实进程。未经真机验证(经 yubai 的 magpie 网关另行测试)。 /mwf hook <event> --host claudereuses the 4a handlers; shared code moved tosrc/hooks/json-host.ts,claude.tsadded. Differences from Codex and how each is handled: (1) noturn_idon Stop: key =prompt_id, else a hash oflast_assistant_message, else allow; (2)stop_hook_activemust still be exactlyfalseplus the atomicstate.tomlclaim (Claude Code's 8-continuation cap is a third guard); (3) Stop output defaults tohookSpecificOutput.additionalContext(D2),--stop-style blockselects{decision:"block",reason}; (4) SessionStartsource:compactinjects nothing,startup/clear/fork/ unknown / missing inject and reset the recalled list,resumeinjects only when the overview changed (see the next item) and keeps it (D3); (5) the raw/skill argsline reaches UserPromptSubmit:/mwf,/mwf-…,/mwf:…are skipped; (6) context over 10,000 characters becomes a file path in Claude Code: the worst case stays below 9,800, covered by a test; (7) tool names aremcp__mwf__mwf_<tool>(D8):renderForHost/CLAUDE_MCP_SERVER,renderSkillMd(skill, host?); only our own text is rewritten, never stored memory. Not verified on a real Claude Code yet (to be tested through the magpie gateway). -
PR4a hooks 层 / hooks layer(不含安装):
mwf hook <session-start|prompt|stop>(Codex 命令 hook,stdin 为宿主 JSON,stdout 一行 JSON,永远退出 0,不需要终端、从不--confirm);src/hooks(handlers、fence、Codex 适配器、监督进程 runner/worker、预算常量)、src/skills(技能与快捷命令文本的唯一来源:mwf、mwf-save、mwf-handoff、mwf-tidy;init/status/recall/save/handoff/tidy)、./hooks包导出;cli 新增getSession/setSession,src/mcp/index.ts把它们与confirmHost作为宿主辅助函数(不是工具)导出;state.toml的 session 条目新增stop_turn并保留未知字段;status返回hooks.stop,项目可用[hooks] stop = false关闭 Stop。不写任何用户配置、不含 install。 /mwf hook <event>: always exit 0, no terminal, never--confirm;src/hooks,src/skills, the./hooksexport; cligetSession/setSession, re-exported withconfirmHostfromsrc/mcp/index.tsas host helpers (not tools);stop_turnin the session entry (unknown fields preserved);statusreportshooks.stop. No user-config writes, no install. -
Aegis(PR4a 验收):① 注入围栏:每次调用生成 96 位随机分隔符(
<<<MWF-DATA-<nonce>…MWF-DATA-<nonce>>>>),数据里的控制/双向字符被清除、MWF-DATA与<<</>>>被改写,召回文本无法提前闭合围栏;注入有字符上限(session-start 8000、prompt 4000),按行截断并在围栏外写明[mwf: truncated, N more characters were left out …]。② Stop 防循环:宿主stop_hook_active必须恰为false,并且通过setSession({claim_stop_turn})在锁内原子地认领本回合(state.toml的stop_turn,走runWrite的同一写入路径:锁、intent、原子写、dedup);任一无法读取(缺字段、类型不对、状态文件损坏、锁忙、无 session)即放行、不继续;同一回合第二次一定放行;并发的三个认领只有一个成功。③ 4.5 秒预算含锁等待:所有 hook 锁等待 200 ms(读路径锁忙时直接用现有索引并标注可能过期,不恢复、不等待;写入锁忙则放弃),顺序 锁等待 < 2.5 s 软限(之后不再做可选写入)< 4 s 监督进程 SIGKILL < 5 s 宿主 timeout,三个事件同一预算;0.x #33(Stop 的 15 s 宿主超时与 14.5 s 自杀互相打架)由此消除:没有任何路径会因等锁被宿主杀掉,被杀的工作进程若已输出答案则答案仍被送达。④⑤⑥(符号链接安全写入、保留未知字段、唯一备份名、并发修改拒绝、install/uninstall 仅 TTY)属于 4b/4c;本 PR 的 state.toml 已保留未知字段,且没有任何 hook 写用户配置。 / Aegis: (1) per-invocation random fence + cleaned data + cap with an explicit truncated note; (2) Stop continues a turn only when the host saysstop_hook_active: falseAND an atomic claim under the lock via the normal write path succeeds; anything unreadable, busy or missing allows the stop; (3) lock waits 200 ms, busy reads serve the existing index, order lock waits < 2.5 s < 4 s kill < 5 s host timeout for every event (the 0.x #33 conflict is gone). Items 4–6 belong to 4b/4c. -
设计决定(yubai,PR4 计划 15 点,按推荐)/ Decisions (PR4 plan, 15 points as recommended):三个 hook 点、不做 compact hook;hook 只能经 MWF 写入路径写;入口文本经 hook 与 skill 提供,不写 AGENTS.md;
mwf hook只服务 Codex,Pi 用生成的进程内扩展(4c);session 映射在state.toml,宿主加载在host.local.toml;install 只写用户级配置、卸载无状态靠标记、install/uninstall 仅 TTY(4b/4c)。已知风险:stop_hook_active必须是布尔false,若宿主省略该字段 Stop 永远放行,需在 4b 真机确认;Codex 输出格式在 4b 之前未经真机验证。 / Known risks:stop_hook_activemust be exactlyfalse(a host that omits it never gets a Stop continuation; confirm in 4b); Codex output formats are unverified on a real host until 4b. -
PR3 MCP 层 / MCP layer:
src/mcp把 16 个 CLI 函数暴露为mwf_<name>工具,mwf mcp通过 stdio 提供服务(@modelcontextprotocol/server2.4.0,精确锁定;低层Server+serveStdio,错误沿用 CLI 的{ok,error}包络);结果为文本加structuredContent,失败带isError、retryable与hint;工具不接收项目路径,自服务器工作目录(或--cwd)向上查找.mwf/;同一服务器的写入串行执行;首次工具调用后登记宿主(--host,否则取客户端名);不捕获 SIGTERM,写入中途被杀留下的锁与 intent 由下一个进程恢复。 / MCP toolsmwf_<name>for the 16 CLI functions,mwf mcpover stdio (SDK 2.4.0 exact pin, low-levelServer, CLI envelope kept); text +structuredContent,isError/retryable/hinton failure; no project path argument; serialized writes; host registration after the first call; SIGTERM not trapped (the next process recovers lock + intent). -
设计决定(yubai,PR3):① 破坏性操作(forget、purge、compact、inbox discard)经 MCP 只预览、从不执行;MCP 工具不接收
confirm/preview_token,预览返回preview_token与execute_with(用户要在 shell 里运行的命令)。② shell 因此开放forget、purge、compact、inbox(list/accept/discard):不带--confirm只预览并打印 token;--confirm必须带--preview-token,在锁内重新校验哈希(PREVIEW_MISMATCH);只有--confirm报CONFIRM_REQUIRES_TOKEN,不删除任何东西。③request_id的生成移入cli.run(shell、MCP、hooks 共用,失败时在error.details.request_id回报;预览不带)。④ 项目根 = 运行init的目录,且其中必须有.git:在仓库子目录或没有.git时init拒绝(NOT_GIT_ROOT)、说明原因、不写任何文件;其他命令与 MCP 向上查找 init 创建的.mwf/。⑤recall/status/bootstrap/get的 MCP 描述注明“不改变记忆内容,但可能取锁并写.mwf/”。 / Decisions (yubai, PR3): destructive tools only preview over MCP (noconfirm/preview_token; the preview carriesexecute_with); the shell gainsforget,purge,compact,inboxwith the two-step--confirm --preview-tokenflow (bare--confirmis refused withCONFIRM_REQUIRES_TOKEN, the token is re-verified under the lock);request_idgeneration moved intocli.run;initonly at a git repository root (NOT_GIT_ROOT, nothing written), other commands walk up to the.mwf/; read tools' descriptions say they may take the lock and write.mwf/. -
设计决定(yubai,10-30):shell 的破坏性
--confirm(forget、purge、compact、inbox discard)只能由用户本人在交互式终端执行:process.stdin.isTTY与process.stdout.isTTY必须同时为真,否则返回新错误码CONFIRM_REQUIRES_TTY(退出码 1,消息要求用户自己在终端里运行),在读取记忆或取锁之前拒绝,不删除任何东西;预览(不带--confirm)不受影响。管道(echo y | mwf forget … --confirm …)、重定向、脚本和 agent 的 shell 工具因此都无法确认。测试用main的Io.tty参数注入,没有环境变量或标志可以绕过。MCP 的execute_with说明改为“用户在自己的终端里运行”,去掉了“或经宿主审批”的说法。已知限制:agent 可借script或伪终端(pty)获得 TTY,所以这只防止 agent 误执行,不防止有意绕过。 / Decision (yubai): a destructive shell--confirm(forget, purge, compact, inbox discard) runs only for the user in an interactive terminal: stdin AND stdout must both be TTYs, else the new errorCONFIRM_REQUIRES_TTY(exit 1; the message tells the user to run it themselves in a terminal) is returned before any memory is read or the lock is taken, and nothing is deleted; previews are unaffected. Pipes (echo y | mwf forget … --confirm …), redirects, scripts and an agent's shell tool cannot confirm. Tests injectIo.ttyas an argument; no environment variable or flag overrides it. The MCPexecute_withnote now says the user runs it in their own terminal (the "or after host approval" wording is gone). Known limitation: an agent can obtain a TTY withscriptor a pseudo-terminal (pty), so this only prevents accidental agent execution, not deliberate circumvention. -
SDK 注意(Aegis L1):MCP 层使用 SDK 的低层
Server(类型里标为 deprecated,建议用McpServer;我们选低层是为了沿用 CLI 的{ok,error}错误包络和自己的 JSON Schema 校验),@modelcontextprotocol/server精确锁定在 2.4.0;升级 SDK 时可能需要迁移(Server→McpServer),升级前先跑tests/mcp.test.ts。 / SDK note (Aegis L1): the MCP layer uses the SDK's low-levelServer, which is@deprecatedin the SDK's types (it recommendsMcpServer); we use it to keep the CLI's{ok,error}envelope and our own JSON-Schema validation.@modelcontextprotocol/serveris pinned to exactly 2.4.0 and may need a migration (Server→McpServer) when the SDK is upgraded; runtests/mcp.test.tsfirst. -
测试 / Tests:
--confirm无终端被拒且不删除、stdin 与 stdout 各自单独检查、真实进程用管道(echo y | …、yes | …、< /dev/null)被拒、真实伪终端里可执行(有script时)、预览无需终端;MCP 上非数字wait_ms被 schema 拒绝(Aegis L2)。 /--confirmrefused without a terminal and nothing deleted, stdin and stdout checked independently, real piped processes refused, executes in a real pty (wherescriptexists), previews need no terminal; a non-numericwait_msis rejected over MCP (Aegis L2). -
测试辅助 / Test hook:
MWF_FAILPOINT_STALL=<ms>让 failpoint 打印failpoint-stalled <name>并阻塞,而不是 SIGKILL,供 SIGTERM 测试使用。 /MWF_FAILPOINT_STALLstalls at a failpoint instead of SIGKILL, for the SIGTERM test. -
PR2 CLI 层 / CLI layer:
src/cli为每个命令提供一个结构化函数(init、bootstrap、recall、get、add、propose、edit、handoff、status、doctor、inbox、compact、reindex、forget、restore、purge;MCP 层日后映射为mwf_<name>),输入按 JSON Schema 子集校验(拒绝未知字段),自cwd向上查找项目,返回{ok,data}/{ok:false,error:{code,message,details}},永不抛出;mwf可执行文件(src/bin,只分发)仅开放只读的status/recall/doctor(--json、--cwd;退出码 0 成功、1 失败或 doctor 报错、2 用法错误),写操作只走 MCP;hook/mcp/install/uninstall/update不在本次构建内。tests/layers.test.ts强制各层只依赖紧邻的下一层。package.json新增bin与./cli导出。 -
设计决定(yubai,18:41 SGT):
recall --handoffs忽略--scope,handoff 不按 scope 过滤(仍按 query 与 status 过滤,排在匹配的记录之后);在 core 实现,CLI 与 MCP 一致;多维度 scope 规则保持不变。 / Decision (yubai):recall --handoffsis never scope-filtered (core, so CLI and MCP agree); the multi-dimension scope rule is unchanged. -
修复(Aegis):
recall在 scope 过滤之前就把候选截断到 200 条,--scope可能漏掉靠后的匹配;现在先按 scope 过滤再截断(无 scope 时仍最多 200 个候选)。shell 的 stdin(--body-file -)改为边读边按字节计数,超过 1 MB 立即中止(退出码 2),不再读完再检查。 / Fixes:recallapplies the scope filter before the 200-candidate cap; stdin is counted while streaming and aborted as soon as it passes 1 MB. -
设计决定(yubai,PR #38):①
mwfshell 另外开放add与handoff(read / save):参数或 stdin(--body-file -/--content-file -)输入,--json,退出码约定不变(0 成功、1 失败含秘密扫描拒绝、2 用法或无效输入);走与 MCP 相同的 core 写入路径(秘密扫描、request_id 幂等、handoff 版本检查),shell 始终发送并打印 request_id(失败时也打印,--json在error.details.request_id);其他写操作仍仅 MCP。②recall --scope只返回 scope 匹配的记录(无 scope 的记录不再返回):在 core 的scopeMatch统一修改,shell、CLI 函数与 MCP 行为一致;没有--scope时不过滤。③lockHeldWarnMs默认值保持 120 秒。④LOCK_LOST对该次调用是终止性的,调用方用同一个 request_id 重试,写入恰好生效一次(readme、--help已说明)。 -
Decisions (yubai, PR #38): the shell also exposes
addandhandoff read|save(flags or stdin,--json, same exit codes, same core write path incl. secret scan and request_id idempotency; the shell always sends and prints a request_id);recall --scopereturns only records whose scope matches (changed in corescopeMatch, so every layer agrees; unscoped records are no longer returned, no--scopemeans no filter);lockHeldWarnMsstays 120 s;LOCK_LOSTis terminal for the call and the caller retries with the same request_id. -
CLI 文档与提示:NOT_INITIALIZED 提示改为“通过 MCP 工具
mwf_init(或可用时的mwf install)初始化,shell 没有 init”;mwf --help与 readme 说明 status/recall 可能取项目锁并写.mwf/以恢复崩溃遗留的 intent、刷新过期索引,doctor 从不取锁、不写文件。 / CLI hint and docs: not-initialized points atmwf_init/mwf install; help and readme state that status and recall may take the lock and write to recover a crashed intent, while doctor never does. -
Locking / recovery (Aegis L1–L4):① doctor 报告“向前滚动时因文件已变化而跳过删除”(
rollforward_skipped,记录在机器本地的.mwf/recovery.local.json,30 天过期;文件消失后不再报告);② doctor 报告锁被活着的持有者持有过久(lock_held_long,lockHeldWarnMs默认 120 秒;锁里新增只在获取时写入的acquired);③ 记录并文档化“同主机名、不同 pid 命名空间”的容器可能误回收对方的锁:锁里记录pidns(Linux/proc/self/ns/pid),命名空间不同的持有者按异主机处理(仅按心跳超时回收);无法读取命名空间时(无 /proc、旧版锁)该风险仍在,见 readme「Locking」;④ 心跳发现锁已丢失时中止写入:写入在 intent 之前、每个目标之前、索引同步与 dedup 登记之前复核锁,丢失则以新错误码LOCK_LOST终止,不再写任何文件,残留 intent 由下一个持锁者恢复;定时心跳与beat()也会发现并终止。 -
Aegis L1–L4 (English): doctor reports roll-forwards that skipped a changed file and locks held too long; the same-hostname / different-pid-namespace hazard is documented and mitigated where
/procallows; a write whose lock was lost is aborted withLOCK_LOST. -
设计决定落地(core 跟进):① request_id 去重表移到机器本地的
.mwf/dedup.local.toml(被.mwf/*.local.*忽略,不入库;损坏时视为空并由 doctor 警告),state.toml只保留 session 映射;②runWrite内置秘密扫描,写入新引入疑似秘密(API key、令牌、私钥、JWT、带口令 URL、key = 随机值)时以SECRET_DETECTED拒绝,不落任何文件,错误只带规则/路径/行号和打码样本;只统计新引入的匹配,已有内容仍可 forget/purge/编辑其他字段;③inbox discard与 forget/compact/purge 一致,需 preview_token + confirm(edit仍非破坏性,仅哈希前置条件);④ 每次改动记录/handoff 的写入都在同一把锁、同一 intent(先写 index.md)内更新index.md。 -
恢复修复:index.md 是每个计划的第一个写入,崩溃后被丢弃的 intent 可能让它列出从未落盘的记录;现在恢复(任何非 none 的 intent 路径,含损坏的 intent)会在删除 intent 之前按磁盘上的记录重建 index.md,并且读操作在遇到“写入者已死”的遗留 intent 时不再走免锁快路径,而是先恢复;活着的写入者的 intent 不受影响。protocol.md 注明秘密扫描基于模式、并不穷尽(如
DB_PASS=...)。 -
Decisions landed (core follow-up): dedup table moved to machine-local
.mwf/dedup.local.toml; secret scanning insiderunWrite(SECRET_DETECTED, only newly introduced matches);inbox discardneeds preview_token + confirm;index.mdis refreshed by every record/handoff write inside the same lock/intent/recovery flow. -
src/core:.mwf/布局(config.toml、protocol.md、index.md、inbox.md、handoff/、memory/<五类>/、index.db、state.toml、host.local.toml、trash/)、init(git 模式 track/local)、bootstrap、recall、get、add、propose、edit(内容哈希前置条件)、handoff read/save(版本检查,冲突追加「并行更新」段)、status、doctor、inbox、compact、reindex、forget/restore/purge(30 天回收站)。 -
并发与崩溃安全:同目录临时文件 + fsync + rename + fsync 目录;O_EXCL 锁(pid/host/time/start;同主机仅在持有者 pid 确认已死、或进程启动时间不符(pid 复用,Linux 读 /proc//stat + boot_id)时回收,活着的同主机持有者无论多久都不回收,无 /proc 的平台退化为仅 pid 存活检查;异主机持有者按心跳超时(默认 30 秒)回收并由 doctor 报告;长操作(compact/reindex/purge 等)定期心跳刷新锁时间;回收守卫文件清理前复读 token 比对);forget/purge/compact 的多文件写入先写后删,崩溃后恢复时对已落盘的删除向前滚动,compact 的 preview_token 不含保留记录的 scope(只做幂等并集);request_id 幂等(intent → 原子写 → 登记 dedup → 删 intent,下次加锁恢复遗留 intent);forget/purge/compact 预览 + preview_token 确认。
-
Tests: multi-process writes, kill -9 at every failpoint, dedup, reindex equivalence, lock timeout / stale reclaim, reader-during-write, preview_token, gitignore modes.