@lmzhen/dsh-evolution-core 0.59.1 → 0.59.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.
Files changed (41) hide show
  1. package/lib/authority-plugin.js +7 -4
  2. package/lib/{extract-plan-BxDhKSki.js → extract-plan-D3ALlAmN.js} +2 -2
  3. package/lib/extract.js +4 -4
  4. package/lib/index.js +9 -9
  5. package/lib/io-node.js +1 -1
  6. package/lib/{mutation-authority-Du-ON0NY.js → mutation-authority-CZpc9F20.js} +222 -4
  7. package/lib/{mutation-storage-adapter-7R3ra0wj.js → mutation-storage-adapter-z1_hyrQn.js} +10 -6
  8. package/lib/{mutations-mvTnWkua.js → mutations-Y-wKod7W.js} +2 -2
  9. package/lib/{quality-CREp6s1G.js → quality-NPGr3VzA.js} +3 -3
  10. package/lib/{review-context-CW_kJAzn.js → review-context-yNiZadPw.js} +1 -1
  11. package/lib/{skill-history-YX84wO20.js → skill-history-BvLWFoOo.js} +2 -2
  12. package/lib/skills.js +1023 -189
  13. package/lib/types/authority-plugin.d.ts +7 -1
  14. package/lib/types/authority-plugin.js +10 -2
  15. package/lib/types/authority.d.ts +49 -0
  16. package/lib/types/authority.js +194 -0
  17. package/lib/types/events.d.ts +2 -0
  18. package/lib/types/mutation-authority.d.ts +31 -2
  19. package/lib/types/mutation-authority.js +45 -1
  20. package/lib/types/mutation-unit.d.ts +23 -1
  21. package/lib/types/mutation-unit.js +7 -3
  22. package/lib/types/skill-observation-source.d.ts +26 -0
  23. package/lib/types/skill-observation-source.js +56 -0
  24. package/lib/types/skill-observation.d.ts +87 -0
  25. package/lib/types/skill-observation.js +110 -0
  26. package/lib/types/skill-root-gate.d.ts +40 -0
  27. package/lib/types/skill-root-gate.js +98 -0
  28. package/lib/types/skill-store.d.ts +22 -3
  29. package/lib/types/skill-store.js +437 -217
  30. package/lib/types/skill-target-locks.d.ts +39 -0
  31. package/lib/types/skill-target-locks.js +64 -0
  32. package/lib/types/skill-write-intent.d.ts +63 -0
  33. package/lib/types/skill-write-intent.js +104 -0
  34. package/lib/types/skill-write-service.d.ts +85 -0
  35. package/lib/types/skill-write-service.js +180 -0
  36. package/lib/types/skills.d.ts +6 -0
  37. package/lib/types/skills.js +6 -0
  38. package/lib/{usage-DrczLTP4.js → usage-D7yHG2Cb.js} +2 -2
  39. package/lib/write.js +3 -3
  40. package/package.json +3 -3
  41. package/lib/{io-GxghO3Ip.js → io-Cpa8wuvj.js} +1 -1
package/lib/skills.js CHANGED
@@ -1,15 +1,15 @@
1
- import { _ as probeMtime, b as probeText, c as transactIo, d as isAbsent, g as probeList, h as probeAbsent, i as isCommittedWarning, m as isUnknown, o as nodeEvolutionIo, p as isPresent, t as TransactionNotInvokedError, v as probePresent, x as probeUnknown, y as probeReason } from "./io-GxghO3Ip.js";
2
- import { n as mutationLockFrom } from "./mutation-authority-Du-ON0NY.js";
1
+ import { _ as probeMtime, b as probeText, c as transactIo, d as isAbsent, g as probeList, h as probeAbsent, i as isCommittedWarning, m as isUnknown, o as nodeEvolutionIo, p as isPresent, t as TransactionNotInvokedError, v as probePresent, x as probeUnknown, y as probeReason } from "./io-Cpa8wuvj.js";
2
+ import { i as mutationLockFrom } from "./mutation-authority-CZpc9F20.js";
3
3
  import { o as resolveCitations } from "./citations-CZKTUGQF.js";
4
4
  import { Q as SUPPORT_DIRS, Z as SKILL_NAME_RE, a as DEFAULT_SUPPORT_FILE_CHAR_POLICY, i as DEFAULT_SKILL_LIMITS, n as DEFAULT_CITATION_POLICY, o as POLICY_STAGE_DEFAULTS, q as PROTECTED_BUILTIN_SKILLS, r as DEFAULT_REFERENCE_REWRITE_POLICY, s as policyStageLimits, t as DEFAULT_ARCHIVE_RETENTION_POLICY, u as CONTENT_SPLIT_HINT } from "./limits-CO4JGSJL.js";
5
- import { B as READ_REQUIRED_ACTIONS, C as appendEvolutionEvent, F as lintBody, H as isUnreadWrite, I as softBodyTokenBudget, L as RULES, M as HEALTH_STAMP_RE, N as MIN_STAMP_BODY_CHARS, P as assessStructureHealth, R as diffFindings, U as sessionReadSkillNames, V as filterUnreadSkillOps, W as sessionReadSupportFiles, _ as fuzzyPatch, a as isReviewChannelSession, d as scanContentThreats, j as DEFAULT_HEALTH_THRESHOLDS, m as makeSerialQueue, q as authorityFrom, t as currentReviewContext, v as trimPatternBoundaries, w as eventsFile, z as lintSkill } from "./review-context-CW_kJAzn.js";
5
+ import { B as READ_REQUIRED_ACTIONS, C as appendEvolutionEvent, F as lintBody, H as isUnreadWrite, I as softBodyTokenBudget, L as RULES, M as HEALTH_STAMP_RE, N as MIN_STAMP_BODY_CHARS, P as assessStructureHealth, R as diffFindings, U as sessionReadSkillNames, V as filterUnreadSkillOps, W as sessionReadSupportFiles, _ as fuzzyPatch, a as isReviewChannelSession, d as scanContentThreats, j as DEFAULT_HEALTH_THRESHOLDS, m as makeSerialQueue, q as authorityFrom, t as currentReviewContext, v as trimPatternBoundaries, w as eventsFile, z as lintSkill } from "./review-context-yNiZadPw.js";
6
6
  import { a as measureUnit } from "./text-metrics-CyJhxWBs.js";
7
- import { E as usageFile, F as describeReferenceRewrite, I as planReferenceRewrite, L as planRehoming, N as supportRefs, O as selectSections, P as applyReferenceRewrite, _ as loadUsage, p as getRecord, w as suppressedFile, y as mutateUsage } from "./usage-DrczLTP4.js";
8
- import { _ as validateFrontmatter, c as ensureSkillFrontmatter, d as frontmatterCatalogInvalid, f as normalizeFrontmatter, g as skillMdOnDisk, h as shrinksOverLimit, i as loadMutations, l as exceedsContentLimit, m as relatedSkillNames, o as recordMutation, p as parseFrontmatter, r as contentHash, s as authoringFeedback, u as frontmatterBlock, v as yamlPlainScalarNeedsQuotes } from "./mutations-mvTnWkua.js";
7
+ import { E as usageFile, F as describeReferenceRewrite, I as planReferenceRewrite, L as planRehoming, N as supportRefs, O as selectSections, P as applyReferenceRewrite, _ as loadUsage, p as getRecord, w as suppressedFile, y as mutateUsage } from "./usage-D7yHG2Cb.js";
8
+ import { _ as validateFrontmatter, c as ensureSkillFrontmatter, d as frontmatterCatalogInvalid, f as normalizeFrontmatter, g as skillMdOnDisk, h as shrinksOverLimit, i as loadMutations, l as exceedsContentLimit, m as relatedSkillNames, o as recordMutation, p as parseFrontmatter, r as contentHash, s as authoringFeedback, u as frontmatterBlock, v as yamlPlainScalarNeedsQuotes } from "./mutations-Y-wKod7W.js";
9
9
  import { n as evolutionRoot } from "./state-store-Jpa-iYIZ.js";
10
- import { C as partitionVersions, D as textDiffFacts, E as summaryChars, O as versionActionKind, S as parseHistoryIndex, T as recordVersions, _ as loadVersionContent, a as RETENTION_FEEDBACK_KEEP_RATIO, b as normalizeChangeSummary, c as TEXT_DIFF_MAX_LINES, d as contentRetentionFeedback, f as elapsedSince, g as latestVersionAt, h as historyRoot, i as HISTORY_INDEX_VERSION, k as versionTarget, l as blobPath, m as historyIndexFile, n as DEFAULT_SKILL_WRITE_SUMMARY_CHARS, o as RETENTION_FEEDBACK_MIN_CHARS, p as entryTarget, r as HISTORY_DIR, s as TEXT_DIFF_MAX_CHARS, t as BASELINE_ACTION, u as clipChangeSummary, v as loadVersions, w as readHistoryIndex, x as orderVersions, y as nextHistoryIndex } from "./skill-history-YX84wO20.js";
11
- import { D as fileMutationLock, E as MutationUnit, n as unitJournalPort, r as unitSnapshotPort, t as pruneTreeChangeUnits } from "./mutation-storage-adapter-7R3ra0wj.js";
12
- import { n as projectExtractBodies } from "./extract-plan-BxDhKSki.js";
10
+ import { C as partitionVersions, D as textDiffFacts, E as summaryChars, O as versionActionKind, S as parseHistoryIndex, T as recordVersions, _ as loadVersionContent, a as RETENTION_FEEDBACK_KEEP_RATIO, b as normalizeChangeSummary, c as TEXT_DIFF_MAX_LINES, d as contentRetentionFeedback, f as elapsedSince, g as latestVersionAt, h as historyRoot, i as HISTORY_INDEX_VERSION, k as versionTarget, l as blobPath, m as historyIndexFile, n as DEFAULT_SKILL_WRITE_SUMMARY_CHARS, o as RETENTION_FEEDBACK_MIN_CHARS, p as entryTarget, r as HISTORY_DIR, s as TEXT_DIFF_MAX_CHARS, t as BASELINE_ACTION, u as clipChangeSummary, v as loadVersions, w as readHistoryIndex, x as orderVersions, y as nextHistoryIndex } from "./skill-history-BvLWFoOo.js";
11
+ import { D as fileMutationLock, E as MutationUnit, n as unitJournalPort, r as unitSnapshotPort, t as pruneTreeChangeUnits } from "./mutation-storage-adapter-z1_hyrQn.js";
12
+ import { n as projectExtractBodies } from "./extract-plan-D3ALlAmN.js";
13
13
  import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
14
14
  //#region lib/types/skill-stats.js
15
15
  /**
@@ -169,6 +169,636 @@ const SKILL_OPERATIONS = Object.freeze([
169
169
  }
170
170
  ]);
171
171
  //#endregion
172
+ //#region lib/types/skill-observation.js
173
+ /**
174
+ * Skill write observation: the domain-level counterpart of platform
175
+ * `fs-observation-policy`.
176
+ *
177
+ * A successful read records `present(version)` or `absent` for one owner
178
+ * (session / review task / run identity) and one target. Writes later derive
179
+ * their expected version from this store; observations never cross owners.
180
+ *
181
+ * This module is intentionally dependency-free and has no enforcement: Phase A
182
+ * only collects observations. The SkillWriteService switches writes onto them
183
+ * in a later phase, so existing behavior cannot change from this file alone.
184
+ *
185
+ * @module @lmzhen/dsh-evolution-core/skill-observation
186
+ */
187
+ /**
188
+ * Canonical target key. Skill names are trimmed; support paths are slash
189
+ * normalized and collapsed. The key is never a filesystem path, so it cannot
190
+ * leak a host-specific separator into persistence or diagnostics.
191
+ * @param skill - raw skill name supplied by a caller.
192
+ * @param relPath - empty for SKILL.md, otherwise the support-file path.
193
+ * @returns the normalized target.
194
+ */
195
+ function skillTarget(skill, relPath = "") {
196
+ const name = skill.trim();
197
+ if (name === "") throw new Error("skillTarget requires a skill name");
198
+ const rel = normalizeRelPath(relPath);
199
+ return {
200
+ skill: name,
201
+ relPath: rel,
202
+ targetKey: name + "::" + rel
203
+ };
204
+ }
205
+ /** The namespace lock key covering every file of one skill. */
206
+ function skillNamespaceKey(skill) {
207
+ const name = skill.trim();
208
+ if (name === "") throw new Error("skillNamespaceKey requires a skill name");
209
+ return "skill::" + name + "::*";
210
+ }
211
+ /** The SKILL.md target of one skill. */
212
+ function skillBodyTarget(skill) {
213
+ return skillTarget(skill, "");
214
+ }
215
+ /** One support-file target of one skill. */
216
+ function skillSupportTarget(skill, relPath) {
217
+ if (normalizeRelPath(relPath) === "") throw new Error("skillSupportTarget requires a non-empty support path");
218
+ return skillTarget(skill, relPath);
219
+ }
220
+ /** Derive the version a write must observe for these current bytes. */
221
+ function skillVersionOf(content) {
222
+ return contentHash(content);
223
+ }
224
+ /** Normalize a support path to forward slashes, without leading/trailing ones. */
225
+ function normalizeRelPath(relPath) {
226
+ const slashed = relPath.replaceAll("\\", "/");
227
+ if (slashed.startsWith("/") || /^[A-Za-z]:/.test(slashed)) throw new Error("skill support paths must be relative");
228
+ const parts = slashed.split("/");
229
+ if (parts.includes("..")) throw new Error("skill support paths must not contain \"..\"");
230
+ return parts.filter((part) => part !== "" && part !== ".").join("/");
231
+ }
232
+ /**
233
+ * Per-owner observation state. A WeakMap owner key keeps a collected session or
234
+ * review task from retaining its reads; disposal blocks HMR from carrying stale
235
+ * observations into a new implementation generation.
236
+ */
237
+ var SkillObservationStore = class {
238
+ byOwner = /* @__PURE__ */ new WeakMap();
239
+ /**
240
+ * Record one successful read observation.
241
+ * @param owner - exact reading identity; never a shared global.
242
+ * @param target - the read target.
243
+ * @param observation - `present` with the read version, or `absent`.
244
+ */
245
+ record(owner, target, observation) {
246
+ let reads = this.byOwner.get(owner);
247
+ if (reads === void 0) {
248
+ reads = /* @__PURE__ */ new Map();
249
+ this.byOwner.set(owner, reads);
250
+ }
251
+ reads.set(target.targetKey, observation);
252
+ }
253
+ /**
254
+ * Read the newest observation for one owner/target.
255
+ * @returns the observation, or `undefined` when this owner never read it.
256
+ */
257
+ get(owner, target) {
258
+ return this.byOwner.get(owner)?.get(target.targetKey);
259
+ }
260
+ /**
261
+ * Resolve the observation a writer may rely on.
262
+ * @returns the present version, or the refusal that names why it is unusable.
263
+ */
264
+ requirePresent(owner, target) {
265
+ const observation = this.get(owner, target);
266
+ if (observation === void 0) return { kind: "unobserved" };
267
+ if (observation.kind === "absent") return { kind: "absent" };
268
+ return { version: observation.version };
269
+ }
270
+ /** Drop every observation, e.g. on plugin disposal or HMR. */
271
+ clear() {
272
+ this.byOwner = /* @__PURE__ */ new WeakMap();
273
+ }
274
+ };
275
+ //#endregion
276
+ //#region lib/types/skill-observation-source.js
277
+ /**
278
+ * Map framework filesystem observations onto skill targets.
279
+ *
280
+ * The platform emits `fs/observed(target, observation, actor)` after a
281
+ * successful read. This module is the skill-domain edge: it decides whether a
282
+ * host path names SKILL.md or a support file under one skill, and records the
283
+ * platform's opaque version in a {@link SkillObservationStore}.
284
+ *
285
+ * It deliberately does not decide which version model wins (platform FsVersion
286
+ * vs content sha256); that choice belongs to the SkillWriteService phase. Its
287
+ * only job is path-to-target identity, so an observation and a later write
288
+ * cannot disagree about which skill file they mean.
289
+ *
290
+ * @module @lmzhen/dsh-evolution-core/skill-observation-source
291
+ */
292
+ /**
293
+ * Resolve a host path under the skills root to one skill file.
294
+ * @param root - absolute skills root.
295
+ * @param hostPath - absolute path reported by the platform observation.
296
+ * @returns the target, or `undefined` when the path is outside the root, points
297
+ * at the root itself, or is not a skill file (`SKILL.md` / a support file).
298
+ */
299
+ function skillTargetFromHostPath(root, hostPath) {
300
+ if (!isAbsolute(root) || !isAbsolute(hostPath)) return void 0;
301
+ const rel = relative(resolve(root), resolve(hostPath)).replaceAll("\\", "/");
302
+ if (rel === "" || rel.startsWith("../") || rel === ".." || isAbsolute(rel)) return void 0;
303
+ const parts = rel.split("/").filter((part) => part !== "" && part !== ".");
304
+ if (parts.length < 2) return void 0;
305
+ const [skill, ...rest] = parts;
306
+ if (skill === void 0 || skill === "") return void 0;
307
+ if (rest.length === 1 && rest[0] === "SKILL.md") return skillBodyTarget(skill);
308
+ return skillSupportTarget(skill, rest.join("/"));
309
+ }
310
+ /**
311
+ * Record one platform observation when it names a skill file.
312
+ * @param store - the per-context observation store.
313
+ * @param owner - exact reading identity (session / review task / run object).
314
+ * @param root - absolute skills root.
315
+ * @param observation - host path and opaque version from the platform event.
316
+ * @returns the recorded target, or `undefined` when the path is not a skill file.
317
+ */
318
+ function recordFsSkillObservation(store, owner, root, observation) {
319
+ const target = skillTargetFromHostPath(root, observation.hostPath);
320
+ if (target === void 0) return void 0;
321
+ store.record(owner, target, {
322
+ kind: "present",
323
+ version: observation.version
324
+ });
325
+ return target;
326
+ }
327
+ //#endregion
328
+ //#region lib/types/skill-write-intent.js
329
+ /**
330
+ * Pure write-intent decision: the smallest authority primitive behind
331
+ * `SkillWriteService`.
332
+ *
333
+ * The caller supplies the *current* bytes and version it read under its own
334
+ * lock. This module decides whether the intent may write, and for `edit`
335
+ * performs the literal match after the version check. It has no IO, lock or
336
+ * session model, so the same rules can be tested and reused by the library,
337
+ * approval replay and unit transactions.
338
+ *
339
+ * Version values are opaque here: a caller using platform `FsVersion` passes
340
+ * that token, a caller that owns canonical bytes passes the content hash. The
341
+ * decision only compares equality; it never reinterprets a token.
342
+ *
343
+ * @module @lmzhen/dsh-evolution-core/skill-write-intent
344
+ */
345
+ /**
346
+ * Content version used when the caller owns canonical bytes (SkillLibrary
347
+ * reads). Platform-read observations use the platform token instead.
348
+ * @param content - canonical text.
349
+ * @returns sha256 of LF-normalized content.
350
+ */
351
+ function skillContentVersion(content) {
352
+ return contentHash(content);
353
+ }
354
+ /**
355
+ * Decide one write against the current state.
356
+ * @param intent - the requested create/replace/edit.
357
+ * @param current - the target state read under the caller's write lock.
358
+ * @returns either the exact next bytes, or a typed refusal.
359
+ */
360
+ function decideSkillWrite(intent, current) {
361
+ switch (intent.kind) {
362
+ case "createIfAbsent": return current.kind === "absent" ? {
363
+ kind: "write",
364
+ next: intent.next,
365
+ replacements: 0
366
+ } : {
367
+ kind: "refuse",
368
+ reason: "already-exists",
369
+ message: "skill target already exists"
370
+ };
371
+ case "replaceIfVersion":
372
+ if (current.kind === "absent") return {
373
+ kind: "refuse",
374
+ reason: "not-found",
375
+ message: "skill target does not exist"
376
+ };
377
+ if (current.version !== intent.expected) return {
378
+ kind: "refuse",
379
+ reason: "stale",
380
+ message: "skill target changed since it was read"
381
+ };
382
+ return {
383
+ kind: "write",
384
+ next: intent.next,
385
+ replacements: 0
386
+ };
387
+ case "editIfVersion":
388
+ if (current.kind === "absent") return {
389
+ kind: "refuse",
390
+ reason: "not-found",
391
+ message: "skill target does not exist"
392
+ };
393
+ if (current.version !== intent.expected) return {
394
+ kind: "refuse",
395
+ reason: "stale",
396
+ message: "skill target changed since it was read"
397
+ };
398
+ return decideLiteralEdit(current.content, intent.oldString, intent.newString, intent.replaceAll === true);
399
+ }
400
+ }
401
+ /**
402
+ * Apply one literal edit after the caller already checked the version.
403
+ * @param content - current content.
404
+ * @param oldString - exact literal to replace.
405
+ * @param newString - replacement.
406
+ * @param replaceAll - explicit all-occurrences mode; default is unique-match.
407
+ * @returns write decision with replacement count, or a typed refusal.
408
+ */
409
+ function decideLiteralEdit(content, oldString, newString, replaceAll) {
410
+ if (oldString.length === 0) return {
411
+ kind: "refuse",
412
+ reason: "invalid",
413
+ message: "old_string must be a non-empty string"
414
+ };
415
+ if (oldString === newString) return {
416
+ kind: "refuse",
417
+ reason: "invalid",
418
+ message: "old_string and new_string must differ"
419
+ };
420
+ const offsets = matchOffsets(content, oldString);
421
+ if (offsets.length === 0) return {
422
+ kind: "refuse",
423
+ reason: "not-found-match",
424
+ message: "old_string did not appear verbatim"
425
+ };
426
+ if (!replaceAll && offsets.length > 1) return {
427
+ kind: "refuse",
428
+ reason: "ambiguous",
429
+ message: "old_string appears more than once; make it unique or set replace_all"
430
+ };
431
+ const first = offsets[0];
432
+ if (first === void 0) return {
433
+ kind: "refuse",
434
+ reason: "not-found-match",
435
+ message: "old_string did not appear verbatim"
436
+ };
437
+ return {
438
+ kind: "write",
439
+ next: replaceAll ? content.split(oldString).join(newString) : content.slice(0, first) + newString + content.slice(first + oldString.length),
440
+ replacements: offsets.length
441
+ };
442
+ }
443
+ /** All non-overlapping occurrences of a literal, in content order. */
444
+ function matchOffsets(content, literal) {
445
+ const offsets = [];
446
+ let from = 0;
447
+ while (from <= content.length - literal.length) {
448
+ const at = content.indexOf(literal, from);
449
+ if (at < 0) break;
450
+ offsets.push(at);
451
+ from = at + literal.length;
452
+ }
453
+ return offsets;
454
+ }
455
+ //#endregion
456
+ //#region lib/types/skill-target-locks.js
457
+ /**
458
+ * Per-target promise locks for skill writes.
459
+ *
460
+ * The current SkillLibrary serial queue is per root, so writes to different
461
+ * skills serialize even though they share no bytes. This table is the
462
+ * replacement primitive: one tail promise per canonical target key, and a
463
+ * multi-target acquisition that takes keys in lexical order to make deadlock
464
+ * impossible. It is deliberately pure (no IO, no timeout) so the service can
465
+ * compose it with transactIo/HomeFence rather than duplicate lock semantics.
466
+ *
467
+ * @module @lmzhen/dsh-evolution-core/skill-target-locks
468
+ */
469
+ /** A lock table keyed by canonical skill target key. */
470
+ var SkillTargetLocks = class {
471
+ tails = /* @__PURE__ */ new Map();
472
+ /**
473
+ * Run one task while holding one target key.
474
+ * @param targetKey - canonical skill target key.
475
+ * @param task - the read/compare/write critical section.
476
+ * @returns the task's value.
477
+ */
478
+ async withLock(targetKey, task) {
479
+ return await this.withLocks([targetKey], task);
480
+ }
481
+ /**
482
+ * Run one task while holding several target keys.
483
+ *
484
+ * Keys are deduplicated and acquired in lexical order; the caller may pass
485
+ * them in any order. A task must not call {@link withLock}/{@link withLocks}
486
+ * for a key it already holds (the promise chain is not reentrant), so callers
487
+ * should flatten multi-file units into one acquisition.
488
+ * @param targetKeys - canonical target keys touched by the unit.
489
+ * @param task - the unit's read/compare/write critical section.
490
+ * @returns the task's value.
491
+ */
492
+ async withLocks(targetKeys, task) {
493
+ const keys = [...new Set(targetKeys)].sort();
494
+ return await this.acquire(keys, 0, task);
495
+ }
496
+ /** Number of live target queues; exposed for leak assertions in tests. */
497
+ get size() {
498
+ return this.tails.size;
499
+ }
500
+ async acquire(keys, index, task) {
501
+ const key = keys[index];
502
+ if (key === void 0) return await task();
503
+ const prior = this.tails.get(key) ?? Promise.resolve();
504
+ let release;
505
+ const gate = new Promise((resolve) => {
506
+ release = resolve;
507
+ });
508
+ const tail = prior.then(() => gate);
509
+ this.tails.set(key, tail);
510
+ await prior;
511
+ try {
512
+ return await this.acquire(keys, index + 1, task);
513
+ } finally {
514
+ release();
515
+ if (this.tails.get(key) === tail) this.tails.delete(key);
516
+ }
517
+ }
518
+ };
519
+ //#endregion
520
+ //#region lib/types/skill-write-service.js
521
+ /**
522
+ * The first service layer over skill observations and the CAS primitive.
523
+ *
524
+ * It is intentionally narrow while Phase C moves behavior off the tool:
525
+ * read records an observation for one owner; update/patch derive their expected
526
+ * version from that observation and execute through the library mutators with a
527
+ * content anchor, so validation/audit/history stay in their existing owner.
528
+ * existing create/update/patch paths keep their behavior.
529
+ *
530
+ * @module @lmzhen/dsh-evolution-core/skill-write-service
531
+ */
532
+ /**
533
+ * Read body/support bytes and record the observation for the exact owner.
534
+ *
535
+ * A read failure is a failed read, not an observation; `null` means the file is
536
+ * authoritatively absent and is recorded as such.
537
+ */
538
+ var SkillWriteService = class {
539
+ library;
540
+ observations;
541
+ locks = new SkillTargetLocks();
542
+ constructor(library, observations) {
543
+ this.library = library;
544
+ this.observations = observations;
545
+ }
546
+ /**
547
+ * Read SKILL.md and record present/absent for this owner.
548
+ * @param owner - exact session/review/run identity.
549
+ * @param name - skill name.
550
+ * @returns the body, or null when absent.
551
+ */
552
+ async readBody(owner, name) {
553
+ const target = skillBodyTarget(name);
554
+ const content = await this.library.read(name);
555
+ this.record(owner, target, content);
556
+ return content;
557
+ }
558
+ /**
559
+ * Read one support file and record present/absent for this owner.
560
+ * @param owner - exact session/review/run identity.
561
+ * @param name - skill name.
562
+ * @param filePath - support path.
563
+ * @returns the bytes, or null when absent.
564
+ */
565
+ async readSupport(owner, name, filePath) {
566
+ const target = skillSupportTarget(name, filePath);
567
+ const content = await this.library.readSupportFile(name, filePath);
568
+ this.record(owner, target, content);
569
+ return content;
570
+ }
571
+ /**
572
+ * Replace SKILL.md only when this owner observed its current version.
573
+ * @param owner - exact writer identity.
574
+ * @param name - skill name.
575
+ * @param content - full next body.
576
+ * @returns write outcome or a typed refusal.
577
+ */
578
+ async updateBody(owner, name, content, origin = "foreground") {
579
+ const target = skillBodyTarget(name);
580
+ const observed = this.observations.requirePresent(owner, target);
581
+ if (!("version" in observed)) return refusal(observed.kind);
582
+ return await this.locks.withLock(target.targetKey, async () => {
583
+ const result = await this.library.update(name, content, origin, anchorOf(observed.version));
584
+ if (result.ok) await this.readBody(owner, name);
585
+ return actionResult(result);
586
+ });
587
+ }
588
+ /**
589
+ * Patch SKILL.md only when this owner observed its current version.
590
+ * @param owner - exact writer identity.
591
+ * @param name - skill name.
592
+ * @param oldString - literal to replace.
593
+ * @param newString - replacement.
594
+ * @param replaceAll - explicit all-occurrences mode.
595
+ * @returns write outcome or a typed refusal.
596
+ */
597
+ async patchBody(owner, name, oldString, newString, replaceAll = false, origin = "foreground") {
598
+ const target = skillBodyTarget(name);
599
+ const observed = this.observations.requirePresent(owner, target);
600
+ if (!("version" in observed)) return refusal(observed.kind);
601
+ return await this.locks.withLock(target.targetKey, async () => {
602
+ const result = await this.library.patch(name, oldString, newString, "", replaceAll, origin, anchorOf(observed.version));
603
+ if (result.ok) await this.readBody(owner, name);
604
+ return actionResult(result);
605
+ });
606
+ }
607
+ /**
608
+ * Replace one support file only when this owner observed its current version.
609
+ * @param owner - exact writer identity.
610
+ * @param name - skill name.
611
+ * @param filePath - support path.
612
+ * @param content - full next bytes.
613
+ * @returns write outcome or a typed refusal.
614
+ */
615
+ async updateSupport(owner, name, filePath, content, origin = "foreground") {
616
+ const target = skillSupportTarget(name, filePath);
617
+ const observed = this.observations.requirePresent(owner, target);
618
+ if (!("version" in observed)) return refusal(observed.kind);
619
+ return await this.locks.withLock(target.targetKey, async () => {
620
+ const result = await this.library.writeSupportFile(name, filePath, content, origin, anchorOf(observed.version));
621
+ if (result.ok) await this.readSupport(owner, name, filePath);
622
+ return actionResult(result);
623
+ });
624
+ }
625
+ /** Remove a support file only after this owner read it at the observed version. */
626
+ async removeSupport(owner, name, filePath, origin = "foreground") {
627
+ const target = skillSupportTarget(name, filePath);
628
+ const observed = this.observations.requirePresent(owner, target);
629
+ if (!("version" in observed)) return refusal(observed.kind);
630
+ return await this.locks.withLock(target.targetKey, async () => {
631
+ const result = await this.library.removeSupportFile(name, filePath, origin, anchorOf(observed.version));
632
+ if (result.ok) this.observations.record(owner, target, { kind: "absent" });
633
+ return actionResult(result);
634
+ });
635
+ }
636
+ /**
637
+ * Create a support file when absent, or update it only after this owner read it.
638
+ * A new support file is a createIfAbsent (no prior read is required); an
639
+ * existing unread file is refused rather than overwritten.
640
+ */
641
+ async writeSupport(owner, name, filePath, content, origin = "foreground") {
642
+ const target = skillSupportTarget(name, filePath);
643
+ const observed = this.observations.get(owner, target);
644
+ if (observed === void 0) {
645
+ if (await this.library.readSupportFile(name, filePath) !== null) return {
646
+ ok: false,
647
+ code: "SKILL_NOT_OBSERVED",
648
+ message: "read the skill target before writing it"
649
+ };
650
+ this.observations.record(owner, target, { kind: "absent" });
651
+ const created = await this.library.writeSupportFile(name, filePath, content, origin);
652
+ if (created.ok) await this.readSupport(owner, name, filePath);
653
+ return actionResult(created);
654
+ }
655
+ if (observed.kind === "absent") {
656
+ const created = await this.library.writeSupportFile(name, filePath, content, origin);
657
+ if (created.ok) await this.readSupport(owner, name, filePath);
658
+ return actionResult(created);
659
+ }
660
+ return await this.updateSupport(owner, name, filePath, content, origin);
661
+ }
662
+ /** Record a just-committed SKILL.md write for this owner (create/fallback path). */
663
+ async observeBodyWrite(owner, name) {
664
+ await this.readBody(owner, name);
665
+ }
666
+ /** Record a just-committed support-file write for this owner (fallback path). */
667
+ async observeSupportWrite(owner, name, filePath) {
668
+ await this.readSupport(owner, name, filePath);
669
+ }
670
+ record(owner, target, content) {
671
+ this.observations.record(owner, target, content === null ? { kind: "absent" } : {
672
+ kind: "present",
673
+ version: contentHash(content)
674
+ });
675
+ }
676
+ };
677
+ function refusal(kind) {
678
+ return kind === "unobserved" ? {
679
+ ok: false,
680
+ code: "SKILL_NOT_OBSERVED",
681
+ message: "read the skill target before writing it"
682
+ } : {
683
+ ok: false,
684
+ code: "SKILL_NOT_FOUND",
685
+ message: "skill target does not exist"
686
+ };
687
+ }
688
+ function anchorOf(version) {
689
+ return { sha256: version };
690
+ }
691
+ function actionResult(result) {
692
+ if (result.ok) return {
693
+ ok: true,
694
+ message: result.message,
695
+ ...result.noop === true ? { noop: true } : {}
696
+ };
697
+ if (result.stale === true) return {
698
+ ok: false,
699
+ code: "SKILL_STALE_VERSION",
700
+ message: result.message
701
+ };
702
+ return {
703
+ ok: false,
704
+ code: "SKILL_INVALID",
705
+ message: result.message
706
+ };
707
+ }
708
+ //#endregion
709
+ //#region lib/types/skill-root-gate.js
710
+ /**
711
+ * Root-level shared/exclusive gate for skill-tree operations.
712
+ *
713
+ * Single-file writes only need the tree to stay structurally stable: they can
714
+ * run under a shared lease plus their per-target lock. Structural operations
715
+ * (archive/restore/consolidate) move or replace whole trees and need an
716
+ * exclusive lease. This gate replaces the implicit "every write is exclusive"
717
+ * per-root serial queue without changing the mutation primitives.
718
+ *
719
+ * The gate is deliberately non-reentrant: a holder must not call read/write
720
+ * again from inside its own section (the queue has no ownership token).
721
+ *
722
+ * @module @lmzhen/dsh-evolution-core/skill-root-gate
723
+ */
724
+ /** A fair-ish shared/exclusive gate. */
725
+ var SkillRootGate = class {
726
+ readers = 0;
727
+ writer = false;
728
+ queue = [];
729
+ /**
730
+ * Run a task under a shared lease.
731
+ * @param task - a single-file mutation that only needs tree stability.
732
+ * @returns the task's value.
733
+ */
734
+ async read(task) {
735
+ await this.acquire(false);
736
+ try {
737
+ return await task();
738
+ } finally {
739
+ this.release(false);
740
+ }
741
+ }
742
+ /**
743
+ * Run a task under an exclusive lease.
744
+ * @param task - a structural mutation that moves/replaces whole trees.
745
+ * @returns the task's value.
746
+ */
747
+ async write(task) {
748
+ await this.acquire(true);
749
+ try {
750
+ return await task();
751
+ } finally {
752
+ this.release(true);
753
+ }
754
+ }
755
+ /** Active shared holders, for leak assertions. */
756
+ get readerCount() {
757
+ return this.readers;
758
+ }
759
+ /** Whether an exclusive holder is active. */
760
+ get writerActive() {
761
+ return this.writer;
762
+ }
763
+ acquire(exclusive) {
764
+ if (!this.writer && (!exclusive || this.readers === 0) && this.queue.length === 0) {
765
+ if (exclusive) this.writer = true;
766
+ else this.readers += 1;
767
+ return Promise.resolve();
768
+ }
769
+ return new Promise((resolve) => {
770
+ this.queue.push({
771
+ exclusive,
772
+ run: resolve
773
+ });
774
+ });
775
+ }
776
+ release(exclusive) {
777
+ if (exclusive) this.writer = false;
778
+ else this.readers -= 1;
779
+ this.drain();
780
+ }
781
+ drain() {
782
+ while (this.queue.length > 0 && !this.writer && this.readers === 0) {
783
+ const next = this.queue[0];
784
+ if (next === void 0) return;
785
+ if (next.exclusive) {
786
+ this.queue.shift();
787
+ this.writer = true;
788
+ next.run();
789
+ return;
790
+ }
791
+ while (this.queue.length > 0 && this.queue[0]?.exclusive === false) {
792
+ const reader = this.queue.shift();
793
+ if (reader === void 0) break;
794
+ this.readers += 1;
795
+ reader.run();
796
+ }
797
+ return;
798
+ }
799
+ }
800
+ };
801
+ //#endregion
172
802
  //#region lib/types/skill-row-cells.js
173
803
  /**
174
804
  * The cells one row shows, decided here and rendered by the client.
@@ -894,6 +1524,16 @@ function sameRevisionAnchor(expected, live) {
894
1524
  if (expected.kind !== live.kind) return false;
895
1525
  return expected.kind === "absent" || expected.sha256 === live.sha256;
896
1526
  }
1527
+ /** One target-lock registry per skill ROOT, shared by every library instance in this process. */
1528
+ const TARGET_LOCKS_BY_ROOT = /* @__PURE__ */ new Map();
1529
+ function targetLocksFor(root) {
1530
+ let locks = TARGET_LOCKS_BY_ROOT.get(root);
1531
+ if (locks === void 0) {
1532
+ locks = new SkillTargetLocks();
1533
+ TARGET_LOCKS_BY_ROOT.set(root, locks);
1534
+ }
1535
+ return locks;
1536
+ }
897
1537
  var SkillLibrary = class {
898
1538
  root;
899
1539
  /** The ONE read face owner/health/panel consume; a thin adapter, not a store. */
@@ -911,6 +1551,10 @@ var SkillLibrary = class {
911
1551
  * one skill never interleave their read-modify-write (the cross-process layer
912
1552
  * is the IO backend's transact lock; this chain is the second layer). */
913
1553
  serial;
1554
+ /** Transitional target locks (same key as SkillWriteService). */
1555
+ targetLocks;
1556
+ /** Root structural gate; simple writes still use the serial until D.5d. */
1557
+ rootGate = new SkillRootGate();
914
1558
  /** V10-03 (P2-18): see the constructor's threatExemptLabels. Empty by
915
1559
  * default — the strict ANY-hit-blocks policy is unchanged. */
916
1560
  threatExemptLabels;
@@ -925,6 +1569,7 @@ var SkillLibrary = class {
925
1569
  historyWarned = false;
926
1570
  constructor(root = skillsRoot(), io = nodeEvolutionIo(), limits = DEFAULT_SKILL_LIMITS, onMutation, transact, threatExemptLabels, authority = CLASS_DEFAULT_AUTHORITY, mutationLock, fence) {
927
1571
  this.root = root;
1572
+ this.targetLocks = targetLocksFor(root);
928
1573
  this.io = io;
929
1574
  this.limits = limits;
930
1575
  this.onMutation = onMutation;
@@ -971,8 +1616,12 @@ var SkillLibrary = class {
971
1616
  sources: roots.map((skill) => ({ skill }))
972
1617
  };
973
1618
  }
974
- async withMutationLock(task) {
975
- const lease = await this.lockPort().acquire();
1619
+ /** Transitional: serialize one target even while the root serial remains. */
1620
+ async withTarget(targetKey, task) {
1621
+ return await this.targetLocks.withLock(targetKey, task);
1622
+ }
1623
+ async withMutationLock(task, targetKeys) {
1624
+ const lease = await this.lockPort().acquire(targetKeys);
976
1625
  try {
977
1626
  return await task();
978
1627
  } finally {
@@ -1029,6 +1678,12 @@ var SkillLibrary = class {
1029
1678
  norm
1030
1679
  };
1031
1680
  }
1681
+ /** True when the injected lock port is per-target rather than the home fence. */
1682
+ keyedTargetLocks() {
1683
+ if (this.mutationLock !== void 0) return this.mutationLock.keyed === true;
1684
+ if (process.env["VITEST"] !== "true" && process.env["NODE_ENV"] !== "test") this.lockPort();
1685
+ return false;
1686
+ }
1032
1687
  lockPort() {
1033
1688
  if (this.mutationLock !== void 0) return this.mutationLock;
1034
1689
  if (process.env["VITEST"] === "true" || process.env["NODE_ENV"] === "test") return fileMutationLock(this.io, this.root);
@@ -1049,14 +1704,32 @@ var SkillLibrary = class {
1049
1704
  /** Recover every prepared tree-change snapshot in the shared unit store. */
1050
1705
  async recoverPreparedUnits() {
1051
1706
  const home = dirname(this.root);
1052
- const results = await this.commitUnit({
1707
+ try {
1708
+ await this.lockPort().repair?.();
1709
+ } catch {}
1710
+ const unit = this.commitUnit({
1053
1711
  limits: {
1054
1712
  maxSkillFileBytes: this.limits.maxSkillFileBytes,
1055
1713
  maxSkillContentChars: this.limits.maxSkillContentChars
1056
1714
  },
1057
1715
  serial: this.serial,
1058
- lock: this.lockPort()
1059
- }).recoverPrepared();
1716
+ lock: this.lockPort(),
1717
+ targetKeysForSnapshot: (snapshot) => {
1718
+ const keys = /* @__PURE__ */ new Set();
1719
+ for (const op of snapshot.ops) {
1720
+ const rel = relative(this.root, op.target);
1721
+ if (rel === "" || rel.startsWith("..") || isAbsolute(rel)) continue;
1722
+ const parts = rel.split(/[\\/]+/);
1723
+ const skill = parts[0];
1724
+ if (skill === void 0 || skill === "") continue;
1725
+ keys.add("skill::" + skill);
1726
+ keys.add(skillNamespaceKey(skill));
1727
+ if (parts.length > 1) keys.add("skill::" + skill + "::" + parts.slice(1).join("/"));
1728
+ }
1729
+ return [...keys];
1730
+ }
1731
+ });
1732
+ const results = await this.rootGate.write(() => unit.recoverPrepared());
1060
1733
  await pruneTreeChangeUnits(this.io, home).catch(() => {});
1061
1734
  return results;
1062
1735
  }
@@ -1692,7 +2365,14 @@ var SkillLibrary = class {
1692
2365
  * marker write is the only state change; content is untouched.
1693
2366
  */
1694
2367
  async setPinned(name, pinned, origin = this.authority.origin) {
1695
- return await this.serial(() => this.setPinnedCore(name, pinned, origin));
2368
+ return await this.rootGate.read(async () => {
2369
+ const lease = await this.lockPort().acquire([skillNamespaceKey(name)]);
2370
+ try {
2371
+ return await this.withTarget("pin::" + name, () => this.setPinnedCore(name, pinned, origin));
2372
+ } finally {
2373
+ await lease.release();
2374
+ }
2375
+ });
1696
2376
  }
1697
2377
  async setPinnedCore(name, pinned, origin) {
1698
2378
  const normalized = name.trim();
@@ -1739,7 +2419,7 @@ var SkillLibrary = class {
1739
2419
  };
1740
2420
  }
1741
2421
  } else await this.io.remove(marker);
1742
- await this.audit(normalized, pinned ? "pin" : "unpin", null, null, pinned ? "pinned" : "unpinned");
2422
+ await this.audit(normalized, pinned ? "pin" : "unpin", null, null, pinned ? "pinned" : "unpinned", void 0, void 0, void 0, void 0, true);
1743
2423
  return {
1744
2424
  ok: true,
1745
2425
  message: `${pinned ? `技能 "${normalized}" 已固定:免受删除、后台复核与生命周期影响。` : `技能 "${normalized}" 已取消固定。`}${durabilityWarning === "" ? "" : ` (警告:写入已落盘,但目录 fsync 失败 —— 持久性未确认:${durabilityWarning})`}`,
@@ -1749,7 +2429,7 @@ var SkillLibrary = class {
1749
2429
  async create(name, content, origin = this.authority.origin, options = {}) {
1750
2430
  await this.ensureRecovered();
1751
2431
  const normalized = name.trim();
1752
- return await this.serial(() => this.withMutationLock(() => this.createCore(normalized, content, origin, options, true)));
2432
+ return await this.rootGate.read(() => this.withTarget("skill::" + normalized, () => this.withMutationLock(() => this.createCore(normalized, content, origin, options, true), ["skill::" + normalized, skillNamespaceKey(normalized)])));
1753
2433
  }
1754
2434
  async createCore(normalized, content, origin, options = {}, fenceHeld = false) {
1755
2435
  const bad = this.badName(normalized);
@@ -1867,7 +2547,7 @@ var SkillLibrary = class {
1867
2547
  async update(rawName, content, origin = this.authority.origin, anchor) {
1868
2548
  const name = rawName.trim();
1869
2549
  await this.ensureRecovered();
1870
- return await this.serial(() => this.updateCore(name, content, origin, anchor));
2550
+ return await this.rootGate.read(() => this.withTarget("skill::" + name, () => this.updateCore(name, content, origin, anchor)));
1871
2551
  }
1872
2552
  async updateCore(name, content, origin, anchor) {
1873
2553
  const badName = this.badName(name);
@@ -1921,6 +2601,7 @@ var SkillLibrary = class {
1921
2601
  maxSkillContentChars: Number.MAX_SAFE_INTEGER
1922
2602
  },
1923
2603
  lock: this.lockPort(),
2604
+ targetKeys: ["skill::" + name, skillNamespaceKey(name)],
1924
2605
  ...this.transact === void 0 ? {} : { transact: this.transact },
1925
2606
  hooks: { committed: async (event) => {
1926
2607
  const op = event.ops[0];
@@ -1977,10 +2658,11 @@ var SkillLibrary = class {
1977
2658
  ...prepared.norm.changed ? { normalizedFrontmatterFields: prepared.norm.fields } : {}
1978
2659
  };
1979
2660
  }
1980
- async patch(rawName, oldString, newString, filePath = "", replaceAll = false, origin = this.authority.origin) {
2661
+ async patch(rawName, oldString, newString, filePath = "", replaceAll = false, origin = this.authority.origin, anchor) {
1981
2662
  await this.ensureRecovered();
1982
2663
  const name = rawName.trim();
1983
- return await this.serial(() => this.patchCore(name, oldString, newString, filePath, replaceAll, origin));
2664
+ const key = "skill::" + name + (filePath === "" ? "" : "::" + filePath.replace(/\\/g, "/"));
2665
+ return await this.rootGate.read(() => this.withTarget(key, () => this.patchCore(name, oldString, newString, filePath, replaceAll, origin, anchor)));
1984
2666
  }
1985
2667
  /**
1986
2668
  * Replace ONE section's content (or one exact sub-block) in place. Keeps the
@@ -2064,7 +2746,7 @@ var SkillLibrary = class {
2064
2746
  path: dir
2065
2747
  };
2066
2748
  }
2067
- async patchCore(name, oldString, newString, filePath, replaceAll, origin) {
2749
+ async patchCore(name, oldString, newString, filePath, replaceAll, origin, anchor) {
2068
2750
  const badName = this.badName(name);
2069
2751
  if (badName) return {
2070
2752
  ok: false,
@@ -2225,6 +2907,8 @@ var SkillLibrary = class {
2225
2907
  message: `文件不存在:${patchLabel}`
2226
2908
  };
2227
2909
  }
2910
+ const verdict = anchorVerdict(anchor, current);
2911
+ if (verdict !== "match") return anchorRefusalFile(name, patchLabel, verdict);
2228
2912
  const outcome = compute(current);
2229
2913
  if (outcome.write === null) {
2230
2914
  if (outcome.hardCapHit !== void 0) await this.recordHardCapHit(name, outcome.hardCapHit.bodyChars, "patch", outcome.hardCapHit.supportFiles);
@@ -2237,6 +2921,7 @@ var SkillLibrary = class {
2237
2921
  maxSkillContentChars: Number.MAX_SAFE_INTEGER
2238
2922
  },
2239
2923
  lock: this.lockPort(),
2924
+ targetKeys: [filePath === "" ? "skill::" + name : "skill::" + name + "::" + filePath.replace(/\\/g, "/"), skillNamespaceKey(name)],
2240
2925
  ...this.transact === void 0 ? {} : { transact: this.transact },
2241
2926
  hooks: { committed: async (event) => {
2242
2927
  await this.audit(name, "patch", outcome.audit?.before ?? current, event.ops[0]?.after ?? onDisk, outcome.audit?.summary ?? `patched ${patchLabel}`, filePath === "" ? void 0 : filePath, event.unitId, { sources: [{ skill: name }] }, origin, true);
@@ -2360,8 +3045,25 @@ var SkillLibrary = class {
2360
3045
  });
2361
3046
  } catch {}
2362
3047
  }
2363
- async archive(rawName, options = {}, origin = this.authority.origin, change) {
2364
- return await this.archiveCore(rawName, options, origin, false, change);
3048
+ async archive(rawName, options = {}, origin = this.authority.origin, change, rootHeld = false, namespaceHeld = false) {
3049
+ if (rootHeld) {
3050
+ if (!this.keyedTargetLocks() || namespaceHeld) return await this.archiveCore(rawName, options, origin, true, change);
3051
+ const lease = await this.lockPort().acquire([skillNamespaceKey(rawName)]);
3052
+ try {
3053
+ return await this.archiveCore(rawName, options, origin, true, change);
3054
+ } finally {
3055
+ await lease.release();
3056
+ }
3057
+ }
3058
+ const namespace = skillNamespaceKey(rawName);
3059
+ return await this.rootGate.write(async () => {
3060
+ const lease = await this.lockPort().acquire([namespace]);
3061
+ try {
3062
+ return await this.archiveCore(rawName, options, origin, true, change);
3063
+ } finally {
3064
+ await lease.release();
3065
+ }
3066
+ });
2365
3067
  }
2366
3068
  async archiveCore(rawName, options, origin, fenceHeld, change) {
2367
3069
  const name = rawName.trim();
@@ -2479,9 +3181,30 @@ var SkillLibrary = class {
2479
3181
  message: `来源技能「${protectedSource}」是受保护的内置技能。`
2480
3182
  };
2481
3183
  const limits = plan.limits ?? this.limits;
2482
- const run = async () => {
3184
+ const serialized = options?.serialized === true;
3185
+ const run = async (sourceHeld) => {
2483
3186
  const fenceHeld = plan.nested === true;
2484
- const archive = (name, archiveOptions) => fenceHeld ? this.archiveCore(name, archiveOptions, plan.origin, true) : this.archive(name, archiveOptions, plan.origin);
3187
+ const keyed = this.keyedTargetLocks();
3188
+ const archive = async (name, archiveOptions) => {
3189
+ if (!fenceHeld) return await this.archive(name, archiveOptions, plan.origin, void 0, true, sourceHeld);
3190
+ if (!keyed || sourceHeld) return await this.archiveCore(name, archiveOptions, plan.origin, true);
3191
+ const lease = await this.lockPort().acquire([skillNamespaceKey(name)]);
3192
+ try {
3193
+ return await this.archiveCore(name, archiveOptions, plan.origin, true);
3194
+ } finally {
3195
+ await lease.release();
3196
+ }
3197
+ };
3198
+ const restore = async (source) => {
3199
+ if (!fenceHeld) return await this.restoreFromArchive(source, plan.origin, true, sourceHeld);
3200
+ if (!keyed || sourceHeld) return await this.restoreFromArchiveCore(source, plan.origin, true);
3201
+ const lease = await this.lockPort().acquire([skillNamespaceKey(source)]);
3202
+ try {
3203
+ return await this.restoreFromArchiveCore(source, plan.origin, true);
3204
+ } finally {
3205
+ await lease.release();
3206
+ }
3207
+ };
2485
3208
  const dir = this.dirOf(target);
2486
3209
  const targetPath = join(dir, "SKILL.md");
2487
3210
  if (!plan.targetExists && await this.io.exists(dir)) return {
@@ -2620,7 +3343,7 @@ var SkillLibrary = class {
2620
3343
  const rollbackSources = async () => {
2621
3344
  const stuck = [];
2622
3345
  for (const source of [...archived].reverse()) try {
2623
- if (!(fenceHeld ? await this.restoreFromArchiveCore(source, plan.origin, true) : await this.restoreFromArchive(source, plan.origin)).ok) stuck.push(source);
3346
+ if (!(await restore(source)).ok) stuck.push(source);
2624
3347
  } catch {
2625
3348
  stuck.push(source);
2626
3349
  }
@@ -2824,7 +3547,17 @@ var SkillLibrary = class {
2824
3547
  mutations: 1 + sources.length
2825
3548
  };
2826
3549
  };
2827
- return options?.serialized === true ? await run() : await this.serial(run);
3550
+ const acquireSourcesAndRun = async () => {
3551
+ const sourceHeld = this.keyedTargetLocks() && sources.length > 0;
3552
+ const lease = sourceHeld ? await this.lockPort().acquire(sources.map(skillNamespaceKey)) : void 0;
3553
+ try {
3554
+ return serialized ? await run(sourceHeld) : await this.serial(() => run(sourceHeld));
3555
+ } finally {
3556
+ if (lease !== void 0) await lease.release();
3557
+ }
3558
+ };
3559
+ if (serialized) return await acquireSourcesAndRun();
3560
+ return await this.rootGate.write(acquireSourcesAndRun);
2828
3561
  }
2829
3562
  /**
2830
3563
  * V2 (design §16.7): what an apply-mode consolidation would do for ONE source,
@@ -2935,166 +3668,173 @@ var SkillLibrary = class {
2935
3668
  ok: false,
2936
3669
  message: `技能「${targetName}」受保护(${targetProtection})。`
2937
3670
  };
2938
- return await this.serial(async () => {
2939
- const referenceWrites = [];
2940
- const rehomed = [];
2941
- const demotedPointers = [];
2942
- const parts = [];
2943
- const plannedSourceBytes = /* @__PURE__ */ new Map();
2944
- if (mode === "append") for (const source of normalizedSources) {
2945
- const protection = await this.deleteProtection(source);
2946
- if (protection) return {
2947
- ok: false,
2948
- message: `技能「${source}」受保护(${protection})。`
2949
- };
2950
- const sourceMd = await this.io.readText(join(this.dirOf(source), "SKILL.md"));
2951
- if (!sourceMd) return {
2952
- ok: false,
2953
- message: `技能「${source}」不存在。`
2954
- };
2955
- const parsed = parseFrontmatter(sourceMd);
2956
- if (!parsed) return {
2957
- ok: false,
2958
- message: `技能「${source}」没有有效的 frontmatter;拒绝合并。`
2959
- };
2960
- const carriesSupport = await this.countSupportDirs(source) > 0;
2961
- const parsedRefs = supportRefs(parsed.body);
2962
- const rawRefs = [...parsed.body.matchAll(/(?:references|scripts|templates|assets)\/[A-Za-z0-9._/-]+/g)].map((match) => match[0]);
2963
- const refs = parsedRefs.length > 0 ? parsedRefs : rawRefs;
2964
- let appendedBody = parsed.body;
2965
- if (carriesSupport || refs.length > 0) {
2966
- const decision = await this.planSourceRehoming(source, targetName, parsed.body, rehomed.map((file) => file.to));
2967
- if (decision.kind === "blocked") return {
2968
- ok: false,
2969
- message: `合并被拒绝:${carriesSupport ? `source "${source}" carries support files` : `source "${source}" body references support files (${refs.join(", ")})`} 会被落下。请改用 mode:'reference',或直接归档整个包。${decision.note}`
2970
- };
2971
- rehomed.push(...decision.files);
2972
- appendedBody = decision.rewritten;
2973
- }
2974
- parts.push(`\n<!-- consolidated from ${source} at ${(/* @__PURE__ */ new Date()).toISOString()} -->\n${appendedBody.trim()}`);
2975
- plannedSourceBytes.set(source, sourceMd);
2976
- }
2977
- else for (const source of normalizedSources) {
2978
- const protection = await this.deleteProtection(source);
2979
- if (protection) return {
2980
- ok: false,
2981
- message: `技能「${source}」受保护(${protection})。`
2982
- };
2983
- const sourceMd = await this.io.readText(join(this.dirOf(source), "SKILL.md"));
2984
- if (!sourceMd) return {
2985
- ok: false,
2986
- message: `技能「${source}」不存在。`
2987
- };
2988
- const parsed = parseFrontmatter(sourceMd);
2989
- if (!parsed) return {
2990
- ok: false,
2991
- message: `技能「${source}」没有有效的 frontmatter;拒绝降级。`
2992
- };
2993
- const refs = supportRefs(parsed.body);
2994
- let demotedBody = parsed.body;
2995
- if (refs.length > 0) {
2996
- const decision = await this.planSourceRehoming(source, targetName, parsed.body, rehomed.map((file) => file.to));
2997
- if (decision.kind === "blocked") return {
2998
- ok: false,
2999
- message: `合并被拒绝:来源技能「${source}」的正文引用了会被落下的支撑文件(${refs.join(", ")}):请改为归档整个包。${decision.note}`
3000
- };
3001
- rehomed.push(...decision.files);
3002
- demotedBody = decision.rewritten;
3003
- }
3004
- const target = join(targetDir, "references", `${source}.md`);
3005
- referenceWrites.push({
3006
- target,
3007
- content: `<!-- demoted from ${source} at ${(/* @__PURE__ */ new Date()).toISOString()} -->\n${demotedBody.trim()}\n`
3008
- });
3009
- demotedPointers.push(pointerBlock(`references/${source}.md`, demotedBody));
3010
- plannedSourceBytes.set(source, sourceMd);
3011
- }
3012
- const archived = [];
3671
+ return await this.rootGate.write(async () => {
3672
+ const sourceLease = this.keyedTargetLocks() ? await this.lockPort().acquire([...normalizedSources].map(skillNamespaceKey)) : void 0;
3013
3673
  try {
3014
- if (!await this.io.readText(join(targetDir, "SKILL.md"))) return {
3015
- ok: false,
3016
- message: `技能「${targetName}」不存在。`
3017
- };
3018
- for (const source of normalizedSources) {
3019
- if (plannedSourceBytes.has(source)) {
3020
- if (await this.io.readText(join(this.dirOf(source), "SKILL.md")) !== plannedSourceBytes.get(source)) throw new Error(`Consolidation aborted: source "${source}" changed while the consolidation ran (its planned bytes are no longer current).`);
3674
+ return await this.serial(async () => {
3675
+ const referenceWrites = [];
3676
+ const rehomed = [];
3677
+ const demotedPointers = [];
3678
+ const parts = [];
3679
+ const plannedSourceBytes = /* @__PURE__ */ new Map();
3680
+ if (mode === "append") for (const source of normalizedSources) {
3681
+ const protection = await this.deleteProtection(source);
3682
+ if (protection) return {
3683
+ ok: false,
3684
+ message: `技能「${source}」受保护(${protection})。`
3685
+ };
3686
+ const sourceMd = await this.io.readText(join(this.dirOf(source), "SKILL.md"));
3687
+ if (!sourceMd) return {
3688
+ ok: false,
3689
+ message: `技能「${source}」不存在。`
3690
+ };
3691
+ const parsed = parseFrontmatter(sourceMd);
3692
+ if (!parsed) return {
3693
+ ok: false,
3694
+ message: `技能「${source}」没有有效的 frontmatter;拒绝合并。`
3695
+ };
3696
+ const carriesSupport = await this.countSupportDirs(source) > 0;
3697
+ const parsedRefs = supportRefs(parsed.body);
3698
+ const rawRefs = [...parsed.body.matchAll(/(?:references|scripts|templates|assets)\/[A-Za-z0-9._/-]+/g)].map((match) => match[0]);
3699
+ const refs = parsedRefs.length > 0 ? parsedRefs : rawRefs;
3700
+ let appendedBody = parsed.body;
3701
+ if (carriesSupport || refs.length > 0) {
3702
+ const decision = await this.planSourceRehoming(source, targetName, parsed.body, rehomed.map((file) => file.to));
3703
+ if (decision.kind === "blocked") return {
3704
+ ok: false,
3705
+ message: `合并被拒绝:${carriesSupport ? `source "${source}" carries support files` : `source "${source}" body references support files (${refs.join(", ")})`} 会被落下。请改用 mode:'reference',或直接归档整个包。${decision.note}`
3706
+ };
3707
+ rehomed.push(...decision.files);
3708
+ appendedBody = decision.rewritten;
3709
+ }
3710
+ parts.push(`\n<!-- consolidated from ${source} at ${(/* @__PURE__ */ new Date()).toISOString()} -->\n${appendedBody.trim()}`);
3711
+ plannedSourceBytes.set(source, sourceMd);
3712
+ }
3713
+ else for (const source of normalizedSources) {
3714
+ const protection = await this.deleteProtection(source);
3715
+ if (protection) return {
3716
+ ok: false,
3717
+ message: `技能「${source}」受保护(${protection})。`
3718
+ };
3719
+ const sourceMd = await this.io.readText(join(this.dirOf(source), "SKILL.md"));
3720
+ if (!sourceMd) return {
3721
+ ok: false,
3722
+ message: `技能「${source}」不存在。`
3723
+ };
3724
+ const parsed = parseFrontmatter(sourceMd);
3725
+ if (!parsed) return {
3726
+ ok: false,
3727
+ message: `技能「${source}」没有有效的 frontmatter;拒绝降级。`
3728
+ };
3729
+ const refs = supportRefs(parsed.body);
3730
+ let demotedBody = parsed.body;
3731
+ if (refs.length > 0) {
3732
+ const decision = await this.planSourceRehoming(source, targetName, parsed.body, rehomed.map((file) => file.to));
3733
+ if (decision.kind === "blocked") return {
3734
+ ok: false,
3735
+ message: `合并被拒绝:来源技能「${source}」的正文引用了会被落下的支撑文件(${refs.join(", ")}):请改为归档整个包。${decision.note}`
3736
+ };
3737
+ rehomed.push(...decision.files);
3738
+ demotedBody = decision.rewritten;
3739
+ }
3740
+ const target = join(targetDir, "references", `${source}.md`);
3741
+ referenceWrites.push({
3742
+ target,
3743
+ content: `<!-- demoted from ${source} at ${(/* @__PURE__ */ new Date()).toISOString()} -->\n${demotedBody.trim()}\n`
3744
+ });
3745
+ demotedPointers.push(pointerBlock(`references/${source}.md`, demotedBody));
3746
+ plannedSourceBytes.set(source, sourceMd);
3747
+ }
3748
+ const archived = [];
3749
+ try {
3750
+ if (!await this.io.readText(join(targetDir, "SKILL.md"))) return {
3751
+ ok: false,
3752
+ message: `技能「${targetName}」不存在。`
3753
+ };
3754
+ for (const source of normalizedSources) {
3755
+ if (plannedSourceBytes.has(source)) {
3756
+ if (await this.io.readText(join(this.dirOf(source), "SKILL.md")) !== plannedSourceBytes.get(source)) throw new Error(`Consolidation aborted: source "${source}" changed while the consolidation ran (its planned bytes are no longer current).`);
3757
+ }
3758
+ const result = await this.archive(source, { absorbedInto: targetName }, void 0, void 0, true, true);
3759
+ if (!result.ok) throw new Error(result.message);
3760
+ archived.push(source);
3761
+ }
3762
+ const freshTargetMd = await this.io.readText(join(targetDir, "SKILL.md"));
3763
+ if (!freshTargetMd) throw new Error(`target "${targetName}" disappeared mid-consolidate`);
3764
+ const writes = [];
3765
+ for (const reference of referenceWrites) {
3766
+ const previous = await this.readForCas(reference.target);
3767
+ const base = previous?.trimEnd() ?? "";
3768
+ writes.push({
3769
+ target: reference.target,
3770
+ content: base === "" ? reference.content : `${base}\n\n${reference.content}`,
3771
+ expected: previous
3772
+ });
3773
+ }
3774
+ for (const file of rehomed) {
3775
+ const target = join(targetDir, ...file.to.split("/"));
3776
+ const previous = await this.readForCas(target);
3777
+ writes.push({
3778
+ target,
3779
+ content: file.content,
3780
+ expected: previous
3781
+ });
3782
+ }
3783
+ if (mode === "append") {
3784
+ const merged = freshTargetMd.trimEnd() + parts.join("\n") + "\n";
3785
+ const validation = validateFrontmatter(merged, targetName, this.limits);
3786
+ if (validation) throw new Error(`merge validation failed: ${validation}`);
3787
+ writes.push({
3788
+ target: join(targetDir, "SKILL.md"),
3789
+ content: merged,
3790
+ expected: freshTargetMd
3791
+ });
3792
+ } else {
3793
+ const pointerLines = demotedPointers.map((lines) => `\n${lines.join("\n")}`).join("");
3794
+ const extended = freshTargetMd.trimEnd() + pointerLines + "\n";
3795
+ const validation = validateFrontmatter(extended, targetName, this.limits);
3796
+ if (validation) throw new Error(`merge validation failed: ${validation}`);
3797
+ writes.push({
3798
+ target: join(targetDir, "SKILL.md"),
3799
+ content: extended,
3800
+ expected: freshTargetMd
3801
+ });
3802
+ }
3803
+ const result = await this.applyTreeChange({
3804
+ name: targetName,
3805
+ origin,
3806
+ protection: "write",
3807
+ writes,
3808
+ auditAction: "consolidate",
3809
+ auditSummary: `consolidated ${normalizedSources.join(", ")} (${mode}) into ${targetName}` + (rehomed.length === 0 ? "" : `; re-homed ${rehomed.map((file) => `${file.from}->${file.to}`).join(", ")}`),
3810
+ eventAction: "consolidate"
3811
+ });
3812
+ if (!result.ok) throw new Error(result.message);
3813
+ return {
3814
+ ok: true,
3815
+ message: `已把 ${normalizedSources.join(", ")} 合并进「${targetName}」。`,
3816
+ path: targetDir
3817
+ };
3818
+ } catch (error) {
3819
+ const reason = error instanceof Error ? error.message : String(error);
3820
+ const failedRestores = [];
3821
+ for (const source of archived.reverse()) try {
3822
+ if (!(await this.restoreFromArchive(source, void 0, true, true)).ok) failedRestores.push(source);
3823
+ } catch {
3824
+ failedRestores.push(source);
3825
+ }
3826
+ if (failedRestores.length > 0) return {
3827
+ ok: false,
3828
+ message: `合并失败(${reason});已回滚,但以下未回滚:${failedRestores.join(", ")}:它们仍在 .archive 里,请用 /evolution skill restore 恢复。`
3829
+ };
3830
+ return {
3831
+ ok: false,
3832
+ message: `合并失败,已回滚:${reason}`
3833
+ };
3021
3834
  }
3022
- const result = await this.archive(source, { absorbedInto: targetName });
3023
- if (!result.ok) throw new Error(result.message);
3024
- archived.push(source);
3025
- }
3026
- const freshTargetMd = await this.io.readText(join(targetDir, "SKILL.md"));
3027
- if (!freshTargetMd) throw new Error(`target "${targetName}" disappeared mid-consolidate`);
3028
- const writes = [];
3029
- for (const reference of referenceWrites) {
3030
- const previous = await this.readForCas(reference.target);
3031
- const base = previous?.trimEnd() ?? "";
3032
- writes.push({
3033
- target: reference.target,
3034
- content: base === "" ? reference.content : `${base}\n\n${reference.content}`,
3035
- expected: previous
3036
- });
3037
- }
3038
- for (const file of rehomed) {
3039
- const target = join(targetDir, ...file.to.split("/"));
3040
- const previous = await this.readForCas(target);
3041
- writes.push({
3042
- target,
3043
- content: file.content,
3044
- expected: previous
3045
- });
3046
- }
3047
- if (mode === "append") {
3048
- const merged = freshTargetMd.trimEnd() + parts.join("\n") + "\n";
3049
- const validation = validateFrontmatter(merged, targetName, this.limits);
3050
- if (validation) throw new Error(`merge validation failed: ${validation}`);
3051
- writes.push({
3052
- target: join(targetDir, "SKILL.md"),
3053
- content: merged,
3054
- expected: freshTargetMd
3055
- });
3056
- } else {
3057
- const pointerLines = demotedPointers.map((lines) => `\n${lines.join("\n")}`).join("");
3058
- const extended = freshTargetMd.trimEnd() + pointerLines + "\n";
3059
- const validation = validateFrontmatter(extended, targetName, this.limits);
3060
- if (validation) throw new Error(`merge validation failed: ${validation}`);
3061
- writes.push({
3062
- target: join(targetDir, "SKILL.md"),
3063
- content: extended,
3064
- expected: freshTargetMd
3065
- });
3066
- }
3067
- const result = await this.applyTreeChange({
3068
- name: targetName,
3069
- origin,
3070
- protection: "write",
3071
- writes,
3072
- auditAction: "consolidate",
3073
- auditSummary: `consolidated ${normalizedSources.join(", ")} (${mode}) into ${targetName}` + (rehomed.length === 0 ? "" : `; re-homed ${rehomed.map((file) => `${file.from}->${file.to}`).join(", ")}`),
3074
- eventAction: "consolidate"
3075
3835
  });
3076
- if (!result.ok) throw new Error(result.message);
3077
- return {
3078
- ok: true,
3079
- message: `已把 ${normalizedSources.join(", ")} 合并进「${targetName}」。`,
3080
- path: targetDir
3081
- };
3082
- } catch (error) {
3083
- const reason = error instanceof Error ? error.message : String(error);
3084
- const failedRestores = [];
3085
- for (const source of archived.reverse()) try {
3086
- if (!(await this.restoreFromArchive(source)).ok) failedRestores.push(source);
3087
- } catch {
3088
- failedRestores.push(source);
3089
- }
3090
- if (failedRestores.length > 0) return {
3091
- ok: false,
3092
- message: `合并失败(${reason});已回滚,但以下未回滚:${failedRestores.join(", ")}:它们仍在 .archive 里,请用 /evolution skill restore 恢复。`
3093
- };
3094
- return {
3095
- ok: false,
3096
- message: `合并失败,已回滚:${reason}`
3097
- };
3836
+ } finally {
3837
+ if (sourceLease !== void 0) await sourceLease.release();
3098
3838
  }
3099
3839
  });
3100
3840
  }
@@ -3113,7 +3853,7 @@ var SkillLibrary = class {
3113
3853
  async restructure(rawName, moves, origin = this.authority.origin, change) {
3114
3854
  const name = rawName.trim();
3115
3855
  await this.ensureRecovered();
3116
- return await this.restructureCore(name, moves, origin, change);
3856
+ return await this.rootGate.write(() => this.restructureCore(name, moves, origin, change));
3117
3857
  }
3118
3858
  async restructureCore(name, moves, origin, change) {
3119
3859
  const badName = this.badName(name);
@@ -3244,6 +3984,7 @@ var SkillLibrary = class {
3244
3984
  },
3245
3985
  serial: this.serial,
3246
3986
  lock: this.lockPort(),
3987
+ targetKeys: [skillNamespaceKey(name)],
3247
3988
  hooks: { committed: async (event) => {
3248
3989
  let headPlaced = false;
3249
3990
  for (const op of event.ops) {
@@ -3298,6 +4039,9 @@ var SkillLibrary = class {
3298
4039
  */
3299
4040
  async extract(plan, origin = this.authority.origin, change) {
3300
4041
  await this.ensureRecovered();
4042
+ return await this.rootGate.write(() => this.extractCore(plan, origin, change));
4043
+ }
4044
+ async extractCore(plan, origin, change) {
3301
4045
  if (plan.outcome === "owner-gap" || plan.owner.mode !== "covered") return {
3302
4046
  ok: false,
3303
4047
  message: "提取被拒绝:owner-gap 不是写操作。"
@@ -3437,6 +4181,7 @@ var SkillLibrary = class {
3437
4181
  },
3438
4182
  serial: this.serial,
3439
4183
  lock: this.lockPort(),
4184
+ targetKeys: [skillNamespaceKey(source), skillNamespaceKey(target)],
3440
4185
  hooks: { committed: async (event) => {
3441
4186
  const provenance = /* @__PURE__ */ new Map();
3442
4187
  for (const move of [...plan.support.shared, ...plan.support.external]) provenance.set(join(targetDir, ...move.to.split("/")), move.provenance);
@@ -3582,6 +4327,7 @@ var SkillLibrary = class {
3582
4327
  const applied = await this.commitUnit({
3583
4328
  limits: this.limits,
3584
4329
  ...plan.nested === true ? { nested: true } : { lock: this.lockPort() },
4330
+ targetKeys: [...new Set(landing.map((entry) => entry.skill))].map(skillNamespaceKey),
3585
4331
  ...this.transact === void 0 ? {} : { transact: this.transact },
3586
4332
  now: () => Date.now()
3587
4333
  }).apply({
@@ -3648,8 +4394,25 @@ var SkillLibrary = class {
3648
4394
  * recoverability: archival never deletes, and this is the control-plane
3649
4395
  * path back. The `.archive-reason` marker is dropped on restore.
3650
4396
  */
3651
- async restoreFromArchive(rawName, origin = this.authority.origin) {
3652
- return await this.restoreFromArchiveCore(rawName, origin, false);
4397
+ async restoreFromArchive(rawName, origin = this.authority.origin, rootHeld = false, namespaceHeld = false) {
4398
+ if (rootHeld) {
4399
+ if (!this.keyedTargetLocks() || namespaceHeld) return await this.restoreFromArchiveCore(rawName, origin, true);
4400
+ const lease = await this.lockPort().acquire([skillNamespaceKey(rawName)]);
4401
+ try {
4402
+ return await this.restoreFromArchiveCore(rawName, origin, true);
4403
+ } finally {
4404
+ await lease.release();
4405
+ }
4406
+ }
4407
+ const namespace = skillNamespaceKey(rawName);
4408
+ return await this.rootGate.write(async () => {
4409
+ const lease = await this.lockPort().acquire([namespace]);
4410
+ try {
4411
+ return await this.restoreFromArchiveCore(rawName, origin, true);
4412
+ } finally {
4413
+ await lease.release();
4414
+ }
4415
+ });
3653
4416
  }
3654
4417
  async restoreFromArchiveCore(rawName, origin, fenceHeld) {
3655
4418
  const name = rawName.trim();
@@ -3751,9 +4514,78 @@ var SkillLibrary = class {
3751
4514
  path: dest
3752
4515
  };
3753
4516
  }
4517
+ /** Result of the low-level CAS primitive. It intentionally has no audit/event. */
4518
+ async writeFileCas(rawName, filePath, intent) {
4519
+ await this.ensureRecovered();
4520
+ const name = rawName.trim();
4521
+ const badName = this.badName(name);
4522
+ if (badName !== null) return {
4523
+ ok: false,
4524
+ message: badName,
4525
+ reason: "invalid"
4526
+ };
4527
+ let target;
4528
+ if (filePath === "") target = join(this.dirOf(name), "SKILL.md");
4529
+ else {
4530
+ const validation = validateSupportPath(filePath);
4531
+ if (validation !== null) return {
4532
+ ok: false,
4533
+ message: validation,
4534
+ reason: "invalid"
4535
+ };
4536
+ target = join(this.dirOf(name), ...filePath.replace(/\\/g, "/").split("/").filter(Boolean));
4537
+ }
4538
+ return await this.serial(() => this.withMutationLock(async () => {
4539
+ let refusal;
4540
+ const apply = (current) => {
4541
+ const decision = decideSkillWrite(intent, current === null ? { kind: "absent" } : {
4542
+ kind: "present",
4543
+ version: contentHash(current),
4544
+ content: current
4545
+ });
4546
+ if (decision.kind === "refuse") {
4547
+ refusal = {
4548
+ reason: decision.reason,
4549
+ message: decision.message
4550
+ };
4551
+ return current;
4552
+ }
4553
+ return decision.next;
4554
+ };
4555
+ let next;
4556
+ if (this.transact !== void 0) {
4557
+ next = null;
4558
+ await this.transact(this.io, target, (current) => {
4559
+ next = apply(current);
4560
+ return next;
4561
+ });
4562
+ } else {
4563
+ const current = await probeText(this.io, target);
4564
+ if (isUnknown(current)) return {
4565
+ ok: false,
4566
+ message: `cannot read ${target}: ${current.reason}`,
4567
+ reason: "invalid"
4568
+ };
4569
+ const value = isPresent(current) ? current.value : null;
4570
+ next = apply(value);
4571
+ if (next !== null && next !== value) await this.io.writeText(target, next);
4572
+ }
4573
+ if (refusal !== void 0) return {
4574
+ ok: false,
4575
+ message: refusal.message,
4576
+ reason: refusal.reason
4577
+ };
4578
+ return {
4579
+ ok: true,
4580
+ message: "skill file written",
4581
+ path: target
4582
+ };
4583
+ }));
4584
+ }
3754
4585
  async writeSupportFile(rawName, filePath, content, origin = this.authority.origin, anchor) {
3755
4586
  const name = rawName.trim();
3756
- return await this.writeSupportFileCore(name, filePath, content, origin, anchor);
4587
+ const key = "skill::" + name + "::" + filePath.replace(/\\/g, "/");
4588
+ return await this.rootGate.read(() => this.withTarget(key, () => this.writeSupportFileCore(name, filePath, content, origin, anchor)));
3757
4589
  }
3758
4590
  async writeSupportFileCore(name, filePath, content, origin, anchor) {
3759
4591
  const badName = this.badName(name);
@@ -3814,6 +4646,7 @@ var SkillLibrary = class {
3814
4646
  },
3815
4647
  serial: this.serial,
3816
4648
  lock: this.lockPort(),
4649
+ targetKeys: ["skill::" + name + "::" + filePath.replace(/\\/g, "/"), skillNamespaceKey(name)],
3817
4650
  ...this.transact === void 0 ? {} : { transact: this.transact },
3818
4651
  hooks: { committed: async (event) => {
3819
4652
  const op = event.ops[0];
@@ -3857,7 +4690,8 @@ var SkillLibrary = class {
3857
4690
  };
3858
4691
  }
3859
4692
  async removeSupportFile(rawName, filePath, origin = this.authority.origin, anchor, unitId) {
3860
- return await this.serial(() => this.removeSupportFileCore(rawName.trim(), filePath, origin, anchor, unitId));
4693
+ const key = "skill::" + rawName.trim() + "::" + filePath.replace(/\\/g, "/");
4694
+ return await this.rootGate.read(() => this.withTarget(key, () => this.removeSupportFileCore(rawName.trim(), filePath, origin, anchor, unitId)));
3861
4695
  }
3862
4696
  async removeSupportFileCore(name, filePath, origin, anchor, unitId) {
3863
4697
  const badName = this.badName(name);
@@ -4335,4 +5169,4 @@ function newSkillLibrary(options) {
4335
5169
  } : void 0, transact, [...threatExemptLabels ?? []], authority, options.mutationLock ?? mutationLockFrom(ctx), options.fence ?? ctx?.get?.("evolutionMutationAuthority")?.homeFence);
4336
5170
  }
4337
5171
  //#endregion
4338
- export { BASELINE_ACTION, DEFAULT_ARCHIVE_RETENTION_POLICY, DEFAULT_CITATION_POLICY, DEFAULT_HEALTH_THRESHOLDS, DEFAULT_REFERENCE_REWRITE_POLICY, DEFAULT_SKILL_LIMITS, DEFAULT_SKILL_WRITE_SUMMARY_CHARS, DEFAULT_SUPPORT_FILE_CHAR_POLICY, HEALTH_STAMP_RE, HISTORY_DIR, HISTORY_INDEX_VERSION, MAX_RESTRUCTURE_MOVES, MIN_STAMP_BODY_CHARS, POLICY_STAGE_DEFAULTS, READ_REQUIRED_ACTIONS, RECENT_USE_WINDOW_DAYS, RESTRUCTURE_TARGET_RE, RETENTION_FEEDBACK_KEEP_RATIO, RETENTION_FEEDBACK_MIN_CHARS, RULES, SKILL_OPERATIONS, SNAPSHOT_EXTRA_NAME_RE, SkillLibrary, SkillModel, TEXT_DIFF_MAX_CHARS, TEXT_DIFF_MAX_LINES, ageCopyKey, anchorVerdict, assertSkillsRootAliasRetired, assessStructureHealth, authoringFeedback, blobPath, clipChangeSummary, compareSkillStats, computeSkillStatsTotals, contentRetentionFeedback, diffFindings, elapsedSince, ensureSkillFrontmatter, entryTarget, exceedsContentLimit, filterSkillStats, filterUnreadSkillOps, frontmatterBlock, frontmatterCatalogInvalid, historyIndexFile, historyRoot, isUnreadWrite, latestActivityAt, latestVersionAt, lintBody, lintSkill, loadVersionContent, loadVersions, markerEntryName, needsAttention, newSkillLibrary, nextHistoryIndex, normalizeChangeSummary, normalizeFrontmatter, orderVersions, parseFrontmatter, parseHistoryIndex, partitionVersions, policyStageLimits, readHistoryIndex, recentlyUsedAt, recordVersions, relatedSkillNames, resolveExecOrigins, resolveOrigins, resolveRootConfig, resolveSkillsRoot, revisionAnchor, revisionAnchorOf, revisionFingerprint, revisionSupportDigest, sessionReadSkillNames, sessionReadSupportFiles, shrinksOverLimit, skillMdOnDisk, skillRowCells, skillStateKey, skillsRoot, softBodyTokenBudget, sortSkillStats, sortValue, summaryChars, textDiffFacts, validateFrontmatter, validateRestructureTarget, validateSupportPath, verdictRank, versionActionKind, versionRowCells, versionTarget, yamlPlainScalarNeedsQuotes };
5172
+ export { BASELINE_ACTION, DEFAULT_ARCHIVE_RETENTION_POLICY, DEFAULT_CITATION_POLICY, DEFAULT_HEALTH_THRESHOLDS, DEFAULT_REFERENCE_REWRITE_POLICY, DEFAULT_SKILL_LIMITS, DEFAULT_SKILL_WRITE_SUMMARY_CHARS, DEFAULT_SUPPORT_FILE_CHAR_POLICY, HEALTH_STAMP_RE, HISTORY_DIR, HISTORY_INDEX_VERSION, MAX_RESTRUCTURE_MOVES, MIN_STAMP_BODY_CHARS, POLICY_STAGE_DEFAULTS, READ_REQUIRED_ACTIONS, RECENT_USE_WINDOW_DAYS, RESTRUCTURE_TARGET_RE, RETENTION_FEEDBACK_KEEP_RATIO, RETENTION_FEEDBACK_MIN_CHARS, RULES, SKILL_OPERATIONS, SNAPSHOT_EXTRA_NAME_RE, SkillLibrary, SkillModel, SkillObservationStore, SkillRootGate, SkillTargetLocks, SkillWriteService, TEXT_DIFF_MAX_CHARS, TEXT_DIFF_MAX_LINES, ageCopyKey, anchorVerdict, assertSkillsRootAliasRetired, assessStructureHealth, authoringFeedback, blobPath, clipChangeSummary, compareSkillStats, computeSkillStatsTotals, contentRetentionFeedback, decideLiteralEdit, decideSkillWrite, diffFindings, elapsedSince, ensureSkillFrontmatter, entryTarget, exceedsContentLimit, filterSkillStats, filterUnreadSkillOps, frontmatterBlock, frontmatterCatalogInvalid, historyIndexFile, historyRoot, isUnreadWrite, latestActivityAt, latestVersionAt, lintBody, lintSkill, loadVersionContent, loadVersions, markerEntryName, needsAttention, newSkillLibrary, nextHistoryIndex, normalizeChangeSummary, normalizeFrontmatter, orderVersions, parseFrontmatter, parseHistoryIndex, partitionVersions, policyStageLimits, readHistoryIndex, recentlyUsedAt, recordFsSkillObservation, recordVersions, relatedSkillNames, resolveExecOrigins, resolveOrigins, resolveRootConfig, resolveSkillsRoot, revisionAnchor, revisionAnchorOf, revisionFingerprint, revisionSupportDigest, sessionReadSkillNames, sessionReadSupportFiles, shrinksOverLimit, skillBodyTarget, skillContentVersion, skillMdOnDisk, skillNamespaceKey, skillRowCells, skillStateKey, skillSupportTarget, skillTarget, skillTargetFromHostPath, skillVersionOf, skillsRoot, softBodyTokenBudget, sortSkillStats, sortValue, summaryChars, textDiffFacts, validateFrontmatter, validateRestructureTarget, validateSupportPath, verdictRank, versionActionKind, versionRowCells, versionTarget, yamlPlainScalarNeedsQuotes };