opencode-growth 0.1.75 → 0.1.76

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-growth",
3
- "version": "0.1.75",
3
+ "version": "0.1.76",
4
4
  "description": "OpenCode growth kit: cross-project memory (memory / capability / preference / fact) with evidence and withdrawal.",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",
@@ -106,6 +106,8 @@ export function buildSkillTool({
106
106
  old_string: z.string().optional().describe("patch 用:要替换的原文(必须唯一命中)"),
107
107
  new_string: z.string().optional().describe("patch 用:替换后的新文"),
108
108
  absorbed_into: z.string().optional().describe("archive 用:合并去向的伞技能名(必须已存在)"),
109
+ file_path: z.string().optional().describe("write_file/remove_file 用:references|scripts|templates|assets 下的相对路径"),
110
+ file_content: z.string().optional().describe("write_file 用:附件正文(UTF-8,≤1MiB)"),
109
111
  // 注意这里**没有** origin / agent / created_by:身份与归属由宿主 ctx 和
110
112
  // 部署者名单决定(extra#4),created_by 由动作层按身份写进 frontmatter。
111
113
  },
@@ -132,6 +134,8 @@ export function buildSkillTool({
132
134
  old_string: args?.old_string,
133
135
  new_string: args?.new_string,
134
136
  absorbedInto: args?.absorbed_into,
137
+ file_path: args?.file_path ?? null,
138
+ file_content: args?.file_content ?? null,
135
139
  ask,
136
140
  hostPermission: gate.hostPermission,
137
141
  agentSkillEnabled: gate.agentSkillEnabled,
package/src/cli/main.mjs CHANGED
@@ -281,6 +281,14 @@ function render(command, env) {
281
281
  return d.pending
282
282
  .map((p) => {
283
283
  const head = ` ${p.file} ${p.op ?? "?"} ${p.kind ?? "?"}${p.label ? ` ${p.label}` : ""}`
284
+ // S5:附属文件动作要能看见「哪个文件、新/覆盖/删除、旧文与新文」,stale 如实标。
285
+ if (p.kind === "skills" && (p.op === "write_file" || p.op === "remove_file")) {
286
+ const state = p.state === "new" ? "新" : p.state === "ok" ? (p.op === "remove_file" ? "删除" : "覆盖") : String(p.state ?? "?")
287
+ const oldTxt = p.state === "new" || !p.fileExists ? "旧:(原先不存在)" : `旧:${flat(p.oldText)}`
288
+ return p.op === "write_file"
289
+ ? `${head}\n 文件:${p.filePath}(${state})\n ${oldTxt}\n 新:${flat(p.newText)}`
290
+ : `${head}\n 文件:${p.filePath}(${state})\n ${oldTxt}`
291
+ }
284
292
  // 人读行的判据:update/remove 要能看见**被替换/删除的那一条全文**,不是只有新文或定位子串。
285
293
  if (p.op === "update") return `${head}\n ${oldLine(p)}\n 新:${flat(p.text)}`
286
294
  if (p.op === "remove") return `${head}\n ${oldLine(p)}`
@@ -19,12 +19,12 @@ import { withCommitLock } from "./lock.mjs"
19
19
  import { appendAudit } from "./audit.mjs"
20
20
  import { createMemoryStore, storeHashOf } from "./memories.mjs"
21
21
  import { sha256 } from "./ids.mjs"
22
- import { runSkillAction } from "./skill-actions.mjs"
22
+ import { runSkillAction, resolveSupportTarget, applySupportFile } from "./skill-actions.mjs"
23
23
  import { snapshotSkills } from "./skill-backup.mjs"
24
24
  import { readCreatedBy, SKILL_FILE, skillsDir } from "./skills.mjs"
25
25
 
26
26
  const OPS = ["add", "update", "remove", "batch"]
27
- const SKILL_OPS = ["create", "patch"]
27
+ const SKILL_OPS = ["create", "patch", "write_file", "remove_file"]
28
28
  const KINDS = ["memory", "user", "skills"]
29
29
 
30
30
  const MAX_DIFF_LINES = 200
@@ -77,6 +77,24 @@ function skillTargetOf(L, name) {
77
77
  }
78
78
  }
79
79
 
80
+
81
+ /** 附属文件提案的目标与「当初那份」指纹;路径守卫与写路径同一实现。 */
82
+ function skillSupportOf(L, rec) {
83
+ const skillDir = path.join(skillsDir(L.root), String(rec.name))
84
+ const skillFile = path.join(skillDir, SKILL_FILE)
85
+ if (!fs.existsSync(skillFile)) return { ok: false, error: `技能不存在:${String(rec.name)}` }
86
+ const t = resolveSupportTarget(skillDir, rec.filePath)
87
+ if (!t.ok) return t
88
+ const exists = fs.existsSync(t.abs)
89
+ return {
90
+ ok: true,
91
+ abs: t.abs,
92
+ rel: t.rel,
93
+ exists,
94
+ hash: exists ? sha256(fs.readFileSync(t.abs)) : null,
95
+ createdBy: readCreatedBy(skillFile),
96
+ }
97
+ }
80
98
  /** 列出待批提案。origin 保留原值;后台来源标 `[auto]`(照 Hermes,人一眼能看出不是自己提的)。 */
81
99
  export function listPending(L) {
82
100
  const store = createMemoryStore({ root: L.root })
@@ -98,6 +116,7 @@ export function listPending(L) {
98
116
  label: origin === "background" ? "[auto]" : null,
99
117
  text: raw.text ?? null,
100
118
  match: raw.match ?? null,
119
+ proposalHash: raw.proposalHash ?? null,
101
120
  // 批量提案:列出条目数与动作分布——人要能一眼看出「在批什么、几笔」
102
121
  operations: Array.isArray(raw.operations) ? raw.operations : null,
103
122
  ops: Array.isArray(raw.operations) ? raw.operations.length : null,
@@ -118,18 +137,43 @@ export function listPending(L) {
118
137
  entry.oldCandidates = hits.length > 1 ? hits : null
119
138
  }
120
139
  if (raw.kind === "skills") {
121
- const target = skillTargetOf(L, raw.name)
122
- const oldText = target.exists ? fs.readFileSync(target.file, "utf8") : ""
123
- const newText = raw.op === "create" ? raw.text ?? "" : oldText.replace(String(raw.match ?? ""), String(raw.text ?? ""))
124
- Object.assign(entry, {
125
- name: raw.name ?? null,
126
- description: raw.description ?? null,
127
- oldText,
128
- newText,
129
- diff: lineDiff(oldText, newText),
130
- // 过期预判:人不用等批准才知道提案已经跟不上了
131
- stale: raw.op === "create" ? target.exists : !target.exists || (raw.baseHash ? target.hash !== raw.baseHash : false),
132
- })
140
+ if (raw.op === "write_file" || raw.op === "remove_file") {
141
+ const t = skillSupportOf(L, raw)
142
+ let state = "invalid"
143
+ let oldText = null
144
+ if (t.ok) {
145
+ oldText = t.exists ? fs.readFileSync(t.abs, "utf8") : null
146
+ if (raw.op === "remove_file") state = t.exists && t.hash === raw.baseHash ? "ok" : "stale"
147
+ else if (t.exists) state = t.hash === raw.baseHash ? "ok" : "stale"
148
+ else state = raw.baseHash === null ? "new" : "stale"
149
+ }
150
+ const newText = raw.op === "write_file" ? raw.text ?? "" : null
151
+ Object.assign(entry, {
152
+ name: raw.name ?? null,
153
+ filePath: raw.filePath ?? null,
154
+ fileExists: Boolean(t.ok && t.exists),
155
+ baseHash: raw.baseHash ?? null,
156
+ state,
157
+ oldText,
158
+ newText,
159
+ diff: lineDiff(oldText ?? "", newText ?? ""),
160
+ stale: state === "stale" || state === "invalid",
161
+ detail: t.ok ? null : t.error,
162
+ })
163
+ } else {
164
+ const target = skillTargetOf(L, raw.name)
165
+ const oldText = target.exists ? fs.readFileSync(target.file, "utf8") : ""
166
+ const newText = raw.op === "create" ? raw.text ?? "" : oldText.replace(String(raw.match ?? ""), String(raw.text ?? ""))
167
+ Object.assign(entry, {
168
+ name: raw.name ?? null,
169
+ description: raw.description ?? null,
170
+ oldText,
171
+ newText,
172
+ diff: lineDiff(oldText, newText),
173
+ // 过期预判:人不用等批准才知道提案已经跟不上了
174
+ stale: raw.op === "create" ? target.exists : !target.exists || (raw.baseHash ? target.hash !== raw.baseHash : false),
175
+ })
176
+ }
133
177
  }
134
178
  return entry
135
179
  })
@@ -159,6 +203,18 @@ function invalidReason(rec) {
159
203
  if (kind === "skills") {
160
204
  if (!SKILL_OPS.includes(rec.op)) return `未知的技能 op:${String(rec.op)}(可用:${SKILL_OPS.join(" / ")})`
161
205
  if (typeof rec.name !== "string" || !rec.name.trim()) return "技能提案缺少 name"
206
+ if (rec.op === "write_file" || rec.op === "remove_file") {
207
+ if (typeof rec.filePath !== "string" || !rec.filePath.trim()) return `${rec.op} 提案缺少 filePath`
208
+ if (!("baseHash" in rec)) return `${rec.op} 提案缺少 baseHash`
209
+ if (rec.op === "remove_file") {
210
+ if (typeof rec.text === "string" && rec.text.trim()) return "remove_file 提案不该带新内容(text 必须为空)"
211
+ if (!/^[0-9a-f]{64}$/.test(String(rec.baseHash ?? ""))) return "remove_file 必须带旧字节 sha256"
212
+ } else {
213
+ if (typeof rec.text !== "string") return "write_file 提案缺少 text"
214
+ if (rec.baseHash !== null && !/^[0-9a-f]{64}$/.test(String(rec.baseHash))) return "write_file 的 baseHash 必须是 null 或 sha256"
215
+ }
216
+ return null
217
+ }
162
218
  if (typeof rec.text !== "string" || !rec.text.trim()) return `${rec.op} 提案缺少非空 text`
163
219
  if (rec.op === "patch" && (typeof rec.match !== "string" || !rec.match.trim())) return "patch 提案缺少 old_string(match)"
164
220
  return null
@@ -182,7 +238,47 @@ function invalidReason(rec) {
182
238
  * 技能提案:先判过期(源或所有权变了就不许覆盖),再在快照之后按已批准的技能写路径应用。
183
239
  * 过期判据是**内容指纹**:create 要求目标仍不存在;patch 要求目标仍存在、内容仍是当初那份、所有权没变。
184
240
  */
185
- async function approveSkillPending(L, rec, file, who, pendingPath) {
241
+ async function approveSkillPending(L, rec, file, who, pendingPath, expectHash = null) {
242
+ // S5:附属文件动作在批准时重验路径/存在性/旧字节/所有权,失败保留提案。
243
+ if (rec.op === "write_file" || rec.op === "remove_file") {
244
+ const canonical = JSON.stringify({ op: rec.op, kind: "skills", name: rec.name, filePath: rec.filePath, baseHash: rec.baseHash, text: rec.text, createdBy: rec.createdBy })
245
+ const expected = sha256(Buffer.from(canonical))
246
+ if (rec.proposalHash && rec.proposalHash !== expected) {
247
+ return { ok: false, reason: "tampered", file, detail: "提案内容与登记时的哈希不符(待批文件被改过)" }
248
+ }
249
+ if (expectHash && expectHash !== expected) {
250
+ return { ok: false, reason: "stale", file, detail: "提案不是预览时的那一份(expectHash 不匹配)" }
251
+ }
252
+ const locked = withCommitLock(L.lock, () => {
253
+ const t = skillSupportOf(L, rec)
254
+ if (!t.ok) return { ok: false, reason: "stale", file, detail: t.error }
255
+ if (rec.op === "remove_file") {
256
+ if (!t.exists) return { ok: false, reason: "stale", file, detail: "附件在待批期间消失" }
257
+ if (t.hash !== rec.baseHash) return { ok: false, reason: "stale", file, detail: "附件在待批期间被改动" }
258
+ } else if (t.exists) {
259
+ if (t.hash !== rec.baseHash) return { ok: false, reason: "stale", file, detail: "附件在待批期间被改动" }
260
+ } else if (rec.baseHash !== null) {
261
+ return { ok: false, reason: "stale", file, detail: "附件在待批期间消失(提案是按覆盖旧字节提的)" }
262
+ }
263
+ if (rec.createdBy && t.createdBy !== rec.createdBy) {
264
+ return { ok: false, reason: "stale", file, detail: `所有权从 ${rec.createdBy} 变成 ${t.createdBy}` }
265
+ }
266
+ const applied = applySupportFile({
267
+ root: L.root, name: rec.name, action: rec.op, filePath: rec.filePath,
268
+ text: rec.text, expectedBaseHash: rec.baseHash, createdBy: rec.createdBy, origin: "foreground",
269
+ })
270
+ if (!applied.ok) return { ok: false, reason: "apply-failed", file, detail: applied.error ?? "附件写入失败" }
271
+ fs.rmSync(pendingPath, { force: true })
272
+ appendAudit(L, {
273
+ event: "approve", file, op: rec.op, kind: "skills", name: rec.name, filePath: rec.filePath,
274
+ origin: rec.origin ?? "unknown", approvedBy: who, generation: storeHashOf(L.root),
275
+ })
276
+ return { ok: true, file, op: rec.op, kind: "skills", name: rec.name, filePath: rec.filePath,
277
+ origin: rec.origin ?? "unknown", approvedBy: who, pending: listPending(L).length }
278
+ })
279
+ if (!locked.ok) return { ok: false, reason: locked.reason, file }
280
+ return locked.value
281
+ }
186
282
  const target = skillTargetOf(L, rec.name)
187
283
  if (rec.op === "create" && target.exists) {
188
284
  return { ok: false, reason: "stale", file, detail: `同名技能在待批期间出现:${path.relative(L.root, target.file)}` }
@@ -246,7 +342,7 @@ async function approveSkillPending(L, rec, file, who, pendingPath) {
246
342
  *
247
343
  * @returns {{ok:true, file, op, kind, origin, approvedBy, pending}} 或 {{ok:false, reason, ...}}
248
344
  */
249
- export async function approvePending(L, ref, { approvedBy = null } = {}) {
345
+ export async function approvePending(L, ref, { approvedBy = null, expectHash = null } = {}) {
250
346
  const found = resolvePendingRef(L, ref)
251
347
  if (!found.ok) return found
252
348
 
@@ -267,7 +363,7 @@ export async function approvePending(L, ref, { approvedBy = null } = {}) {
267
363
 
268
364
  const kind = rec.kind ?? "memory"
269
365
  // 技能提案:按 kind 分派到技能写路径(不是把批准器放宽成任意写入)。
270
- if (kind === "skills") return await approveSkillPending(L, rec, found.file, who, pendingPath)
366
+ if (kind === "skills") return await approveSkillPending(L, rec, found.file, who, pendingPath, expectHash)
271
367
 
272
368
  const locked = withCommitLock(L.lock, ({ fencing, assertStillOwner }) => {
273
369
  try {
@@ -38,9 +38,15 @@ import { decideWrite } from "./write-approval.mjs"
38
38
  import { scanForThreats } from "./threats.mjs"
39
39
  import { readUsage, recordSkillCreated, bumpSkillPatch, bumpSkillView, updateRecord } from "./skill-usage.mjs"
40
40
  import { archiveSkill } from "./skill-lifecycle.mjs"
41
+ import { snapshotSkills } from "./skill-backup.mjs"
41
42
 
42
43
  /** 动作是封闭枚举:加动作=改工具契约(照 memory-actions 的 extra#4 纪律,无 approve/apply)。 */
43
- export const SKILL_ACTIONS = ["create", "patch", "view", "list", "archive"]
44
+ export const SKILL_ACTIONS = ["create", "patch", "view", "list", "archive", "write_file", "remove_file"]
45
+
46
+ /** 附属文件只允许落在这四个子目录(照 Hermes `_SUPPORT_DIRS` 的同形约束)。 */
47
+ export const SUPPORT_DIRS = ["references", "scripts", "templates", "assets"]
48
+ /** 单个附属文件上限:正文上限 100k 字符留给人读手册,附件只装脚本/模板/素材。 */
49
+ export const MAX_SUPPORT_FILE_BYTES = 1024 * 1024
44
50
 
45
51
  /** description 预算:照 Hermes `SKILL_PROMPT_DESC_LIMIT`(新技能不许吃掉索引的路由信号)。 */
46
52
  export const MAX_DESCRIPTION_LENGTH = 60
@@ -118,6 +124,102 @@ function externalHit(name, externalDirs = []) {
118
124
  return null
119
125
  }
120
126
 
127
+ /** 校验附属文件路径(纯词法):四目录之一 + 至少两段,拒绝对路径/盘符/UNC/`.`/`..`/空段。 */
128
+ export function validateSupportPath(filePath) {
129
+ if (typeof filePath !== "string" || !filePath.length) return "file_path 必填"
130
+ if (filePath.includes("\u0000")) return "file_path 含 NUL"
131
+ if (filePath.startsWith("/") || /^[A-Za-z]:/.test(filePath)) return "只接受技能目录下的相对路径(不许绝对路径/盘符)"
132
+ if (filePath.includes("\\")) return "只接受 POSIX 相对路径(不许反斜杠/UNC)"
133
+ const segs = filePath.split("/")
134
+ if (segs.some((x) => x === "")) return "路径包含空段"
135
+ if (segs.some((x) => x === "." || x === "..")) return "路径不许包含 . 或 .. 段"
136
+ // Windows 会把尾随点/空格、保留名(CON/PRN/AUX/NUL/COM1-9/LPT1-9)别名成别的文件;
137
+ // 这些写法在 Linux 上合法、到 Windows 上会指到意想不到的位置,统一拒绝(不赌平台)。
138
+ for (const seg of segs) {
139
+ if (/[\u0000-\u001f]/.test(seg)) return "路径包含控制字符"
140
+ if (/[<>:"|?*]/.test(seg)) return `路径段含 Windows 禁止字符:${seg}`
141
+ if (/[. ]$/.test(seg)) return `路径段不许以点或空格结尾:${seg}`
142
+ if (/^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(\..*)?$/i.test(seg)) return `路径段是 Windows 保留名:${seg}`
143
+ }
144
+ if (segs.length < 2) return "必须落在 references|scripts|templates|assets 下的文件"
145
+ if (!SUPPORT_DIRS.includes(segs[0])) return `只允许 references|scripts|templates|assets,收到 ${segs[0]}`
146
+ return null
147
+ }
148
+
149
+ /** 逐级检查已存在的祖先里有没有符号链接(解析与落盘前共用同一个判定)。 */
150
+ function hasSymlinkComponent(skillDir, rel) {
151
+ let cur = skillDir
152
+ for (const seg of String(rel).split("/")) {
153
+ cur = path.join(cur, seg)
154
+ try { if (fs.lstatSync(cur).isSymbolicLink()) return true } catch { /* 不存在:继续 */ }
155
+ }
156
+ return false
157
+ }
158
+
159
+ /** 解析并校验真实落点:逐级拒绝符号链接,最终路径必须留在 realpath(技能目录) 内。 */
160
+ export function resolveSupportTarget(skillDir, filePath) {
161
+ const bad = validateSupportPath(filePath)
162
+ if (bad) return { ok: false, error: bad }
163
+ const segs = filePath.split("/")
164
+ if (hasSymlinkComponent(skillDir, filePath)) return { ok: false, error: `路径包含符号链接,拒绝写入:${filePath}` }
165
+ const realRoot = fs.realpathSync(skillDir)
166
+ const abs = path.resolve(skillDir, ...segs)
167
+ if (!abs.startsWith(realRoot + path.sep)) return { ok: false, error: `路径逃逸出技能目录:${filePath}` }
168
+ return { ok: true, abs, rel: segs.join("/"), realRoot }
169
+ }
170
+
171
+ /** 落盘(同步):批准路径与直写路径共用;调用方负责门控与快照外的并发锁。 */
172
+ export function applySupportFile({ root, name, action, filePath, text = null, expectedBaseHash, createdBy, origin, agent = null }) {
173
+ const location = skillFileOf(root, name)
174
+ if (!fs.existsSync(location)) return fail(action, `技能不存在:${name}`, { name })
175
+ const target = resolveSupportTarget(path.dirname(location), filePath)
176
+ if (!target.ok) return fail(action, target.error, { name, location })
177
+ const exists = fs.existsSync(target.abs)
178
+ if (action === "remove_file" && !exists) return fail(action, `附件不存在:${String(filePath)}`, { name, location })
179
+ const baseHash = action === "write_file" ? (exists ? sha256(fs.readFileSync(target.abs)) : null) : (exists ? sha256(fs.readFileSync(target.abs)) : null)
180
+ if (expectedBaseHash !== undefined && baseHash !== expectedBaseHash) {
181
+ return fail(action, "目标在批准前被改动(baseHash 不匹配)", { name, location })
182
+ }
183
+ const snap = snapshotSkills(root, `skill-file:${name}`)
184
+ if (!snap.ok) return fail(action, snap.error ?? "快照失败,未写入", { name, location })
185
+ if (hasSymlinkComponent(path.dirname(location), target.rel)) {
186
+ return fail(action, `路径包含符号链接,拒绝写入:${filePath}`, { name, location })
187
+ }
188
+ if (action === "write_file") fs.mkdirSync(path.dirname(target.abs), { recursive: true })
189
+ const parentReal = fs.realpathSync(path.dirname(target.abs))
190
+ if (!parentReal.startsWith(target.realRoot + path.sep) && parentReal !== target.realRoot) {
191
+ return fail(action, "目标父目录在写入前逃出了技能目录(符号链接?)", { name, location })
192
+ }
193
+ const dst = path.join(parentReal, path.basename(target.abs))
194
+ const before = fs.statSync(parentReal)
195
+ if (action === "write_file") {
196
+ const flags = fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_TRUNC |
197
+ (fs.constants.O_NOFOLLOW ?? 0)
198
+ const fd = fs.openSync(dst, flags, 0o600)
199
+ try {
200
+ const after = fs.statSync(parentReal)
201
+ if (after.dev !== before.dev || after.ino !== before.ino) {
202
+ return fail(action, "目标父目录在打开后发生了变化,拒绝写入", { name, location })
203
+ }
204
+ fs.writeFileSync(fd, text)
205
+ } finally { fs.closeSync(fd) }
206
+ } else {
207
+ const after = fs.statSync(parentReal)
208
+ if (after.dev !== before.dev || after.ino !== before.ino) {
209
+ return fail(action, "目标父目录在删除前发生了变化,拒绝删除", { name, location })
210
+ }
211
+ fs.unlinkSync(dst)
212
+ }
213
+ appendAudit(layout(root), {
214
+ event: action === "write_file" ? "skill-file-write" : "skill-file-remove",
215
+ name, filePath: target.rel, createdBy, origin, agent, baseHash, snapshot: snap.id ?? null,
216
+ })
217
+ return {
218
+ ok: true, action, name, location: target.abs, filePath: target.rel, createdBy,
219
+ receipt: receipt("已交付", { name, location: target.abs, createdBy, detail: `${action === "write_file" ? "写入" : "删除"}附件 ${target.rel}` }),
220
+ }
221
+ }
222
+
121
223
  /**
122
224
  * 跑一个技能动作。返回结构化结果(不抛):成功与失败都带认账 `receipt`。
123
225
  *
@@ -144,6 +246,9 @@ export async function runSkillAction({
144
246
  content = null,
145
247
  old_string = null,
146
248
  new_string = null,
249
+ file_path = null,
250
+ file_content = null,
251
+ expectedBaseHash = undefined,
147
252
  ask = null,
148
253
  hostPermission = null,
149
254
  agentSkillEnabled = true,
@@ -263,6 +368,71 @@ export async function runSkillAction({
263
368
  }
264
369
  }
265
370
 
371
+ // ── S5 附属文件动作:只动四个子目录里的文件,根 SKILL.md 只读 ──────────────
372
+ if (action === "write_file" || action === "remove_file") {
373
+ if (!name) return fail(action, `${action} 需要 name`, { name })
374
+ if (!fs.existsSync(location)) return fail(action, `技能不存在:${name}`, { name })
375
+ // 后台只动 agent-created(与 patch 同一条规则;user-owned 先 adopt)。
376
+ if (origin === "background" && readCreatedBy(location) !== "agent") {
377
+ return { ok: false, action, error: `回合后通道只动 agent-created 技能:${name} 是 ${readCreatedBy(location)}-owned`, receipt: receipt("未生效", { name, location, detail: "非 agent-created" }) }
378
+ }
379
+ const skillDir = path.dirname(location)
380
+ const target = resolveSupportTarget(skillDir, file_path)
381
+ if (!target.ok) return fail(action, target.error, { name, location })
382
+ const exists = fs.existsSync(target.abs)
383
+ let text = null
384
+ let baseHash = null
385
+ let destructive = false
386
+ if (action === "remove_file") {
387
+ if (!exists) return fail(action, `附件不存在:${String(file_path)}`, { name, location })
388
+ baseHash = sha256(fs.readFileSync(target.abs))
389
+ destructive = true
390
+ } else {
391
+ if (typeof file_content !== "string") return fail(action, "write_file 需要 file_content", { name, location })
392
+ const bytes = Buffer.byteLength(file_content, "utf8")
393
+ if (bytes > MAX_SUPPORT_FILE_BYTES) return fail(action, `附件 ${bytes} 字节,超出 ${MAX_SUPPORT_FILE_BYTES} 上限`, { name, location })
394
+ const hits = scanForThreats(String(file_content), { scope: "strict" })
395
+ if (hits.length) return fail(action, `写入被拒:内容命中威胁模式 ${hits.join(", ")}`, { name, location })
396
+ baseHash = exists ? sha256(fs.readFileSync(target.abs)) : null
397
+ destructive = exists // 覆盖已有附件=破坏动作(闸关 + 后台也必须进待批)
398
+ text = file_content
399
+ }
400
+ const fileDecision = hostPermission === "deny"
401
+ ? "deny"
402
+ : approved?.by
403
+ ? "apply"
404
+ : decideWrite({ root, subsystem: "skills", origin, destructive, interactive: typeof ask === "function", hostPermission })
405
+ if (fileDecision === "deny") {
406
+ return { ok: false, action, error: "宿主权限闸拒绝了这次写入", receipt: receipt("未生效", { name, location, detail: "permission deny" }) }
407
+ }
408
+ if (fileDecision === "stage") {
409
+ const store = createMemoryStore({ root, identity: { origin, agent: identity?.agent ?? null } })
410
+ const proposal = {
411
+ op: action,
412
+ kind: "skills",
413
+ name,
414
+ filePath: target.rel,
415
+ baseHash,
416
+ text,
417
+ createdBy,
418
+ }
419
+ // 提案内容哈希:预览读到的就是它;批准时可带 expectHash 把「预览的那一份」钉住。
420
+ proposal.proposalHash = sha256(Buffer.from(JSON.stringify(proposal)))
421
+ const file = store.stageProposal(proposal)
422
+ return {
423
+ ok: true,
424
+ action,
425
+ staged: true,
426
+ file,
427
+ receipt: receipt("待批", { name, location: target.abs, detail: `进待批队列(${action} ${target.rel})`, createdBy }),
428
+ }
429
+ }
430
+ return applySupportFile({
431
+ root, name, action, filePath: file_path, text,
432
+ expectedBaseHash, createdBy: readCreatedBy(location), origin, agent: identity?.agent ?? null,
433
+ })
434
+ }
435
+
266
436
  let body = null
267
437
  if (action === "create") {
268
438
  const errs = [validateDescription(description), validateContent(content)].filter(Boolean)