@fanglinwei/agent-fit 0.7.1 → 0.7.3

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.
@@ -0,0 +1,20 @@
1
+ {
2
+ "name": "agent-fit",
3
+ "interface": {
4
+ "displayName": "Agent Fit"
5
+ },
6
+ "plugins": [
7
+ {
8
+ "name": "agent-fit",
9
+ "source": {
10
+ "source": "local",
11
+ "path": "./"
12
+ },
13
+ "policy": {
14
+ "installation": "AVAILABLE",
15
+ "authentication": "ON_USE"
16
+ },
17
+ "category": "Productivity"
18
+ }
19
+ ]
20
+ }
@@ -0,0 +1,34 @@
1
+ {
2
+ "name": "agent-fit",
3
+ "version": "0.7.3",
4
+ "description": "为 Codex 已获授权的子任务选择模型、推理强度和备用组合;需要 agent-fit CLI。",
5
+ "author": {
6
+ "name": "fanglinwei",
7
+ "url": "https://github.com/fanglinwei"
8
+ },
9
+ "homepage": "https://github.com/fanglinwei/agent-fit",
10
+ "repository": "https://github.com/fanglinwei/agent-fit",
11
+ "license": "MIT",
12
+ "keywords": [
13
+ "codex",
14
+ "subagents",
15
+ "model-routing",
16
+ "skills"
17
+ ],
18
+ "skills": "./adapters/codex/skills/",
19
+ "interface": {
20
+ "displayName": "Agent Fit",
21
+ "shortDescription": "按任务复杂度、作用域和预算选择子代理模型",
22
+ "longDescription": "提供 agent-fit Skill,查询已配置的档位,为已获授权的委派选择模型、推理强度和备用组合。使用前须安装 @fanglinwei/agent-fit CLI 并完成 setup;插件安装不会自动修改 Codex 配置。",
23
+ "developerName": "fanglinwei",
24
+ "category": "Productivity",
25
+ "capabilities": [
26
+ "Instructions"
27
+ ],
28
+ "websiteURL": "https://github.com/fanglinwei/agent-fit",
29
+ "defaultPrompt": [
30
+ "使用 Agent Fit 查看当前有效档位和委派规则。",
31
+ "使用 Agent Fit 为已获授权的子任务选择模型与推理强度。"
32
+ ]
33
+ }
34
+ }
package/README.md CHANGED
@@ -15,7 +15,7 @@ Agent Fit 将任务复杂度、模型档位和委派职责放进一套可查询
15
15
  - **配置与模型检测分开**:安装、切档和保存配置只处理本地文件。需要时手动查询目录或验证模型,网页检测前确认主组合和费用。
16
16
  - **可检查、可恢复**:提供状态诊断、职责核对、配置冲突保护及首次安装前的恢复基线;保留无关配置和管理区块之外的修改。
17
17
 
18
- 当前面向 **Codex**,需要 **Node.js 22+** 和支持独立角色 TOML 的 Codex 客户端。已在 macOS 与 Codex CLI 0.162.1 验证相关配置和账号接口,其他环境的验证范围见[实施验收记录](docs/implementation-review.md)。项目处于内测阶段,只处理当前格式与版本的配置。
18
+ 当前面向 **Codex**,需要 **Node.js 22+** 和支持独立角色 TOML 的 Codex 客户端。已在 macOS 与 Codex CLI 0.162.1 验证相关配置和账号接口,其他环境的验证范围见[实施验收记录](docs/implementation-review.md)。项目处于内测阶段,处理当前配置,并支持 0.7.1 旧目录布局的显式迁移。
19
19
 
20
20
  ## 快速开始
21
21
 
@@ -29,7 +29,11 @@ agent-fit setup --mode official
29
29
 
30
30
  npm 包名为 [`@fanglinwei/agent-fit`](https://www.npmjs.com/package/@fanglinwei/agent-fit),安装后的命令和 Skill 名为 `agent-fit`。
31
31
 
32
- **首次配置完成后重启 Codex。** 安装 npm 包本身不会修改 Codex;`setup` 才会写入 Skill、四个委派角色、AGENTS 管理区块和档位数据。默认目标为 `CODEX_HOME` 或 `~/.codex`,可通过 `--codex-home "/path/to/codex-home"` 指定独立目录。
32
+ **首次配置完成后重启 Codex。** 安装 npm 包本身不会修改 Codex;`setup` 才会写入四个委派角色、AGENTS 管理区块和档位数据,并在共享 Skill 不存在时安装规则。默认目标为 `CODEX_HOME` 或 `~/.codex`,可通过 `--codex-home "/path/to/codex-home"` 指定独立目录。
33
+
34
+ Skill 默认放在 `~/.agents/skills/agent-fit/`,可由 CCSwitch 统一管理。动态档位存于对应 home 的 `.agent-fit/current-mode.json`,多个 home 共用规则但配置独立。`status`、`explain` 和 `skill path` 只读;日常切档和 `restore` 不改写或删除共享 Skill。
35
+
36
+ 从 0.7.1 迁移时,先执行 `agent-fit setup --dry-run`,再执行 `agent-fit setup`。旧目录保留、移除或软链接到共享目录均可识别;迁移验证安装记录,冲突时保留现场。已有共享规则需要更新时,显式执行 `agent-fit skill update --dry-run` 和 `agent-fit skill update`。完整边界见[目录与迁移](docs/usage.md#skill-目录与旧安装迁移)。
33
37
 
34
38
  打开本地配置页面:
35
39
 
@@ -41,6 +45,19 @@ agent-fit serve --open
41
45
 
42
46
  日常全局、项目和会话切档,以及模型与 effort 调整无需重启;后续新任务读取新选择。更新基础 Skill、AGENTS 或角色职责,以及恢复原配置后仍需重启。
43
47
 
48
+ ## Marketplace 插件
49
+
50
+ 仓库同时提供 Codex marketplace 插件,直接复用现有 Skill:
51
+
52
+ - marketplace 清单:`.agents/plugins/marketplace.json`。
53
+ - 插件清单:`.codex-plugin/plugin.json`,通过 `skills` 指向 `adapters/codex/skills/`。
54
+ - 在 Codex 的插件管理中添加 GitHub 仓库 `https://github.com/fanglinwei/agent-fit` 作为 marketplace 来源,选择 **Agent Fit** 安装并启用。首次安装后重启 Codex,使插件 Skill 可被发现。
55
+ - 本地验证时可将当前仓库作为 marketplace 来源;清单中的 `source.path` 相对于仓库根目录解析。
56
+
57
+ 插件安装提供规则;运行依赖仍按上面的快速开始安装 `@fanglinwei/agent-fit` 并执行 `setup`。已有配置无需重新 setup。插件不会自动运行命令、切档、检测模型或修改账号。使用时可要求“使用 Agent Fit 查看当前有效档位”。
58
+
59
+ CLI setup 安装的共享 Skill 与插件中的 Skill 来自同一份源码,可能同时被发现;两者应保持同版本。插件通过插件管理更新,共享 Skill 通过 `agent-fit skill update` 更新。禁用或卸载插件只移除插件规则;如需移除 CLI 配置,仍须按下文恢复流程处理原绑定 home。
60
+
44
61
  ## 四种档位
45
62
 
46
63
  | 档位 | 使用方式 |
@@ -121,7 +138,7 @@ agent-fit models check --verify
121
138
 
122
139
  ## 委派规则如何生效
123
140
 
124
- `setup` 安装的 AGENTS 入口要求 Codex 启动时读取 `skills/agent-fit/SKILL.md`,并在创建、重试或切换子代理模型前重新核对规则与有效档位。主代理仍负责设计、集成、关键验证和最终结论。
141
+ `setup` 安装的 AGENTS 入口要求 Codex 启动时通过 `agent-fit skill path` 查找并读取规则,并在创建、重试或切换子代理模型前重新核对规则与有效档位。主代理仍负责设计、集成、关键验证和最终结论。
125
142
 
126
143
  共同规则包括先权衡委派收益与协调成本、保留用户授权和预算、区分复杂度与职责、明确独占写入范围、禁止递归委派,以及完成最小充分验证。质量升级与故障备用分别判断,初次派发、重试和接续共用每任务最多三次委派。
127
144
 
@@ -151,7 +168,7 @@ npm test
151
168
  npm pack
152
169
  ```
153
170
 
154
- 本地打包产物为 `fanglinwei-agent-fit-0.7.1.tgz`,可用 `npm install -g ./fanglinwei-agent-fit-0.7.1.tgz` 安装。浏览器集成使用已有 Playwright 与 Chrome,运行方法见[开发验证](docs/usage.md#开发验证)。唯一运行依赖为 [smol-toml](https://github.com/squirrelchat/smol-toml)。
171
+ 本地打包产物为 `fanglinwei-agent-fit-0.7.3.tgz`,可用 `npm install -g ./fanglinwei-agent-fit-0.7.3.tgz` 安装。浏览器集成使用已有 Playwright 与 Chrome,运行方法见[开发验证](docs/usage.md#开发验证)。唯一运行依赖为 [smol-toml](https://github.com/squirrelchat/smol-toml)。
155
172
 
156
173
  ## License
157
174
 
package/VERSION CHANGED
@@ -1 +1 @@
1
- 0.7.1
1
+ 0.7.3
@@ -6,7 +6,15 @@ license: MIT
6
6
 
7
7
  # Agent Fit
8
8
 
9
- Codex 启动后读取本 Skill;每次创建、重新委派或切换子智能体模型前,执行下面流程。新任务按下述作用域查询有效档位;[全局档位](references/current-mode.json) 仅代表全局基线。本 Skill 不指定主代理模型,不授予委派权限,不替代专业规则。
9
+ Codex 启动后读取本 Skill;每次创建、重新委派或切换子智能体模型前,执行下面流程。新任务通过绑定 Codex home 的 CLI 按下述作用域查询有效档位。本 Skill 不指定主代理模型,不授予委派权限,不替代专业规则。
10
+
11
+ 本目录只保存可共享的规则与说明,可由 CCSwitch 放在 `~/.agents/skills/agent-fit/`。当前档位、项目与会话配置属于各自 Codex home;全局快照存于 `<home>/.agent-fit/current-mode.json`,有效配置通过 `agent-fit explain` 查询。目录中遗留的 `references/current-mode.json` 是旧安装文件,不能作为当前配置。规则入口用 `agent-fit skill path --codex-home <绑定 home> --json` 查询;退出码为 0 且 `errors` 为空后读取 `data.path`。
12
+
13
+ ## Marketplace 插件前提
14
+
15
+ 通过 marketplace 安装本 Skill 后,仍需 Node.js 22+、`@fanglinwei/agent-fit` CLI 和已完成 `setup` 的目标 Codex home。插件安装仅提供规则,不自动安装 CLI、写入角色或切换档位。
16
+
17
+ 首次使用先确认 `agent-fit --version` 可用,再用 `agent-fit status --codex-home <绑定 home> --json` 检查配置。CLI 缺失或尚未配置时,说明缺少的前提并提供 README 中的安装与 setup 步骤;不凭预设猜测有效档位,不自动执行安装或 setup。用户已授权初始化时可按其范围完成配置。插件缓存中的规则由插件更新管理;`agent-fit skill update` 管理的是共享 Skill,不更新插件缓存。
10
18
 
11
19
  ## 卸载前恢复
12
20
 
@@ -1,6 +1,10 @@
1
1
  # Codex configuration
2
2
 
3
- 本工具管理四个 task_* 角色、此 Skill、全局档位、home 内的项目/会话配置及 AGENTS.md 中带 agent-fit 标记的区块。AGENTS 启动入口明确引用绑定 home 的 Skill;每次委派前必须按 Skill 检查。指令约束不等于宿主拦截器,原生 Skill 选择器发现与实际运行生效另行核验。
3
+ 本工具在绑定 home 内管理四个 task_* 角色、`.agent-fit/current-mode.json` 全局档位、项目/会话配置及 AGENTS.md 中带 agent-fit 标记的区块。共享 Skill 默认位于 `~/.agents/skills/agent-fit/`,只保存通用规则;AGENTS 和角色通过 `agent-fit skill path --codex-home <绑定 home> --json` 查询入口。每次委派前必须按 Skill 检查。指令约束不等于宿主拦截器,原生 Skill 选择器发现与实际运行生效另行核验。
4
+
5
+ - `setup --dry-run` 预览、`setup` 迁移旧安装。迁移核对原安装摘要、权限和档位归属,保留当前档位及各作用域选择;冲突时保留现场。旧目录已移走或仅保留指向共享目录的软链接均可识别。
6
+ - `status`、`explain`、`skill path` 只读;旧安装返回 `MIGRATION_REQUIRED`,不会在查询时迁移。
7
+ - `setup` 仅在共享 Skill 尚不存在时安装;已有文件通过 `skill update --dry-run` 预览和 `skill update` 显式更新。日常切档与 home 的 `restore` 不改写或删除共享 Skill。恢复旧安装前先迁移;共享 Skill 删除不属于 home 恢复。
4
8
 
5
9
  - setup 首次默认 official;内置档位命令与 id 均为 cut、official、high、fire;mode set 切换,mode create/configure 保存自定义档位。
6
10
  - status --details 查看规则、磁盘角色及潜在覆盖;mode show 与 explain 只预览,不委派。
package/bin/agent-fit.mjs CHANGED
@@ -9,6 +9,7 @@ const HELP = `agent-fit ${VERSION} — Codex 子代理委派配置
9
9
  用法:agent-fit <命令> [选项]。
10
10
 
11
11
  setup [--mode MODE] [--dry-run]
12
+ skill path | skill update [--dry-run]
12
13
  mode set MODE [--dry-run]
13
14
  mode clear [--dry-run]
14
15
  mode delete MODE [--dry-run]
@@ -45,6 +46,7 @@ const common = ['agent', 'codex-home', 'json'];
45
46
  const write = [...common, 'dry-run', 'expect-revision'];
46
47
  const scoped = ['scope', 'project', 'thread'];
47
48
  const commands = {
49
+ 'skill-path': common, 'skill-update': [...common, 'dry-run'],
48
50
  setup: [...write, 'mode'], set: [...write, ...scoped], clear: [...write, ...scoped], delete: [...write, ...scoped], list: [...common, ...scoped], show: [...common, ...scoped],
49
51
  create: [...write, ...scoped, 'from'], configure: [...write, ...scoped, 'level', 'model', 'effort', 'fallback-model', 'fallback-effort', 'clear-fallback', 'definition-stdin'],
50
52
  status: [...common, ...scoped, 'details'], explain: [...common, ...scoped, 'level', 'task', 'mode', 'role'],
@@ -72,6 +74,9 @@ export function parseCommand(argv) {
72
74
  action = positionals[1]; count = 2;
73
75
  if (!['set', 'clear', 'delete', 'list', 'show', 'create', 'configure'].includes(action)) throw argumentError('未知 mode 子命令。');
74
76
  if (!['list', 'clear'].includes(action) && (action !== 'show' || positionals[2] !== undefined)) { selector = positionals[2]; count = 3; }
77
+ } else if (action === 'skill') {
78
+ if (!['path', 'update'].includes(positionals[1])) throw argumentError('skill 仅支持 path 或 update。');
79
+ action = `skill-${positionals[1]}`; count = 2;
75
80
  } else if (action === 'models') {
76
81
  if (positionals[1] !== 'check') throw argumentError('models 仅支持 check。');
77
82
  count = 2;
@@ -153,12 +158,19 @@ function renderHuman(data) {
153
158
  }
154
159
  if (data.verification?.required) lines.push('fire:每个会话首次委派前须实际验证;失败时使用用户指定组合,否则继承父代理模型与推理强度。');
155
160
  lines.push(...data.warnings);
161
+ } else if (data.action === 'skill-update') {
162
+ lines.push(`共享 Skill:${data.path}`, `规则版本:${data.version} · ${data.result} · 变化文件:${data.changed_files.length}`);
163
+ if (data.result === 'preview') lines.push(...data.changed_files);
164
+ lines.push(data.restart.message);
165
+ } else if (data.path) {
166
+ lines.push(data.path);
156
167
  } else if (data.result) {
157
168
  lines.push(`操作:${data.action} · ${data.result} · ${data.configuration_status}`, `Codex home:${data.home}`, `档位:${data.mode?.name || '无'} · 变化文件:${data.changed_files?.length || 0}`);
158
169
  if (data.created_mode) lines.push(`已创建:${data.created_mode.name} (${data.created_mode.id}),${data.mode?.id === data.created_mode.id ? '已在当前作用域选择。' : '尚未设为当前档位。'}`);
159
170
  if (data.result === 'preview') lines.push(...(data.changes || []).map(change => `${change.action} ${change.path}`));
160
171
  if (data.custom_modes_removed?.length) lines.push(`清理自定义档位:${data.custom_modes_removed.join('、')}`);
161
172
  if (data.restart?.message) lines.push(data.restart.message);
173
+ if (data.shared_skill) lines.push(`共享 Skill:${data.shared_skill.path} · ${data.shared_skill.result}`);
162
174
  lines.push(...(data.warnings || []));
163
175
  } else if (data.modes) {
164
176
  lines.push(...data.modes.map(mode => `${mode.active ? '*' : ' '} ${mode.id} ${mode.name} ${mode.kind}`));
@@ -199,7 +211,14 @@ async function main() {
199
211
  return;
200
212
  }
201
213
  let data; let code = 0;
202
- if (action === 'status') {
214
+ if (action === 'skill-path' || action === 'skill-update') {
215
+ const { inspectSkill, updateSkill } = await import('../lib/skill.mjs');
216
+ if (action === 'skill-path') {
217
+ const skill = await inspectSkill(home);
218
+ if (!skill.path) throw Object.assign(new Error('未找到 agent-fit Skill;请执行 setup 安装。'), { code: 'SKILL_NOT_INSTALLED', exitCode: 1 });
219
+ data = { home, path: skill.path };
220
+ } else data = await updateSkill(home, { dryRun: options.dryRun, legacyState: (await installer.readSnapshot(home)).state });
221
+ } else if (action === 'status') {
203
222
  for (let attempt = 0; attempt < 2; attempt++) {
204
223
  data = await installer.statusReport(home, options);
205
224
  const related = await inspectProject(options.project || process.cwd());
package/docs/usage.md CHANGED
@@ -1,12 +1,12 @@
1
1
  # 使用说明
2
2
 
3
- `agent-fit` 0.7.1,npm 包名为 `@fanglinwei/agent-fit`,命令和 Skill 名仍为 `agent-fit`。首版支持 Codex;Node.js 22+。命令、网页和生成的 Skill 使用同一套档位数据。
3
+ `agent-fit` 0.7.3,npm 包名为 `@fanglinwei/agent-fit`,命令和 Skill 名仍为 `agent-fit`。首版支持 Codex;Node.js 22+。命令、网页和生成的 Skill 使用同一套档位数据。
4
4
 
5
5
  工具只处理当前格式与版本的配置;独立 home 全程使用显式指定的路径。
6
6
 
7
7
  ## 安装与配置
8
8
 
9
- 从 npm registry 安装,或在项目目录运行 `npm pack` 后使用 `npm install -g ./fanglinwei-agent-fit-0.7.1.tgz` 安装本地包。两种方式都需要 Node/npm。
9
+ 从 npm registry 安装,或在项目目录运行 `npm pack` 后使用 `npm install -g ./fanglinwei-agent-fit-0.7.3.tgz` 安装本地包。两种方式都需要 Node/npm。
10
10
 
11
11
  ```sh
12
12
  npm install -g @fanglinwei/agent-fit
@@ -22,12 +22,35 @@ npm install -g @fanglinwei/agent-fit && agent-fit setup --mode official
22
22
 
23
23
  目标目录优先级为 `--codex-home PATH`、`CODEX_HOME`、用户 `~/.codex`。空格路径需要 shell 引号。命令不会设置主代理模型、全局子代理默认、供应商、审批、沙箱、并发或子代理启用开关。
24
24
 
25
- Skill 名称为 `agent-fit`,调用为 `$agent-fit`,安装目录为 `skills/agent-fit`。npm 安装命令获取已发布版本;当前内测开发代码通过 `npm pack` 构建本地包。
25
+ Skill 名称为 `agent-fit`,调用为 `$agent-fit`,默认安装目录为 `~/.agents/skills/agent-fit/`。npm 安装命令获取已发布版本;当前内测开发代码通过 `npm pack` 构建本地包。
26
26
 
27
27
  首次 setup 默认官方(official);同版本重复 setup 保留当前选择与首次恢复基线。npm 安装没有 postinstall 配置动作。`--dry-run` 不创建目标 home、锁或状态文件。
28
28
 
29
29
  **首次安装、基础规则更新或恢复原配置后需要重启 Codex;日常档位切换与模型/effort 调整无需重启。** 全局角色配置在下一轮加载,项目与会话选择由后续新任务重新查询;已开始的任务继续使用原快照。工具不会自动重启或停止任务。
30
30
 
31
+ ## Skill 目录与旧安装迁移
32
+
33
+ 共享 Skill 保存通用规则和说明;每个 Codex home 的当前档位保存在 `.agent-fit/current-mode.json`,作用域、自定义档位、角色和恢复记录仍属于该 home。CCSwitch 同步规则时不再携带当前运行配置。旧共享目录中遗留的 `references/current-mode.json` 会保留,但迁移后不参与查询、切档或恢复。
34
+
35
+ 支持 0.7.1 的旧布局:Skill 留在 `<home>/skills/agent-fit/`、已搬到共享目录并移除旧位置、旧位置软链接到共享目录。新规则通过 CLI 解析入口,不在角色或 AGENTS 中写死 Skill 的绝对路径。
36
+
37
+ ```sh
38
+ agent-fit status --details --json
39
+ # MIGRATION_REQUIRED 表示旧布局;以上查询不会修改文件。
40
+ agent-fit setup --dry-run
41
+ agent-fit setup
42
+ # 普通 setup 不覆盖已有共享规则;更新规则须显式执行:
43
+ agent-fit skill update --dry-run
44
+ agent-fit skill update
45
+ agent-fit skill path --json
46
+ ```
47
+
48
+ 独立 home 在各命令中添加相同的 `--codex-home PATH`。迁移保留已部署的模型组合、自定义档位和项目/会话选择,不以新包内置预设替代旧快照。旧档位、规则、角色和权限须与原安装记录一致;两个位置内容存在无法确认的差异,或旧 Skill 有尚未恢复的安装前内容时,报告冲突并保留所有文件与恢复记录。
49
+
50
+ `setup` 仅在共享规则不存在时安装;已有规则的更新使用独立锁、内容摘要和逐文件安全回退,未登记的修改不会被覆盖。home 配置事务与共享规则安装是两个步骤;home 已写入但共享安装失败时,报告保留写入状态,修复目录后重试 `setup`。共享 Skill 根可解析符号链接,内部文件、状态、恢复记录与角色路径不跟随符号链接。两个 home 共用规则时,切档、配置和恢复互不改写对方的数据。
51
+
52
+ `restore` 只恢复当前 home 的运行配置和规则;共享 Skill 与迁移后保留的旧 Skill 资产由用户统一管理,不随某个 home 的恢复删除。恢复 0.7.1 旧布局前先执行上述迁移;共享 Skill 的删除属于单独的管理操作。
53
+
31
54
  ## 全局、项目与会话
32
55
 
33
56
  有效优先级为 **session > project > global**。每层选择完整 L1–L4,主组合与备用不跨层拼接。账号认证属于绑定 home;主会话自身模型不受影响。项目/会话数据保存在 home 的 `.agent-fit/scopes.json`,不写项目仓库。
@@ -143,8 +166,8 @@ agent-fit explain --level L4 --role task_review
143
166
  无需全局安装的 npm 查询,以及本地包查询:
144
167
 
145
168
  ```sh
146
- npm exec --package=@fanglinwei/agent-fit@0.7.1 -- agent-fit status --details
147
- npm exec --package="/path/to/fanglinwei-agent-fit-0.7.1.tgz" -- agent-fit status --details
169
+ npm exec --package=@fanglinwei/agent-fit@0.7.3 -- agent-fit status --details
170
+ npm exec --package="/path/to/fanglinwei-agent-fit-0.7.3.tgz" -- agent-fit status --details
148
171
  ```
149
172
 
150
173
  ## 委派收益检查
@@ -435,7 +458,7 @@ restore 后重启 Codex。它不会卸载 npm 工具、删除整个 home、清
435
458
 
436
459
  首次 setup 记录受影响文件的原存在状态与普通权限,仅允许接管同内容公开工具资产;AGENTS 只记录管理区块与校验元数据,不保存完整私有正文、config 或认证文件。同版本档位切换与自定义配置保留首次基线。
437
460
 
438
- 恢复清理本工具新增 Skill、四角色、规则区块、当前档位、全部自定义与元数据;保留用户原文件和后续标记外正文。只非递归删除本工具创建的空目录,home 与无关文件保留。冲突先完整预检,失败不猜测删除。
461
+ 恢复清理本 home 中本工具新增的四角色、规则区块、当前档位、全部自定义与元数据;保留共享 Skill、用户原文件和后续标记外正文。只非递归删除本工具创建的空目录,home 与无关文件保留。冲突先完整预检,失败不猜测删除。
439
462
 
440
463
  工具统一使用 Node.js 22+ 和 npm,不需要 Python;安装与配置入口为 `agent-fit setup`。
441
464
 
package/lib/codex.mjs CHANGED
@@ -106,7 +106,7 @@ export function safeJsonData(value) {
106
106
  return JSON.stringify(value).replace(/[<>`]/g, char => `\\u${char.charCodeAt(0).toString(16).padStart(4, '0')}`);
107
107
  }
108
108
 
109
- export async function renderPayload(home, mode) {
109
+ export async function skillAssets() {
110
110
  const skillRoot = path.join(PACKAGE_ROOT, 'adapters/codex/skills/agent-fit');
111
111
  const files = new Map();
112
112
  async function visit(directory, prefix = '') {
@@ -114,25 +114,30 @@ export async function renderPayload(home, mode) {
114
114
  if (entry.isSymbolicLink()) throw Object.assign(new Error('发布资产不允许符号链接。'), { code: 'INVALID_PACKAGE' });
115
115
  const relative = prefix + entry.name;
116
116
  if (entry.isDirectory()) await visit(path.join(directory, entry.name), relative + '/');
117
- else if (entry.isFile() && entry.name !== '.DS_Store') files.set(`skills/agent-fit/${relative}`, await readFile(path.join(directory, entry.name)));
117
+ else if (entry.isFile() && entry.name !== '.DS_Store') files.set(relative, await readFile(path.join(directory, entry.name)));
118
118
  }
119
119
  }
120
120
  await visit(skillRoot);
121
- const skillPath = path.join(home, 'skills/agent-fit/SKILL.md');
122
- const modePath = path.join(home, 'skills/agent-fit/references/current-mode.json');
121
+ return files;
122
+ }
123
+
124
+ export async function renderPayload(home, mode) {
125
+ const assets = await skillAssets(), files = new Map();
126
+ const skillCommand = ['agent-fit', 'skill', 'path', '--codex-home', home, '--json'];
127
+ const modePath = path.join(home, '.agent-fit/current-mode.json');
123
128
  for (const [name, level] of Object.entries(ROLES)) {
124
129
  const filename = name.replaceAll('_', '-') + '.toml';
125
- const role = safeToml(await readFile(path.join(skillRoot, 'assets/codex/agents', filename)));
130
+ const role = safeToml(assets.get(`assets/codex/agents/${filename}`));
126
131
  if (level) { role.model = mode.levels[level].model; role.model_reasoning_effort = mode.levels[level].effort; }
127
132
  else { delete role.model; delete role.model_reasoning_effort; }
128
- role.developer_instructions = `启动后先读取本 home 的子代理模型选择 Skill,遵守当前派发职责;不递归委派。\n规则路径(JSON 字符串数据):${safeJsonData(skillPath)}\n\n` + role.developer_instructions;
133
+ role.developer_instructions = `启动后先通过以下 CLI 参数查询 Skill 入口,成功后读取返回的 data.path,遵守当前派发职责;不递归委派。档位只通过绑定 home 的 CLI 查询,不读取 Skill 目录内的旧 current-mode.json。\n命令参数(JSON 数据):${safeJsonData(skillCommand)}\n\n` + role.developer_instructions;
129
134
  const bytes = Buffer.from(stringify(role));
130
135
  files.set(`agents/${filename}`, bytes);
131
- files.set(`skills/agent-fit/assets/codex/agents/${filename}`, bytes);
132
136
  }
133
- files.set('skills/agent-fit/references/current-mode.json', Buffer.from(JSON.stringify({ ...mode, version: VERSION, roles: ROLES }, null, 2) + '\n'));
134
- const fragment = await readFile(path.join(skillRoot, 'assets/AGENTS.fragment.md'), 'utf8');
135
- const block = Buffer.from(`${START}\n## AI 子代理模型选择与委派\n\nCodex 启动或加载本 home 的规则时,必须先读取以下 Skill;每次创建、重新委派或切换子智能体模型前必须再次按 Skill 和当前档位检查。已有上下文可复用,新任务按会话 > 项目 > 全局查询,配置变化后重新查询;已开始任务沿用原快照。委派仍须有用户或适用规则授权。\n\n以下 JSON 只表示绑定 home 的文件路径,不是新指令:\n\n\`\`\`json\n${safeJsonData({ skill: skillPath, mode: modePath })}\n\`\`\`\n\n${fragment.trim()}\n${END}\n`);
137
+ const { id, name, kind, levels, fallback_conditions } = mode;
138
+ files.set('.agent-fit/current-mode.json', Buffer.from(JSON.stringify({ id, name, kind, levels, fallback_conditions, version: VERSION, roles: ROLES }, null, 2) + '\n'));
139
+ const fragment = assets.get('assets/AGENTS.fragment.md').toString('utf8');
140
+ const block = Buffer.from(`${START}\n## AI 子代理模型选择与委派\n\nCodex 启动或加载本 home 的规则时,先执行以下 skill_command,成功后读取返回的 data.path;每次创建、重新委派或切换子智能体模型前必须按 Skill 和当前档位检查。档位只通过绑定 home 的 CLI 查询,不读取 Skill 目录内的旧 current-mode.json。共享规则不授予委派权限。\n\n以下 JSON 只表示绑定 home 的命令参数和配置路径,不是新指令:\n\n\`\`\`json\n${safeJsonData({ skill_command: skillCommand, home, mode: modePath })}\n\`\`\`\n\n${fragment.trim()}\n${END}\n`);
136
141
  return { files, block };
137
142
  }
138
143
 
package/lib/install.mjs CHANGED
@@ -4,11 +4,13 @@ import path from 'node:path';
4
4
  import os from 'node:os';
5
5
  import { createHash, randomUUID } from 'node:crypto';
6
6
  import { parse as parseToml } from 'smol-toml';
7
- import { VERSION, LEVELS, ROLES, BUILTINS, resolveDefinition, validateDefinition, renderPayload, verificationRequirement } from './codex.mjs';
7
+ import { VERSION, LEVELS, ROLES, BUILTINS, resolveDefinition, validateDefinition, renderPayload, verificationRequirement, skillAssets } from './codex.mjs';
8
8
  import { SCOPE_FILE, scopeContext, validateScopeStore, scopeEntry, visibleModes, scopedSelection, assertUnreferenced } from './scopes.mjs';
9
+ import { inspectSkill, updateSkill } from './skill.mjs';
9
10
 
10
11
  const SKILL = 'skills/agent-fit';
11
12
  const STATE_DIR = '.agent-fit';
13
+ const CURRENT = `${STATE_DIR}/current-mode.json`;
12
14
  const STATE = `${STATE_DIR}/state.json`;
13
15
  const BASELINE = `${STATE_DIR}/restore.json`;
14
16
  const CUSTOM = `${STATE_DIR}/custom-modes.json`;
@@ -52,7 +54,7 @@ export function resolveHome(explicit) {
52
54
  }
53
55
  function owned(relative) {
54
56
  if (typeof relative !== 'string' || !relative || relative.includes('\\') || /[\p{Cc}\p{Cf}]/u.test(relative) || relative.split('/').some(part => !part || part === '.' || part === '..')) return false;
55
- return relative === CUSTOM || relative === SCOPE_FILE || ROLE_PATHS.includes(relative) || relative.startsWith(`${SKILL}/`) && !relative.slice(SKILL.length + 1).split('/').some(part => part.startsWith('.'));
57
+ return relative === CURRENT || relative === CUSTOM || relative === SCOPE_FILE || ROLE_PATHS.includes(relative) || relative.startsWith(`${SKILL}/`) && !relative.slice(SKILL.length + 1).split('/').some(part => part.startsWith('.'));
56
58
  }
57
59
  function ownedDirectory(relative) {
58
60
  return ['agents', 'skills', SKILL, STATE_DIR].includes(relative) || relative.startsWith(`${SKILL}/`) && owned(`${relative}/entry`);
@@ -156,10 +158,12 @@ function validateState(bytes) {
156
158
  if (bytes === null) return null;
157
159
  const state = parseJson(bytes, 'STATE_INVALID', '安装记录无效或格式不支持。');
158
160
  const fields = ['schema_version', 'agent', 'version', 'files', 'rules_sha256', 'mode', 'mode_kind', 'instance_id', 'file_modes', 'rules_mode', 'restoration'];
159
- if (state?.schema_version !== 2 || state.agent !== 'codex' || !keys(state, fields) || !object(state.files) || !SHA.test(state.rules_sha256)) fail('STATE_INVALID', '安装记录无效或格式不支持。');
160
- if (state.version !== VERSION) fail('VERSION_MISMATCH', '配置版本与当前工具不一致;仅支持当前配置版本。未修改任何文件。');
161
+ if (![2, 3].includes(state?.schema_version) || state.agent !== 'codex' || !keys(state, fields, ['legacy_skill_files']) || !object(state.files) || !SHA.test(state.rules_sha256)) fail('STATE_INVALID', '安装记录无效或格式不支持。');
162
+ if (state.legacy_skill_files !== undefined && (!object(state.legacy_skill_files) || Object.entries(state.legacy_skill_files).some(([relative, digest]) => !relative.startsWith(`${SKILL}/`) || !owned(relative) || !SHA.test(digest)))) fail('STATE_INVALID', '旧 Skill 更新凭据无效。');
163
+ if (state.version !== VERSION && !(state.schema_version === 2 && state.version === '0.7.1')) fail('VERSION_MISMATCH', '配置版本与当前工具不一致;仅支持当前配置及 0.7.1 旧布局迁移。未修改任何文件。');
161
164
  for (const [relative, digest] of Object.entries(state.files)) if (!owned(relative) || !SHA.test(digest)) fail('STATE_INVALID', '安装记录含非法路径或摘要。');
162
- if (![...ROLE_PATHS, `${SKILL}/SKILL.md`, `${SKILL}/references/current-mode.json`].every(relative => Object.hasOwn(state.files, relative)) || typeof state.mode !== 'string' || !['builtin', 'custom'].includes(state.mode_kind) || !UUID.test(state.instance_id) || !object(state.file_modes) || !equal(Object.keys(state.files).sort(), Object.keys(state.file_modes).sort()) || !Object.values(state.file_modes).every(permission) || !permission(state.rules_mode)) fail('STATE_INVALID', '安装记录字段无效。');
165
+ const required = state.schema_version === 2 ? [`${SKILL}/SKILL.md`, `${SKILL}/references/current-mode.json`] : [CURRENT];
166
+ if (state.schema_version === 3 && Object.keys(state.files).some(relative => relative.startsWith(`${SKILL}/`)) || ![...ROLE_PATHS, ...required].every(relative => Object.hasOwn(state.files, relative)) || typeof state.mode !== 'string' || !['builtin', 'custom'].includes(state.mode_kind) || !UUID.test(state.instance_id) || !object(state.file_modes) || !equal(Object.keys(state.files).sort(), Object.keys(state.file_modes).sort()) || !Object.values(state.file_modes).every(permission) || !permission(state.rules_mode)) fail('STATE_INVALID', '安装记录字段无效。');
163
167
  const restore = state.restoration;
164
168
  if (!keys(restore, ['status', 'baseline_sha256']) || restore.status !== 'available' || !SHA.test(restore.baseline_sha256)) fail('STATE_INVALID', '恢复状态字段无效。');
165
169
  return state;
@@ -197,28 +201,51 @@ async function lockExists(home) {
197
201
  await checkPath(home, STATE_DIR);
198
202
  return (await statOrNull(path.join(home, LOCK))) !== null;
199
203
  }
204
+ async function skillInspection(home) {
205
+ try { return await inspectSkill(home); }
206
+ catch (error) {
207
+ if (!['UNSAFE_PATH', 'SKILL_CONFLICT', 'ENOENT', 'EACCES', 'EPERM'].includes(error.code)) throw error;
208
+ return { path: null, roots: [], assets: await skillAssets(), revision: hash(error.code), error: error.code };
209
+ }
210
+ }
200
211
  async function collect(home, { ignoreLock = false } = {}) {
201
212
  if (!ignoreLock && await lockExists(home)) fail('BUSY', '配置写入锁存在;请等待写入完成后重试。');
213
+ const skill = await skillInspection(home), legacyFiles = new Map(), migrationConflicts = [];
202
214
  const observedFiles = new Map(), observedDirectories = new Map();
203
- const file = async relative => { if (!observedFiles.has(relative)) observedFiles.set(relative, await observe(home, relative)); return observedFiles.get(relative); };
215
+ let state;
216
+ const file = async relative => {
217
+ if (relative.startsWith(`${SKILL}/`)) {
218
+ if (!legacyFiles.has(relative)) {
219
+ const name = relative.slice(SKILL.length + 1), expected = state?.files[relative];
220
+ const candidates = skill.roots.map(root => root.files.get(name)).filter(value => value && value.bytes !== null);
221
+ for (const value of candidates) if (expected && hash(value.bytes) !== expected && !skill.assets.get(name)?.equals(value.bytes)) migrationConflicts.push(path.join(home, relative));
222
+ const value = candidates.find(value => hash(value.bytes) === expected) ?? candidates[0];
223
+ legacyFiles.set(relative, value ? { kind: 'file', ...value, entries: null } : { kind: 'missing', mode: null, bytes: null, entries: null });
224
+ }
225
+ return legacyFiles.get(relative);
226
+ }
227
+ if (!observedFiles.has(relative)) observedFiles.set(relative, await observe(home, relative));
228
+ return observedFiles.get(relative);
229
+ };
204
230
  const directory = async relative => { if (!observedDirectories.has(relative)) observedDirectories.set(relative, await observe(home, relative, true, ignoreLock)); return observedDirectories.get(relative); };
205
231
  await directory(''); await directory(STATE_DIR); await directory('agents'); await directory('skills');
206
232
  for (const relative of [STATE, BASELINE, CUSTOM, SCOPE_FILE, 'AGENTS.md', 'AGENTS.override.md', 'config.toml', ...ROLE_PATHS]) await file(relative);
207
- const state = validateState((await file(STATE)).bytes);
233
+ state = validateState((await file(STATE)).bytes);
208
234
  const customModes = validateCustom((await file(CUSTOM)).bytes);
209
235
  let scopeStore;
210
236
  try { const bytes = (await file(SCOPE_FILE)).bytes; scopeStore = validateScopeStore(bytes === null ? null : parseJson(bytes, 'SCOPE_CONFIG_INVALID', '作用域配置无法解析。')); }
211
237
  catch { fail('SCOPE_CONFIG_INVALID', '作用域配置格式或版本无效;未回退到其他档位。'); }
212
- await file(`${SKILL}/references/current-mode.json`);
238
+ const modeFile = state?.schema_version === 2 ? `${SKILL}/references/current-mode.json` : CURRENT;
239
+ await file(modeFile);
213
240
  let mode = null;
214
241
  if (state) {
215
242
  try { mode = resolveDefinition(state.mode, customModes); } catch { fail('STATE_INVALID', '活动档位引用无效。'); }
216
243
  if (mode.kind !== state.mode_kind) fail('STATE_INVALID', '活动档位类型记录无效。');
217
- const installedBytes = (await file(`${SKILL}/references/current-mode.json`)).bytes;
244
+ const installedBytes = (await file(modeFile)).bytes;
218
245
  if (installedBytes !== null) {
219
246
  const installed = parseJson(installedBytes, 'STATE_INVALID', '已部署档位说明无效。');
220
247
  if (!keys(installed, ['id', 'name', 'kind', 'levels', 'version', 'roles', 'fallback_conditions']) || installed.id !== state.mode || installed.kind !== state.mode_kind || safeText(installed.name) === null || [...installed.name].length > 80 || !Array.isArray(installed.fallback_conditions) || !installed.fallback_conditions.every(value => typeof value === 'string' && /^[A-Z_]+$/.test(value)) || !equal(installed.roles, ROLES)) fail('STATE_INVALID', '已部署档位说明无效。');
221
- if (installed.version !== VERSION) fail('STATE_INVALID', '已部署档位说明的版本与当前工具不一致。');
248
+ if (installed.version !== state.version) fail('STATE_INVALID', '已部署档位说明的版本与安装记录不一致。');
222
249
  let levels;
223
250
  try { levels = validateDefinition({ levels: installed.levels }); } catch { fail('STATE_INVALID', '已部署档位等级定义无效。'); }
224
251
  mode = { id: installed.id, name: installed.name, kind: installed.kind, levels, fallback_conditions: installed.fallback_conditions, definition_version: installed.version };
@@ -229,6 +256,7 @@ async function collect(home, { ignoreLock = false } = {}) {
229
256
  for (const relative of paths) {
230
257
  if (!owned(relative)) fail('STATE_INVALID', '管理路径不在白名单中。');
231
258
  await file(relative);
259
+ if (relative.startsWith(`${SKILL}/`)) continue;
232
260
  let parent = path.posix.dirname(relative);
233
261
  while (parent !== '.') { await directory(parent); parent = path.posix.dirname(parent); }
234
262
  }
@@ -241,6 +269,11 @@ async function collect(home, { ignoreLock = false } = {}) {
241
269
  }
242
270
  await discoverRoles('agents');
243
271
  const diagnostics = [];
272
+ if (state?.schema_version === 2) diagnostics.push(diagnostic('MIGRATION_REQUIRED', 'fail', path.join(home, STATE), '旧版安装需要执行 setup --dry-run 预览,再执行 setup 迁移;查询未修改文件。', ['setup', '--dry-run']));
273
+ if (migrationConflicts.length) diagnostics.push(diagnostic('MIGRATION_CONFLICT', 'fail', migrationConflicts[0], '旧目录与共享 Skill 含无法确认归属的差异;保留双方文件。'));
274
+ if (skill.error) diagnostics.push(diagnostic('SKILL_UNAVAILABLE', 'warn', 'shared_skill', `Skill 入口无法安全读取(${skill.error});home 配置可查询和恢复,委派前须修复规则入口。`));
275
+ else if (!skill.path) diagnostics.push(diagnostic('SKILL_NOT_INSTALLED', 'warn', 'shared_skill', '未找到 Skill 入口;执行 setup 安装,查询未写入文件。', ['setup']));
276
+ else if (!skill.roots[0].files.get('.agent-fit-manifest.json').bytes) diagnostics.push(diagnostic('SKILL_UPDATE_REQUIRED', 'warn', skill.path, '规则尚未登记为共享布局;显式执行 skill update --dry-run 和 skill update 更新。', ['skill', 'update', '--dry-run']));
244
277
  let baseline = null;
245
278
  if (!state && (await file(BASELINE)).bytes !== null) fail('RESTORE_METADATA_INVALID', '恢复记录存在但安装状态缺失;请人工核对残留配置。');
246
279
  if (!state && (await file(CUSTOM)).bytes !== null) fail('STATE_INVALID', '自定义档位记录存在但安装状态缺失。');
@@ -249,7 +282,8 @@ async function collect(home, { ignoreLock = false } = {}) {
249
282
  if ((await file(STATE)).mode !== 0o600) diagnostics.push(diagnostic('STATE_PERMISSIONS_DRIFT', 'fail', path.join(home, STATE), '安装状态文件权限变化。'));
250
283
  for (const [relative, digest] of Object.entries(state.files)) {
251
284
  const actual = await file(relative);
252
- if (actual.bytes === null || hash(actual.bytes) !== digest || actual.mode !== state.file_modes[relative]) diagnostics.push(diagnostic('MANAGED_FILE_DRIFT', 'fail', path.join(home, relative), '受管理文件被修改、删除或权限变化。'));
285
+ const updatedStatic = state.schema_version === 2 && relative.startsWith(`${SKILL}/`) && skill.assets.get(relative.slice(SKILL.length + 1))?.equals(actual.bytes ?? Buffer.alloc(0));
286
+ if (actual.bytes === null || !updatedStatic && hash(actual.bytes) !== digest || actual.mode !== state.file_modes[relative]) diagnostics.push(diagnostic('MANAGED_FILE_DRIFT', 'fail', path.join(home, relative), '受管理文件被修改、删除或权限变化。'));
253
287
  }
254
288
  const rules = extractRules((await file('AGENTS.md')).bytes);
255
289
  if (!rules || hash(rules.block) !== state.rules_sha256 || (await file('AGENTS.md')).mode !== state.rules_mode) diagnostics.push(diagnostic('MANAGED_RULES_DRIFT', 'fail', path.join(home, 'AGENTS.md'), '受管理区块被修改、移除或权限变化。'));
@@ -290,15 +324,16 @@ async function collect(home, { ignoreLock = false } = {}) {
290
324
  if (override && /[^\p{White_Space}]/u.test(override.toString('utf8'))) diagnostics.push(diagnostic('RULES_SHADOWED', 'warn', path.join(home, 'AGENTS.override.md'), '非空 AGENTS.override.md 遮蔽本库 AGENTS.md。'));
291
325
  diagnostics.push(diagnostic('MODEL_ACCESS_UNKNOWN', 'unknown', 'static_configuration', '静态配置不证明账号调用权限。', ['models', 'check']));
292
326
  diagnostics.push(diagnostic('RULES_LOAD_UNVERIFIED', 'unknown', 'static_configuration', '规则读取与运行模型生效需要宿主证据。'));
293
- const snapshot = { home, state, mode, customModes, scopeStore, baseline, observedFiles, observedDirectories, diagnostics, config, externalRoles, roles, payload: candidates };
327
+ const snapshot = { home, state, mode, customModes, scopeStore, baseline, observedFiles, observedDirectories, legacyFiles, skill, diagnostics, config, externalRoles, roles, payload: candidates };
294
328
  snapshot.configuration_revision = revision(snapshot);
295
329
  return snapshot;
296
330
  }
297
331
  function revision(snapshot) {
298
- return hash(json({ instance: snapshot.state?.instance_id ?? 'not_installed', files: [...snapshot.observedFiles].sort(([a], [b]) => a.localeCompare(b)).map(([name, value]) => [name, stamp(value)]), directories: [...snapshot.observedDirectories].sort(([a], [b]) => a.localeCompare(b)).map(([name, value]) => [name, stamp(value)]) }));
332
+ return hash(json({ skill: snapshot.state?.schema_version === 2 ? snapshot.skill.revision : null, instance: snapshot.state?.instance_id ?? 'not_installed', files: [...snapshot.observedFiles].sort(([a], [b]) => a.localeCompare(b)).map(([name, value]) => [name, stamp(value)]), directories: [...snapshot.observedDirectories].sort(([a], [b]) => a.localeCompare(b)).map(([name, value]) => [name, stamp(value)]) }));
299
333
  }
300
334
  async function stillObserved(snapshot, ignoreLock = false) {
301
335
  if (!ignoreLock && await lockExists(snapshot.home)) return false;
336
+ if ((await skillInspection(snapshot.home)).revision !== snapshot.skill.revision) return false;
302
337
  for (const [relative, original] of snapshot.observedFiles) if (!equal(stamp(original), stamp(await observe(snapshot.home, relative)))) return false;
303
338
  for (const [relative, original] of snapshot.observedDirectories) if (!equal(stamp(original), stamp(await observe(snapshot.home, relative, true, ignoreLock)))) return false;
304
339
  return true;
@@ -314,11 +349,13 @@ export async function readSnapshot(home, options = {}) {
314
349
  fail('BUSY', '配置读取期间持续变化;请刷新后重试。');
315
350
  } catch (error) {
316
351
  if (error instanceof DelegationError) throw error;
352
+ if (error.exitCode === 1) fail(error.code, error.message);
317
353
  fail('READ_FAILED', '无法安全读取配置;请检查路径、权限或文件格式。');
318
354
  }
319
355
  }
320
- function requireClean(snapshot, restore = false) {
321
- const failures = snapshot.diagnostics.filter(value => value.status === 'fail' && (!restore || ['MANAGED_FILE_DRIFT', 'MANAGED_RULES_DRIFT', 'STATE_PERMISSIONS_DRIFT'].includes(value.code)));
356
+ function requireClean(snapshot, restore = false, migrating = false) {
357
+ if (snapshot.state?.schema_version === 2 && !migrating) fail('MIGRATION_REQUIRED', '请先执行 setup --dry-run 和 setup 迁移旧安装,再修改或恢复配置。');
358
+ const failures = snapshot.diagnostics.filter(value => value.status === 'fail' && !(migrating && value.code === 'MIGRATION_REQUIRED') && (!restore || ['MANAGED_FILE_DRIFT', 'MANAGED_RULES_DRIFT', 'STATE_PERMISSIONS_DRIFT'].includes(value.code)));
322
359
  if (failures.length) fail(restore ? 'RESTORE_CONFLICT' : failures[0].code, restore ? '受管理内容存在冲突,未恢复任何文件。' : '受管理内容存在冲突,未覆盖任何文件。', 1, { paths: failures.map(value => value.source) });
323
360
  }
324
361
  function requireRevision(snapshot, expected) {
@@ -383,7 +420,7 @@ function configuredLevels(definition, options) {
383
420
  }
384
421
  async function buildPlan(snapshot, action, options) {
385
422
  requireRevision(snapshot, options.expectRevision);
386
- requireClean(snapshot, action === 'restore');
423
+ requireClean(snapshot, action === 'restore', action === 'setup');
387
424
  const { state, home } = snapshot;
388
425
  if (action !== 'setup' && action !== 'restore' && !state) fail('NOT_INSTALLED', '请先执行 setup 配置 Codex。');
389
426
  if (!['setup', 'set', 'clear', 'delete', 'create', 'configure', 'restore'].includes(action)) fail('INVALID_ACTION', '不支持的写入动作。', 2);
@@ -462,7 +499,7 @@ async function buildPlan(snapshot, action, options) {
462
499
  plan.mode = scopedSelection({ ...snapshot, scopeStore }, context).definition;
463
500
  }
464
501
  let customModes = snapshot.customModes.map(mode => ({ ...mode, levels: structuredClone(mode.levels) }));
465
- let desiredMode = snapshot.mode ? resolveDefinition(snapshot.mode.id, customModes) : resolveDefinition('official', customModes);
502
+ let desiredMode = state?.schema_version === 2 ? snapshot.mode : snapshot.mode ? resolveDefinition(snapshot.mode.id, customModes) : resolveDefinition('official', customModes);
466
503
  if (!local && (action === 'setup' && options.mode !== undefined || action === 'set')) desiredMode = resolveDefinition(options.mode, customModes);
467
504
  if (!local && action === 'clear') desiredMode = resolveDefinition('official');
468
505
  if (!local && action === 'delete') {
@@ -493,11 +530,12 @@ async function buildPlan(snapshot, action, options) {
493
530
  files.clear();
494
531
  for (const relative of Object.keys(state.files)) files.set(relative, snapshot.observedFiles.get(relative).bytes);
495
532
  }
496
- if (customModes.length || snapshot.observedFiles.get(CUSTOM).bytes !== null) files.set(CUSTOM, json({ schema_version: 1, agent: 'codex', modes: customModes.map(({ id, name, levels }) => ({ id, name, levels })) }));
497
- if (local || snapshot.observedFiles.get(SCOPE_FILE).bytes !== null) files.set(SCOPE_FILE, json(scopeStore));
533
+ if (customModes.length || snapshot.observedFiles.get(CUSTOM).bytes !== null) files.set(CUSTOM, state?.schema_version === 2 && snapshot.observedFiles.get(CUSTOM).bytes !== null ? snapshot.observedFiles.get(CUSTOM).bytes : json({ schema_version: 1, agent: 'codex', modes: customModes.map(({ id, name, levels }) => ({ id, name, levels })) }));
534
+ if (local || snapshot.observedFiles.get(SCOPE_FILE).bytes !== null) files.set(SCOPE_FILE, local ? json(scopeStore) : snapshot.observedFiles.get(SCOPE_FILE).bytes);
498
535
  const previous = state?.files ?? {};
499
536
  for (const relative of [...new Set([...files.keys(), ...Object.keys(previous)])].sort()) {
500
537
  if (!owned(relative)) fail('UNSAFE_PATH', '发布包含非法管理路径。');
538
+ if (state?.schema_version === 2 && relative.startsWith(`${SKILL}/`)) continue;
501
539
  const before = snapshot.observedFiles.get(relative) ?? await observe(home, relative);
502
540
  const desired = files.get(relative) ?? null;
503
541
  if (before.bytes !== null && !Object.hasOwn(previous, relative) && (!desired || !before.bytes.equals(desired))) fail('FILE_CONFLICT', `文件已有不同内容,未覆盖:${path.join(home, relative)}`);
@@ -508,13 +546,22 @@ async function buildPlan(snapshot, action, options) {
508
546
  if (deploying) await add('AGENTS.md', merged.bytes);
509
547
  const directories = await directoryCreation(snapshot, [...files.keys(), STATE, BASELINE, 'AGENTS.md']);
510
548
  let baseline = snapshot.baseline ? structuredClone(snapshot.baseline) : null;
549
+ if (state?.schema_version === 2) {
550
+ for (const [relative, entry] of Object.entries(baseline.entries)) if (relative.startsWith(`${SKILL}/`)) {
551
+ const actual = snapshot.legacyFiles.get(relative);
552
+ if (entry !== null && (!actual?.bytes?.equals(base64(entry.bytes_base64)) || actual.mode !== entry.mode)) fail('MIGRATION_CONFLICT', `旧 Skill 含尚未恢复的安装前内容;保留现有文件和恢复记录:${path.join(home, relative)}`);
553
+ delete baseline.entries[relative];
554
+ }
555
+ baseline.created_directories = baseline.created_directories.filter(relative => relative !== 'skills' && !relative.startsWith(SKILL));
556
+ plan.warnings.push('旧 Skill 资产保留,由共享 Skill 管理;本 home 的动态档位和恢复记录已独立。需要更新规则时显式运行 agent-fit skill update。');
557
+ }
511
558
  if (!state) {
512
559
  baseline = { schema_version: 1, agent: 'codex', entries: {}, rules: { existed: originalRules.bytes !== null, mode: originalRules.mode, sha256: originalRules.bytes === null ? null : hash(originalRules.bytes), original_block_base64: merged.found?.block.toString('base64') ?? null, separator_base64: merged.separator.toString('base64'), original_prefix_sha256: hash(merged.found?.before ?? originalRules.bytes ?? Buffer.alloc(0)) }, created_directories: directories };
513
560
  }
514
561
  for (const relative of files.keys()) if (!Object.hasOwn(baseline.entries, relative)) baseline.entries[relative] = managedEntry(snapshot.observedFiles.get(relative) ?? await observe(home, relative));
515
562
  baseline.created_directories = [...new Set([...baseline.created_directories, ...directories])];
516
563
  await add(BASELINE, json(baseline), 0o600);
517
- const stateBytes = json({ schema_version: 2, agent: 'codex', version: VERSION, mode: desiredMode.id, mode_kind: desiredMode.kind, instance_id: state?.instance_id ?? randomUUID(), files: Object.fromEntries([...files].sort(([a], [b]) => a.localeCompare(b)).map(([relative, bytes]) => [relative, hash(bytes)])), file_modes: Object.fromEntries([...files.keys()].sort().map(relative => [relative, changes.get(relative)?.mode ?? snapshot.observedFiles.get(relative)?.mode ?? 0o600])), rules_mode: changes.get('AGENTS.md')?.mode ?? originalRules.mode ?? 0o600, rules_sha256: deploying ? hash(payload.block) : state.rules_sha256, restoration: { status: 'available', baseline_sha256: hash(json(baseline)) } });
564
+ const stateBytes = json({ schema_version: 3, legacy_skill_files: state?.schema_version === 2 ? Object.fromEntries(Object.entries(state.files).filter(([relative]) => relative.startsWith(`${SKILL}/`))) : state?.legacy_skill_files ?? {}, agent: 'codex', version: VERSION, mode: desiredMode.id, mode_kind: desiredMode.kind, instance_id: state?.instance_id ?? randomUUID(), files: Object.fromEntries([...files].sort(([a], [b]) => a.localeCompare(b)).map(([relative, bytes]) => [relative, hash(bytes)])), file_modes: Object.fromEntries([...files.keys()].sort().map(relative => [relative, changes.get(relative)?.mode ?? snapshot.observedFiles.get(relative)?.mode ?? 0o600])), rules_mode: changes.get('AGENTS.md')?.mode ?? originalRules.mode ?? 0o600, rules_sha256: deploying ? hash(payload.block) : state.rules_sha256, restoration: { status: 'available', baseline_sha256: hash(json(baseline)) } });
518
565
  await add(STATE, stateBytes, 0o600);
519
566
  const ordered = new Map();
520
567
  if (changes.has(BASELINE)) ordered.set(BASELINE, changes.get(BASELINE));
@@ -524,7 +571,7 @@ async function buildPlan(snapshot, action, options) {
524
571
  plan.deploymentChanged = [...ordered.keys()].some(relative => ![BASELINE, STATE, CUSTOM, SCOPE_FILE].includes(relative));
525
572
  // Compare against today's templates rendered with the old mode, so model/effort changes alone do not require a restart.
526
573
  plan.restartRequired = !state || deploying && [...ordered].some(([relative, change]) => {
527
- if ([BASELINE, STATE, CUSTOM, SCOPE_FILE, `${SKILL}/references/current-mode.json`].includes(relative)) return false;
574
+ if ([BASELINE, STATE, CUSTOM, SCOPE_FILE, CURRENT].includes(relative)) return false;
528
575
  const expected = snapshot.payload.files.get(relative);
529
576
  return !expected || !change.before.bytes?.equals(expected);
530
577
  });
@@ -566,6 +613,7 @@ function normalizedLocked(snapshot, original, created) {
566
613
  if (created.includes(relative) && original.observedDirectories.get(relative)?.kind === 'missing') normalize.set(relative, { kind: 'missing', mode: null, bytes: null, entries: null });
567
614
  else if (value.entries) normalize.set(relative, { ...value, entries: value.entries.filter(([name]) => !created.includes(relative ? `${relative}/${name}` : name)) });
568
615
  }
616
+ if (snapshot.skill.revision !== original.skill.revision) return false;
569
617
  const files = snapshot.observedFiles;
570
618
  for (const [relative, value] of original.observedFiles) if (!equal(stamp(value), stamp(files.get(relative) ?? { kind: 'missing', mode: null, bytes: null, entries: null }))) return false;
571
619
  for (const [relative, value] of original.observedDirectories) if (!equal(stamp(value), stamp(normalize.get(relative) ?? { kind: 'missing', mode: null, bytes: null, entries: null }))) return false;
@@ -611,7 +659,7 @@ export async function applyPlan(plan, options = {}) {
611
659
  const locked = await readSnapshot(home, { ignoreLock: true });
612
660
  if (!normalizedLocked(locked, plan.snapshot, ownCreated)) fail('CONFIG_CHANGED', '锁内检测到配置或角色目录变化;未写入配置。');
613
661
  requireRevision(plan.snapshot, options.expectRevision);
614
- requireClean(locked, plan.action === 'restore');
662
+ requireClean(locked, plan.action === 'restore', plan.action === 'setup');
615
663
  for (const relative of plan.createdDirectories ?? []) {
616
664
  if (ownCreated.includes(relative)) continue;
617
665
  await checkPath(home, relative);
@@ -682,7 +730,22 @@ export async function mutate(home, action, options = {}) {
682
730
  try {
683
731
  const snapshot = await readSnapshot(home);
684
732
  plan = await buildPlan(snapshot, action, options);
685
- return await applyPlan(plan, options);
733
+ const shared = action === 'setup' ? await updateSkill(snapshot.home, { installOnly: true, dryRun: true }) : null;
734
+ const report = await applyPlan(plan, options);
735
+ if (shared) {
736
+ try {
737
+ report.shared_skill = options.dryRun ? shared : await updateSkill(snapshot.home, { installOnly: true });
738
+ if (!options.dryRun && report.shared_skill.result === 'applied') report.restart = restart('deployment_changed');
739
+ } catch (error) {
740
+ report.warnings.push('home 配置已完成,但共享 Skill 安装失败;保留已写入配置,请检查 Skill 目录后重试 setup。');
741
+ throw new DelegationError(error.code ?? 'SKILL_INSTALL_FAILED', error.message, 1, { report });
742
+ }
743
+ if (!options.dryRun) {
744
+ try { report.revision_after = (await readSnapshot(snapshot.home)).configuration_revision; }
745
+ catch { report.revision_after = null; report.warnings.push('配置与共享 Skill 已处理,但最终观察不可用;请刷新状态。'); }
746
+ }
747
+ }
748
+ return report;
686
749
  } catch (error) {
687
750
  if (!(error instanceof DelegationError)) error = error.exitCode === 2 ? new DelegationError(error.code ?? 'INVALID_ARGUMENT', error.message, 2) : new DelegationError('WRITE_FAILED', '无法安全完成配置操作;未输出原始配置。');
688
751
  if (!error.details.report && plan) error.details.report = changeReport(plan, 'failed', 'not_written', null, 'not_applied');
@@ -717,7 +780,7 @@ export async function statusReport(home, options = {}) {
717
780
  if (profileCandidates.length) skippedPaths.push({ path: path.join(snapshot.home, 'config.toml'), reason: 'conditional_active_profile_unknown' });
718
781
  for (const [relative, observed] of snapshot.observedDirectories) if (relative === 'agents' || relative.startsWith('agents/')) for (const [name, kind] of observed.entries ?? []) if (kind === 'symlink') skippedPaths.push({ path: safeSource(path.join(snapshot.home, relative, name)), reason: 'unfollowed_symlink' });
719
782
  const rulesSummary = ['仅在用户和宿主授权下委派', '按当前档位、任务难度和验证需求选择模型', '用户明确模型、预算和项目规则优先', '禁止递归委派', '禁止修改生产、共享环境、第三方系统和代理配置', '明确独占写入', '先读取真实材料与验收条件', '等价局部差异自行适配', '核心前提失效只阻断受影响部分', '必要验证通过后停止,不擅自扩大检查', '未知退出状态、陈旧报告或部分结果标记 PARTIAL', '固定角色不适用时使用 task_delegate,权限与验收不变', 'fire 每会话先验证;失败时用用户指定组合,否则继承父代理组合', '备用须满足原授权、预算、工具和能力;失败不得静默降级'];
720
- return { ...effective, definition: undefined, global_mode: snapshot.mode, agent: 'codex', home: snapshot.home, cli_version: VERSION, configuration_version: state?.version ?? null, configuration_revision: snapshot.configuration_revision, installation: state ? 'installed' : 'not_installed', integrity: snapshot.diagnostics.some(value => value.status === 'fail') ? 'drifted' : 'clean', mode: mode ? { id: mode.id, name: mode.name, kind: mode.kind, levels: mode.levels } : null, verification: verificationRequirement(mode), restoration: { status: state?.restoration.status ?? 'not_installed' }, roles: snapshot.roles, task_levels: mode ? LEVELS.map(level => ({ level, ...mode.levels[level] })) : [], rules: { source: path.join(snapshot.home, SKILL, 'SKILL.md'), integrity: state ? snapshot.diagnostics.some(value => ['MANAGED_RULES_DRIFT', 'MANAGED_FILE_DRIFT'].includes(value.code)) ? 'drifted' : 'clean' : 'not_installed', summary: options.details ? rulesSummary : [] }, related_config: { agents_enabled: typeof snapshot.config.agents?.enabled === 'boolean' ? snapshot.config.agents.enabled : typeof snapshot.config.features?.multi_agent === 'boolean' ? snapshot.config.features.multi_agent : null, default_subagent_model: safeText(snapshot.config.agents?.default_subagent_model), default_subagent_reasoning_effort: safeText(snapshot.config.agents?.default_subagent_reasoning_effort), inheritance_note: 'task_delegate 的省略参数不证明继承;须核对全局子代理默认值与宿主派发参数。', external_roles: snapshot.externalRoles, registered_roles: registeredRoles, profile_candidates: profileCandidates, project_candidates: [] }, inspection: { checked_paths: [...snapshot.observedFiles.keys()].map(relative => safeSource(path.join(snapshot.home, relative))), skipped_paths: skippedPaths }, diagnostics: snapshot.diagnostics, warnings: state ? ['运行模型身份尚未验证;已开始任务沿用原配置。'] : [], runtime_verification: 'unverified' };
783
+ return { ...effective, definition: undefined, global_mode: snapshot.mode, agent: 'codex', home: snapshot.home, cli_version: VERSION, configuration_version: state?.version ?? null, configuration_revision: snapshot.configuration_revision, installation: state ? 'installed' : 'not_installed', integrity: snapshot.diagnostics.some(value => value.status === 'fail') ? 'drifted' : 'clean', mode: mode ? { id: mode.id, name: mode.name, kind: mode.kind, levels: mode.levels } : null, verification: verificationRequirement(mode), restoration: { status: state?.restoration.status ?? 'not_installed' }, roles: snapshot.roles, task_levels: mode ? LEVELS.map(level => ({ level, ...mode.levels[level] })) : [], rules: { source: snapshot.skill.path, integrity: state ? snapshot.diagnostics.some(value => ['MANAGED_RULES_DRIFT', 'MANAGED_FILE_DRIFT'].includes(value.code)) ? 'drifted' : 'clean' : 'not_installed', summary: options.details ? rulesSummary : [] }, related_config: { agents_enabled: typeof snapshot.config.agents?.enabled === 'boolean' ? snapshot.config.agents.enabled : typeof snapshot.config.features?.multi_agent === 'boolean' ? snapshot.config.features.multi_agent : null, default_subagent_model: safeText(snapshot.config.agents?.default_subagent_model), default_subagent_reasoning_effort: safeText(snapshot.config.agents?.default_subagent_reasoning_effort), inheritance_note: 'task_delegate 的省略参数不证明继承;须核对全局子代理默认值与宿主派发参数。', external_roles: snapshot.externalRoles, registered_roles: registeredRoles, profile_candidates: profileCandidates, project_candidates: [] }, inspection: { checked_paths: [...snapshot.observedFiles.keys()].map(relative => safeSource(path.join(snapshot.home, relative))), skipped_paths: skippedPaths }, diagnostics: snapshot.diagnostics, warnings: state ? ['运行模型身份尚未验证;已开始任务沿用原配置。'] : [], runtime_verification: 'unverified' };
721
784
  }
722
785
  export async function listReport(home, options = {}) {
723
786
  const snapshot = await readSnapshot(home, options);
@@ -729,5 +792,5 @@ export async function showReport(home, selector, options = {}) {
729
792
  const selected = scopedSelection(snapshot, await scopeContext(options), selector);
730
793
  const { definition } = selected;
731
794
  const activeBuiltin = definition.kind === 'builtin' && snapshot.mode?.id === definition.id;
732
- return { ...selected, configuration_revision: snapshot.configuration_revision, home: snapshot.home, source: activeBuiltin ? path.join(snapshot.home, SKILL, 'references/current-mode.json') : definition.kind === 'builtin' ? 'package' : path.join(snapshot.home, selected.definition_scope === 'global' ? CUSTOM : SCOPE_FILE), definition_version: activeBuiltin ? snapshot.mode.definition_version ?? snapshot.state.version : definition.kind === 'builtin' ? VERSION : null, diagnostics: snapshot.diagnostics, runtime_verification: 'unverified' };
795
+ return { ...selected, configuration_revision: snapshot.configuration_revision, home: snapshot.home, source: activeBuiltin ? path.join(snapshot.home, snapshot.state?.schema_version === 2 ? `${SKILL}/references/current-mode.json` : CURRENT) : definition.kind === 'builtin' ? 'package' : path.join(snapshot.home, selected.definition_scope === 'global' ? CUSTOM : SCOPE_FILE), definition_version: activeBuiltin ? snapshot.mode.definition_version ?? snapshot.state.version : definition.kind === 'builtin' ? VERSION : null, diagnostics: snapshot.diagnostics, runtime_verification: 'unverified' };
733
796
  }
package/lib/skill.mjs ADDED
@@ -0,0 +1,145 @@
1
+ import fs from 'node:fs/promises';
2
+ import { constants } from 'node:fs';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import { createHash, randomUUID } from 'node:crypto';
6
+ import { skillAssets, VERSION } from './codex.mjs';
7
+
8
+ const MANIFEST = '.agent-fit-manifest.json';
9
+ let testHooks = {};
10
+ export function setSkillTestHooks(hooks = {}) { testHooks = hooks; }
11
+ const hash = bytes => createHash('sha256').update(bytes).digest('hex');
12
+ const fail = (code, message) => { throw Object.assign(new Error(message), { code, exitCode: 1 }); };
13
+ export const sharedSkillPath = () => path.join(os.homedir(), '.agents/skills/agent-fit');
14
+ async function stat(target) { try { return await fs.lstat(target); } catch (error) { if (error.code === 'ENOENT') return null; throw error; } }
15
+ async function checkDirectoryPath(target) {
16
+ let current = path.parse(target).root;
17
+ for (const part of target.slice(current.length).split(path.sep).filter(Boolean)) {
18
+ current = path.join(current, part);
19
+ const info = await stat(current);
20
+ if (info && (!info.isDirectory() || info.isSymbolicLink())) fail('UNSAFE_PATH', `共享 Skill 安装父级不安全:${current}`);
21
+ }
22
+ }
23
+
24
+ async function rootAt(target) {
25
+ try {
26
+ const root = await fs.realpath(target), info = await fs.lstat(root);
27
+ if (!info.isDirectory() || info.mode & 0o7022 || process.platform !== 'win32' && info.uid !== process.getuid()) fail('UNSAFE_PATH', `Skill 目录所有者、权限或类型不安全:${target}`);
28
+ return root;
29
+ } catch (error) { if (error.code === 'ENOENT' && !await stat(target)) return null; throw error; }
30
+ }
31
+
32
+ // Only the Skill root may be a link. Files and nested directories never follow links.
33
+ export async function readSkillFile(root, relative) {
34
+ if (!relative || relative.split('/').some(part => !part || part === '.' || part === '..') || relative.includes('\\')) fail('UNSAFE_PATH', '非法 Skill 文件路径。');
35
+ if (await fs.realpath(root) !== root) fail('UNSAFE_PATH', `Skill 目录已改变:${root}`);
36
+ let current = root;
37
+ for (const part of relative.split('/')) {
38
+ current = path.join(current, part);
39
+ const info = await stat(current);
40
+ if (!info) return { bytes: null, mode: null };
41
+ if (info.isSymbolicLink() || info.mode & 0o7022 || process.platform !== 'win32' && info.uid !== process.getuid()) fail('UNSAFE_PATH', `Skill 文件路径不安全:${current}`);
42
+ if (current !== path.join(root, relative) && !info.isDirectory()) fail('UNSAFE_PATH', `Skill 父级不是目录:${current}`);
43
+ }
44
+ const handle = await fs.open(current, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
45
+ try {
46
+ const info = await handle.stat();
47
+ if (!info.isFile() || info.size > 1024 * 1024) fail('UNSAFE_PATH', `Skill 不是普通文件或过大:${current}`);
48
+ return { bytes: await handle.readFile(), mode: info.mode & 0o777 };
49
+ } finally { await handle.close(); }
50
+ }
51
+
52
+ export async function inspectSkill(home) {
53
+ const assets = await skillAssets(), roots = [];
54
+ const shared = await rootAt(sharedSkillPath());
55
+ const legacyPath = path.join(home, 'skills/agent-fit');
56
+ const legacy = await rootAt(legacyPath);
57
+ if ((await stat(legacyPath))?.isSymbolicLink() && legacy !== shared) fail('UNSAFE_PATH', '旧 Skill 软链接必须指向已识别的共享 Skill 目录。');
58
+ for (const root of [...new Set([shared, legacy].filter(Boolean))]) {
59
+ const files = new Map();
60
+ for (const relative of [...assets.keys(), 'references/current-mode.json', MANIFEST]) files.set(relative, await readSkillFile(root, relative));
61
+ const entry = files.get('SKILL.md').bytes;
62
+ if (!entry || !/^name: agent-fit$/m.test(entry.toString('utf8'))) fail('SKILL_CONFLICT', `目录中不是有效的 agent-fit Skill:${root}`);
63
+ roots.push({ root, files });
64
+ }
65
+ const identity = roots.map(({ root, files }) => [root, [...files].map(([relative, value]) => [relative, value.mode, value.bytes === null ? null : hash(value.bytes)])]);
66
+ return { path: roots.length ? path.join(roots[0].root, 'SKILL.md') : null, roots, revision: hash(JSON.stringify(identity)), assets };
67
+ }
68
+
69
+ export async function updateSkill(home, { dryRun = false, installOnly = false, legacyState = null } = {}) {
70
+ const inspection = await inspectSkill(home), destination = sharedSkillPath();
71
+ const existing = await rootAt(destination);
72
+ if (installOnly && existing) return { result: 'unchanged', path: path.join(existing, 'SKILL.md'), changed_files: [] };
73
+ const root = existing ?? destination, assets = inspection.assets;
74
+ const before = new Map();
75
+ for (const relative of [...assets.keys(), MANIFEST]) before.set(relative, existing ? await readSkillFile(existing, relative) : { bytes: null, mode: null });
76
+ let recorded = {};
77
+ if (before.get(MANIFEST).bytes) {
78
+ try {
79
+ const value = JSON.parse(before.get(MANIFEST).bytes);
80
+ if (value.layout !== 1 || typeof value.version !== 'string' || !value.files || Array.isArray(value.files) || Object.entries(value.files).some(([name, digest]) => !assets.has(name) || !/^[a-f0-9]{64}$/.test(digest))) throw new Error();
81
+ recorded = value.files;
82
+ } catch { fail('SKILL_CONFLICT', '共享 Skill 管理记录无效;保留现有文件。'); }
83
+ }
84
+ const changes = new Map();
85
+ for (const [relative, bytes] of assets) {
86
+ const actual = before.get(relative).bytes;
87
+ if (actual?.equals(bytes)) continue;
88
+ const expected = recorded[relative] ?? legacyState?.legacy_skill_files?.[`skills/agent-fit/${relative}`] ?? legacyState?.files[`skills/agent-fit/${relative}`];
89
+ if (actual !== null && (!expected || hash(actual) !== expected)) fail('SKILL_CONFLICT', `共享 Skill 含未确认的修改,未覆盖:${path.join(root, relative)}`);
90
+ changes.set(relative, bytes);
91
+ }
92
+ const manifest = Buffer.from(JSON.stringify({ layout: 1, version: VERSION, files: Object.fromEntries([...assets].map(([name, bytes]) => [name, hash(bytes)])) }, null, 2) + '\n');
93
+ if (!before.get(MANIFEST).bytes?.equals(manifest)) changes.set(MANIFEST, manifest);
94
+ const report = { action: 'skill-update', home, result: dryRun ? 'preview' : changes.size ? 'applied' : 'unchanged', path: path.join(root, 'SKILL.md'), changed_files: [...changes.keys()], version: VERSION, restart: { required: !dryRun && changes.size > 0, message: dryRun ? '共享规则预览未写入;更新后请重启 Codex。' : changes.size ? '共享规则已更新,请重启 Codex 后使用。' : '共享规则无变化。' } };
95
+ if (!existing) await checkDirectoryPath(path.dirname(root));
96
+ if (dryRun || !changes.size) return report;
97
+ const parent = path.dirname(root), created = [], applied = [];
98
+ await checkDirectoryPath(parent);
99
+ await fs.mkdir(parent, { recursive: true, mode: 0o700 });
100
+ if (await fs.realpath(parent) !== parent) fail('UNSAFE_PATH', `共享 Skill 安装父级含符号链接:${parent}`);
101
+ const lock = path.join(parent, '.agent-fit-skill.lock');
102
+ let handle;
103
+ try { handle = await fs.open(lock, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | (constants.O_NOFOLLOW ?? 0), 0o600); }
104
+ catch (error) { if (error.code === 'EEXIST') fail('BUSY', '共享 Skill 正在更新;请稍后重试。'); throw error; }
105
+ const identity = await handle.stat();
106
+ const ownsLock = async () => { const actual = await stat(lock); return actual?.dev === identity.dev && actual?.ino === identity.ino; };
107
+ const write = async (relative, bytes, mode, expected) => {
108
+ if (!await ownsLock()) fail('BUSY', '共享 Skill 更新锁被替换;保留新锁,停止写入。');
109
+ const actual = await readSkillFile(root, relative);
110
+ if (actual.mode !== expected.mode || (actual.bytes === null ? expected.bytes !== null : !actual.bytes.equals(expected.bytes ?? Buffer.alloc(0)))) fail('CONFIG_CHANGED', `共享 Skill 在更新期间改变:${path.join(root, relative)}`);
111
+ const target = path.join(root, relative);
112
+ if (bytes === null) { await fs.unlink(target); return; }
113
+ const temporary = path.join(path.dirname(target), `.agent-fit-${randomUUID()}.tmp`);
114
+ try {
115
+ await fs.writeFile(temporary, bytes, { flag: 'wx', mode });
116
+ await fs.chmod(temporary, mode);
117
+ const current = await readSkillFile(root, relative);
118
+ if (current.mode !== actual.mode || (current.bytes === null ? actual.bytes !== null : !current.bytes.equals(actual.bytes))) fail('CONFIG_CHANGED', `共享 Skill 在替换前改变:${target}`);
119
+ await fs.rename(temporary, target);
120
+ } finally { await fs.unlink(temporary).catch(error => { if (error.code !== 'ENOENT') throw error; }); }
121
+ };
122
+ try {
123
+ const directories = new Set(['']);
124
+ for (const relative of changes.keys()) { let folder = path.posix.dirname(relative); while (folder !== '.') { directories.add(folder); folder = path.posix.dirname(folder); } }
125
+ for (const relative of [...directories].sort((a, b) => a.split('/').length - b.split('/').length)) {
126
+ const target = path.join(root, relative), info = await stat(target);
127
+ if (!info) { await fs.mkdir(target, { mode: 0o700 }); created.push(target); }
128
+ else if (!info.isDirectory() || info.isSymbolicLink()) fail('UNSAFE_PATH', `共享 Skill 目录不安全:${target}`);
129
+ }
130
+ for (const [relative, bytes] of changes) {
131
+ await testHooks.beforeWrite?.(relative, applied.length);
132
+ await write(relative, bytes, before.get(relative).mode ?? 0o600, before.get(relative)); applied.push(relative);
133
+ }
134
+ return report;
135
+ } catch (error) {
136
+ const failures = [];
137
+ for (const relative of applied.reverse()) {
138
+ try { await write(relative, before.get(relative).bytes, before.get(relative).mode, { bytes: changes.get(relative), mode: before.get(relative).mode ?? 0o600 }); }
139
+ catch { failures.push(path.join(root, relative)); }
140
+ }
141
+ for (const target of created.reverse()) await fs.rmdir(target).catch(() => {});
142
+ if (failures.length) fail('SKILL_UPDATE_PARTIAL', `共享 Skill 更新未完成,部分文件回退失败;请核对:${failures.join('、')}`);
143
+ throw error;
144
+ } finally { await handle.close(); if (await ownsLock()) await fs.unlink(lock); }
145
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fanglinwei/agent-fit",
3
- "version": "0.7.1",
3
+ "version": "0.7.3",
4
4
  "description": "Match delegated tasks to model and reasoning effort profiles for Codex, with scoped configuration and restore.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -11,7 +11,7 @@
11
11
  "keywords": ["codex", "subagents", "model-routing", "reasoning", "skills", "cli"],
12
12
  "bin": { "agent-fit": "bin/agent-fit.mjs" },
13
13
  "engines": { "node": ">=22" },
14
- "files": ["bin/", "lib/", "web/", "adapters/", "VERSION", "README.md", "docs/README.md", "docs/usage.md", "docs/implementation-review.md", "LICENSE"],
14
+ "files": [".agents/plugins/marketplace.json", ".codex-plugin/plugin.json", "bin/", "lib/", "web/", "adapters/", "VERSION", "README.md", "docs/README.md", "docs/usage.md", "docs/implementation-review.md", "LICENSE"],
15
15
  "scripts": { "test": "node --test tests/*.test.mjs", "test:browser": "node tests/browser.mjs" },
16
16
  "dependencies": { "smol-toml": "1.9.1" }
17
17
  }