@lmzhen/dsh-tool-skill-manage 0.49.0 → 0.51.0

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/lib/index.js CHANGED
@@ -1,8 +1,107 @@
1
- import { DEFAULT_ARCHIVE_RETENTION_POLICY, DEFAULT_CITATION_POLICY, DEFAULT_REFERENCE_REWRITE_POLICY, DEFAULT_SKILL_LIMITS, DEFAULT_SKILL_VERSION_KEEP, DEFAULT_SUPPORT_FILE_CHAR_POLICY, DEFAULT_WRITE_CONFIRM_MODE, DEFAULT_WRITE_CONFIRM_TIMEOUT_SECONDS, DSH_AUTHORING_STANDARDS, EXTRACT_PROMPT_V1, SKILLS_GUIDANCE, SKILLS_GUIDANCE_SECTION_ORDER, authorityFrom, buildExtractPlanFromLibrary, callingScope, clampOnce, computeDedupGroups, contentHash, createSubagentChannel, evolutionIoAdapter, fuzzyPatch, isPresent, isUnknown, liveBool, nearDuplicateSummaries, ownerCandidatesFromSummaries, ownerDecisionText, paramRowId, policyStageLimits, probePresent, probeUnknown, projectExtractBodies, proposalFromPlan, protectedSkillNamesOf, readProposalReport, runWriteGates, skillWriteGateContext, unwrapLive, userSetKeys, writeProposalReport } from "@lmzhen/dsh-evolution-core";
1
+ import { defineTool, registerEvolutionTool, settingsPort, skillsPort } from "@lmzhen/dsh-evolution-core/platform";
2
+ import { DEFAULT_ARCHIVE_RETENTION_POLICY, DEFAULT_CITATION_POLICY, DEFAULT_REFERENCE_REWRITE_POLICY, DEFAULT_SKILL_LIMITS, DEFAULT_SKILL_VERSION_KEEP, DEFAULT_SUPPORT_FILE_CHAR_POLICY, DEFAULT_WRITE_CONFIRM_MODE, DEFAULT_WRITE_CONFIRM_TIMEOUT_SECONDS, DSH_AUTHORING_STANDARDS, SKILLS_GUIDANCE, SKILLS_GUIDANCE_SECTION_ORDER, authorityFrom, callingScope, clampOnce, computeDedupGroups, contentHash, createSubagentChannel, currentReviewContext, evolutionIoAdapter, fuzzyPatch, isPresent, isUnknown, liveBool, nearDuplicateSummaries, paramRowId, policyStageLimits, probePresent, probeUnknown, protectedSkillNamesOf, runWriteGates, skillWriteGateContext, unwrapLive, userSetKeys } from "@lmzhen/dsh-evolution-core";
2
3
  import { effectiveSessionPolicy } from "@lmzhen/dsh-evolution-approval";
3
4
  import z from "@deepseek-ai/schemastery";
4
- import { defineTool, registerEvolutionTool } from "@lmzhen/dsh-evolution-core/platform";
5
- import { DEFAULT_HEALTH_THRESHOLDS, anchorVerdict, authoringFeedback, newSkillLibrary, normalizeFrontmatter, parseFrontmatter, resolveExecOrigins, sessionReadSkillNames, sessionReadSupportFiles } from "@lmzhen/dsh-evolution-core/skills";
5
+ import { DEFAULT_HEALTH_THRESHOLDS, DEFAULT_SKILL_WRITE_SUMMARY_CHARS, anchorVerdict, authoringFeedback, newSkillLibrary, normalizeChangeSummary, normalizeFrontmatter, parseFrontmatter, resolveExecOrigins, sessionReadSkillNames, sessionReadSupportFiles } from "@lmzhen/dsh-evolution-core/skills";
6
+ import { EXTRACT_PROMPT_V1, buildExtractPlanFromLibrary, ownerCandidatesFromSummaries, ownerDecisionText, projectExtractBodies, proposalFromPlan, readProposalReport, writeProposalReport } from "@lmzhen/dsh-evolution-core/extract";
7
+ //#region lib/types/skill-actions.js
8
+ const SKILL_ACTIONS = Object.freeze({
9
+ list: {
10
+ mutates: false,
11
+ needsName: false,
12
+ gate: "none",
13
+ summary: "none"
14
+ },
15
+ review: {
16
+ mutates: false,
17
+ needsName: false,
18
+ gate: "none",
19
+ summary: "none"
20
+ },
21
+ create: {
22
+ mutates: true,
23
+ needsName: true,
24
+ gate: "write",
25
+ summary: "host"
26
+ },
27
+ edit: {
28
+ mutates: true,
29
+ needsName: true,
30
+ gate: "write",
31
+ summary: "host"
32
+ },
33
+ update: {
34
+ mutates: true,
35
+ needsName: true,
36
+ gate: "write",
37
+ summary: "host"
38
+ },
39
+ patch: {
40
+ mutates: true,
41
+ needsName: true,
42
+ gate: "write",
43
+ summary: "host"
44
+ },
45
+ delete: {
46
+ mutates: true,
47
+ needsName: true,
48
+ gate: "approval",
49
+ summary: "required"
50
+ },
51
+ write_file: {
52
+ mutates: true,
53
+ needsName: true,
54
+ gate: "write",
55
+ summary: "host"
56
+ },
57
+ remove_file: {
58
+ mutates: true,
59
+ needsName: true,
60
+ gate: "write",
61
+ summary: "host"
62
+ },
63
+ restructure: {
64
+ mutates: true,
65
+ needsName: true,
66
+ gate: "write",
67
+ summary: "required"
68
+ },
69
+ extract: {
70
+ mutates: true,
71
+ needsName: false,
72
+ gate: "write",
73
+ summary: "required"
74
+ },
75
+ feedback: {
76
+ mutates: false,
77
+ needsName: true,
78
+ gate: "none",
79
+ summary: "none"
80
+ },
81
+ pin: {
82
+ mutates: false,
83
+ needsName: true,
84
+ gate: "none",
85
+ summary: "none"
86
+ },
87
+ unpin: {
88
+ mutates: false,
89
+ needsName: true,
90
+ gate: "none",
91
+ summary: "none"
92
+ }
93
+ });
94
+ function skillActionOf(action) {
95
+ return typeof action === "string" && Object.prototype.hasOwnProperty.call(SKILL_ACTIONS, action) ? SKILL_ACTIONS[action] : void 0;
96
+ }
97
+ /** The one commit seam every table-dispatched action passes through. */
98
+ async function commitSkillAction(run) {
99
+ return run();
100
+ }
101
+ function isReadOnlySkillAction(action) {
102
+ return skillActionOf(action)?.mutates === false;
103
+ }
104
+ //#endregion
6
105
  //#region lib/types/index.js
7
106
  /**
8
107
  * Model-facing skill_manage tool over ctx.evolutionIo + ctx.skillUsage.
@@ -23,19 +122,8 @@ import { DEFAULT_HEALTH_THRESHOLDS, anchorVerdict, authoringFeedback, newSkillLi
23
122
  * documented in the README Safety model section.
24
123
  * @module @lmzhen/dsh-tool-skill-manage
25
124
  */
26
- /**
27
- * F-2 (audit v46 / G7.2): the read-only action set used to be spelled out FOUR times in this file
28
- * (usage accounting at the patch_count bump, the cross-source directory exemption, the approval gap
29
- * and the replay exemption). The four USES stay where they are — their neighbouring logic differs —
30
- * but the CRITERION is this one predicate, so adding an action cannot update three of four.
31
- */
32
- const READ_ONLY_ACTIONS = [
33
- "list",
34
- "review",
35
- "pin",
36
- "unpin"
37
- ];
38
- const isReadOnlyAction = (action) => typeof action === "string" && READ_ONLY_ACTIONS.includes(action);
125
+ /** F-2: the read-only criterion is the action table's mutates flag. */
126
+ const isReadOnlyAction = isReadOnlySkillAction;
39
127
  const name = "tool-skill-manage";
40
128
  const inject = [
41
129
  "tools",
@@ -67,6 +155,7 @@ const Config = z.object({
67
155
  threatExemptLabels: z.array(z.string()).default([]),
68
156
  strictCrossSource: z.boolean().default(false).volatile(),
69
157
  skillVersionKeep: z.number().min(1).default(DEFAULT_SKILL_LIMITS.versionKeep ?? DEFAULT_SKILL_VERSION_KEEP),
158
+ skillWriteSummaryChars: z.number().min(1).default(DEFAULT_SKILL_WRITE_SUMMARY_CHARS),
70
159
  skillWriteConfirm: z.union([
71
160
  z.const("auto"),
72
161
  z.const("ask"),
@@ -367,23 +456,24 @@ function reasonOfError(error) {
367
456
  return error instanceof Error ? error.message : String(error);
368
457
  }
369
458
  /**
370
- * The registry's live ROOT agent for this call's session, or `undefined`.
459
+ * The registry's live root agent for this call's session, or `undefined`.
371
460
  *
372
461
  * The registry keys agents by their shared agent/session id (platform `agent`), and the
373
- * platform's `ask()` accepts only an agent that is BOTH its exact live instance and a root —
374
- * that check is `user-questions`'s own private `assertLiveRoot`. An id that resolves to an agent owned by another
375
- * agent is not a root: the caller then proceeds unconfirmed rather than blocking a human question on
376
- * an agent no human is watching.
462
+ * platform's `ask()` accepts only an agent that is BOTH its exact live instance and not a
463
+ * subagent — that check is `user-questions`'s `assertLiveRoot`: it compares
464
+ * `agents.get(id)` identity and rejects `session.header.origin === 'subagent'`. Delegated
465
+ * agents have no independent human, so the caller proceeds unconfirmed instead of blocking a
466
+ * question on an agent no human is watching.
377
467
  * @param probe - the context, read through the optional-service probe.
378
468
  * @param exec - this call's execution context.
379
469
  * @returns the live root agent, when this session has one.
380
470
  */
381
471
  function liveRootAgentOf(probe, exec) {
382
- const agents = probe.get("agents");
472
+ const agents = probe.get("evolutionPlatform")?.ports?.agents;
383
473
  const sessionId = exec.agent?.session?.id;
384
474
  if (agents === void 0 || typeof sessionId !== "string") return void 0;
385
475
  const candidate = agents.get(sessionId);
386
- return candidate !== void 0 && agents.roots().includes(candidate) ? candidate : void 0;
476
+ return candidate !== void 0 && candidate.session?.header?.origin !== "subagent" ? candidate : void 0;
387
477
  }
388
478
  /** The one thing the operator's answer decides: was the confirm label selected? */
389
479
  function confirmedBy(answer, questionId, confirmLabel) {
@@ -391,12 +481,12 @@ function confirmedBy(answer, questionId, confirmLabel) {
391
481
  }
392
482
  function apply(ctx, rawConfig = {}) {
393
483
  ctx.inject(["settings"], (injected) => {
394
- const settings = injected.settings;
395
- if (typeof settings?.configure !== "function") return;
484
+ const settings = settingsPort(injected);
485
+ if (settings?.configure === void 0) return;
396
486
  const disposer = settings.configure({ auto: false }, ctx.fiber);
397
487
  if (typeof disposer === "function") ctx.effect(() => disposer, "tool-skill-manage: settings presentation");
398
488
  });
399
- const systemPrompt = ctx.get("systemPrompt");
489
+ const systemPrompt = ctx.get("evolutionPlatform")?.ports?.systemPrompt;
400
490
  if (systemPrompt) ctx.effect(() => {
401
491
  const disposeVariable = systemPrompt.variable(PROTECTED_SKILLS_VARIABLE, () => protectedSkillsLine());
402
492
  const disposeSection = systemPrompt.section({
@@ -449,7 +539,7 @@ function apply(ctx, rawConfig = {}) {
449
539
  };
450
540
  const isDismissed = (error) => questionErrorCode(error) === "ASK_ABORTED";
451
541
  const confirmSkillWrite = async (request, exec) => {
452
- const questions = probe.get("userQuestions");
542
+ const questions = probe.get("evolutionPlatform")?.ports?.userQuestions;
453
543
  if (questions === void 0) return confirmUnavailable("no user-questions service is mounted");
454
544
  const ask = (agent) => questions.ask({
455
545
  questions: [{
@@ -607,7 +697,7 @@ function apply(ctx, rawConfig = {}) {
607
697
  };
608
698
  };
609
699
  const catalogWinner = async (name) => {
610
- const catalog = ctx.get("skills");
700
+ const catalog = skillsPort(ctx);
611
701
  if (catalog === void 0) return probeUnknown("the skills service is not mounted");
612
702
  const scope = callingScope(ctx);
613
703
  try {
@@ -625,11 +715,36 @@ function apply(ctx, rawConfig = {}) {
625
715
  applyLimits();
626
716
  const action = args.action;
627
717
  const name = args.name ?? "";
718
+ const actionMeta = skillActionOf(action);
719
+ let change;
720
+ if (args.summary !== void 0) {
721
+ const summaryChars = limit("skillWriteSummaryChars", rawConfig.skillWriteSummaryChars, DEFAULT_SKILL_WRITE_SUMMARY_CHARS);
722
+ const normalized = normalizeChangeSummary(args.summary, summaryChars);
723
+ if (!normalized.ok) return {
724
+ ok: false,
725
+ message: normalized.reason === "length" ? `摘要为 ${normalized.length} 个字符,超过上限 ${summaryChars}。` : normalized.reason === "multiline" ? "摘要必须是单行。" : "摘要不能为空。",
726
+ skills: []
727
+ };
728
+ change = {
729
+ text: normalized.text,
730
+ source: "model"
731
+ };
732
+ }
733
+ if (actionMeta?.needsName === true && name === "") return {
734
+ ok: false,
735
+ message: `动作「${action}」需要 name。`,
736
+ skills: []
737
+ };
628
738
  if (action === "extract" && origin === "background_review") return {
629
739
  ok: false,
630
740
  message: "背景审查不能执行 extract:review 只提议;提取必须由显式前台工具/命令执行。",
631
741
  skills: []
632
742
  };
743
+ if ((action === "restructure" || action === "extract" || action === "delete") && origin !== "foreground" && change === void 0) return {
744
+ ok: false,
745
+ message: `动作「${action}」的后台写入必须提供 summary(一句变更原因)。`,
746
+ skills: []
747
+ };
633
748
  if (action === "review") try {
634
749
  return {
635
750
  ok: true,
@@ -657,6 +772,20 @@ function apply(ctx, rawConfig = {}) {
657
772
  skills: []
658
773
  };
659
774
  }
775
+ if (action === "feedback") {
776
+ const service = ctx.get("evolutionFeedback");
777
+ if (service?.record === void 0) return {
778
+ ok: false,
779
+ message: "反馈服务未挂载,未记录。",
780
+ skills: []
781
+ };
782
+ service.record(name, "negative", args.problem ?? "unspecified", "skill");
783
+ return {
784
+ ok: true,
785
+ message: `已记录对「${name}」的问题反馈。`,
786
+ skills: []
787
+ };
788
+ }
660
789
  const refusal = await runWriteGates(skillWriteGateContext({
661
790
  policy: ctx.get("evolutionPolicy"),
662
791
  confirm: void 0,
@@ -690,102 +819,130 @@ function apply(ctx, rawConfig = {}) {
690
819
  }
691
820
  let result;
692
821
  let proposal;
693
- if (action === "create") {
694
- feedbackLines.push(...await duplicateHintLines(name, candidateDescription, crossSourceView));
695
- result = await library.create(name, args.content ?? "", origin, { managed: origin !== "foreground" });
696
- } else if (action === "edit" || action === "update") result = await library.update(name, args.content ?? "", origin, stagedAnchor);
697
- else if (action === "patch") result = await library.patch(name, args.old_string ?? "", args.new_string ?? "", args.file_path ?? "", args.replace_all === true, origin);
698
- else if (action === "delete") result = await library.archive(name, args.absorbed_into ? { absorbedInto: args.absorbed_into } : {});
699
- else if (action === "write_file") result = await library.writeSupportFile(name, args.file_path ?? "", args.file_content ?? "", origin, stagedAnchor);
700
- else if (action === "remove_file") result = await library.removeSupportFile(name, args.file_path ?? "", origin, stagedAnchor);
701
- else if (action === "restructure") {
702
- const moves = Array.isArray(args.restructure) ? args.restructure : [];
703
- if (moves.some((move) => {
704
- const raw = move;
705
- return raw === null || typeof raw !== "object";
706
- })) result = {
707
- ok: false,
708
- message: "restructure 的每一项都必须是带 heading 与 to_file 的对象。"
709
- };
710
- else result = await library.restructure(name, moves.map((move) => ({
711
- heading: typeof move.heading === "string" ? move.heading : "",
712
- toFile: typeof move.to_file === "string" ? move.to_file : ""
713
- })), origin);
714
- } else if (action === "extract") {
715
- let source = typeof args.name === "string" ? args.name : "";
716
- let items = Array.isArray(args.extract) ? args.extract : [];
717
- let outcome = args.outcome;
718
- let ownerCovers = args.owner_covers;
719
- if (args.proposal_id !== void 0 && args.proposal_id !== "") {
720
- const io = ctx.get("evolutionIo")?.provider();
721
- if (io === void 0) result = {
822
+ const simpleActions = {
823
+ create: async () => {
824
+ feedbackLines.push(...await duplicateHintLines(name, candidateDescription, crossSourceView));
825
+ return library.create(name, args.content ?? "", origin, { managed: origin !== "foreground" });
826
+ },
827
+ edit: () => library.update(name, args.content ?? "", origin, stagedAnchor),
828
+ update: () => library.update(name, args.content ?? "", origin, stagedAnchor),
829
+ patch: async () => {
830
+ const section = args.section;
831
+ if (section === void 0) return await library.patch(name, args.old_string ?? "", args.new_string ?? "", args.file_path ?? "", args.replace_all === true, origin);
832
+ if (typeof section.heading !== "string" || typeof section.content !== "string") return {
722
833
  ok: false,
723
- message: "proposal_id 需要 evolutionIo 提供者。"
834
+ message: "patch.section 需要 heading 与 content。"
724
835
  };
725
- else {
726
- const proposal = await readProposalReport(io, args.proposal_id);
727
- if (proposal === null) result = {
728
- ok: false,
729
- message: "找不到 extract proposal:" + args.proposal_id
730
- };
731
- else if (proposal.outcome === "keep") result = {
732
- ok: false,
733
- message: "该 proposal 的结论是 keep,没有可应用提取。"
734
- };
735
- else if (proposal.outcome === "owner-gap" || proposal.owner.mode !== "covered" || proposal.owner.name === void 0) result = {
836
+ return await library.patchSection(name, {
837
+ heading: section.heading,
838
+ content: section.content,
839
+ ...typeof section.start === "string" ? { start: section.start } : {},
840
+ ...typeof section.end === "string" ? { end: section.end } : {}
841
+ }, origin);
842
+ },
843
+ delete: () => library.archive(name, args.absorbed_into ? { absorbedInto: args.absorbed_into } : {}, void 0, change),
844
+ write_file: () => library.writeSupportFile(name, args.file_path ?? "", args.file_content ?? "", origin, stagedAnchor),
845
+ remove_file: () => library.removeSupportFile(name, args.file_path ?? "", origin, stagedAnchor),
846
+ pin: () => library.setPinned(name, true, origin),
847
+ unpin: () => library.setPinned(name, false, origin),
848
+ restructure: async () => {
849
+ const moves = Array.isArray(args.restructure) ? args.restructure : [];
850
+ if (moves.some((move) => {
851
+ const raw = move;
852
+ return raw === null || typeof raw !== "object";
853
+ })) return {
854
+ ok: false,
855
+ message: "restructure 的每一项都必须是带 heading 与 to_file 的对象。"
856
+ };
857
+ return library.restructure(name, moves.map((move) => ({
858
+ heading: typeof move.heading === "string" ? move.heading : "",
859
+ ...typeof move.start === "string" ? { start: move.start } : {},
860
+ ...typeof move.end === "string" ? { end: move.end } : {},
861
+ toFile: typeof move.to_file === "string" ? move.to_file : ""
862
+ })), origin, change);
863
+ },
864
+ extract: async () => {
865
+ let result;
866
+ let source = typeof args.name === "string" ? args.name : "";
867
+ let items = Array.isArray(args.extract) ? args.extract : [];
868
+ let outcome = args.outcome;
869
+ let ownerCovers = args.owner_covers;
870
+ if (args.proposal_id !== void 0 && args.proposal_id !== "") {
871
+ const io = ctx.get("evolutionIo")?.provider();
872
+ if (io === void 0) result = {
736
873
  ok: false,
737
- message: "该 proposal 未覆盖 owner(owner-gap),不能应用。"
874
+ message: "proposal_id 需要 evolutionIo 提供者。"
738
875
  };
739
876
  else {
740
- source = proposal.source;
741
- outcome = proposal.outcome === "extract" || proposal.outcome === "mixed" ? proposal.outcome : void 0;
742
- ownerCovers = void 0;
743
- items = proposal.parts.map((part) => ({
744
- heading: part.heading,
745
- ...part.anchor.start === void 0 ? {} : { start: part.anchor.start },
746
- ...part.anchor.end === void 0 ? {} : { end: part.anchor.end },
747
- to_skill: proposal.owner.name
748
- }));
877
+ const report = await readProposalReport(io, args.proposal_id);
878
+ if (report === null) result = {
879
+ ok: false,
880
+ message: "找不到 extract proposal:" + args.proposal_id
881
+ };
882
+ else if (report.outcome === "keep") result = {
883
+ ok: false,
884
+ message: "该 proposal 的结论是 keep,没有可应用提取。"
885
+ };
886
+ else if (report.outcome === "owner-gap" || report.owner.mode !== "covered" || report.owner.name === void 0) result = {
887
+ ok: false,
888
+ message: "该 proposal 未覆盖 owner(owner-gap),不能应用。"
889
+ };
890
+ else {
891
+ source = report.source;
892
+ outcome = report.outcome === "extract" || report.outcome === "mixed" ? report.outcome : void 0;
893
+ ownerCovers = void 0;
894
+ items = report.parts.map((part) => ({
895
+ heading: part.heading,
896
+ ...part.anchor.start === void 0 ? {} : { start: part.anchor.start },
897
+ ...part.anchor.end === void 0 ? {} : { end: part.anchor.end },
898
+ to_skill: report.owner.name
899
+ }));
900
+ }
749
901
  }
750
902
  }
751
- }
752
- const built = result === void 0 ? await buildExtractPlanFromLibrary(library, {
753
- source,
754
- items,
755
- ...outcome === void 0 ? {} : { outcome },
756
- ...ownerCovers === void 0 ? {} : { ownerCovers }
757
- }) : {
758
- ok: false,
759
- message: result.message
760
- };
761
- if (!built.ok) result = {
762
- ok: false,
763
- message: built.message
764
- };
765
- else {
766
- proposal = JSON.stringify(proposalFromPlan(built.plan, { runId: "tool-" + Date.now().toString(36) }));
767
- const ownerText = ownerDecisionText(built.plan.owner);
768
- const decisionLine = `提取判定:outcome=${built.plan.outcome};target=${built.plan.target.name};owner=${ownerText}`;
769
- const candidateLines = built.candidates.slice(0, 8).map((candidate) => "- " + candidate.name + ":" + candidate.description + (candidate.whenToUse === void 0 ? "" : ";whenToUse: " + candidate.whenToUse) + (candidate.headings.length === 0 ? "" : ";headings: " + candidate.headings.join(" / ")));
770
- result = args.dry_run === true ? {
771
- ok: true,
772
- message: "提取计划(未写入):" + built.plan.parts.map((part) => "## " + part.heading).join(", ") + " -> " + built.plan.target.name + "\n" + decisionLine + (candidateLines.length === 0 ? "" : "\n候选 owner:\n" + candidateLines.join("\n"))
773
- } : await library.extract(built.plan, origin);
774
- if (result.ok && built.warnings !== void 0 && built.warnings.length > 0) result = {
775
- ...result,
776
- message: result.message + "\n" + built.warnings.join("\n")
903
+ const built = result === void 0 ? await buildExtractPlanFromLibrary(library, {
904
+ source,
905
+ items,
906
+ ...outcome === void 0 ? {} : { outcome },
907
+ ...ownerCovers === void 0 ? {} : { ownerCovers }
908
+ }) : {
909
+ ok: false,
910
+ message: result.message
777
911
  };
778
- if (args.dry_run === true) try {
779
- const io = ctx.get("evolutionIo")?.provider();
780
- if (io !== void 0) await writeProposalReport(io, proposalFromPlan(built.plan, { runId: "tool-" + Date.now().toString(36) }));
781
- } catch {}
782
- if (result.ok) result = {
783
- ...result,
784
- message: result.message + "\n" + decisionLine
912
+ if (!built.ok) result = {
913
+ ok: false,
914
+ message: built.message
915
+ };
916
+ else {
917
+ const plan = built.plan;
918
+ proposal = JSON.stringify(proposalFromPlan(plan, { runId: "tool-" + Date.now().toString(36) }));
919
+ const ownerText = ownerDecisionText(plan.owner);
920
+ const decisionLine = `提取判定:outcome=${plan.outcome};target=${plan.target.name};owner=${ownerText}`;
921
+ const candidateLines = built.candidates.slice(0, 8).map((candidate) => "- " + candidate.name + ":" + candidate.description + (candidate.whenToUse === void 0 ? "" : ";whenToUse: " + candidate.whenToUse) + (candidate.headings.length === 0 ? "" : ";headings: " + candidate.headings.join(" / ")));
922
+ result = args.dry_run === true ? {
923
+ ok: true,
924
+ message: "提取计划(未写入):" + plan.parts.map((part) => "## " + part.heading).join(", ") + " -> " + plan.target.name + "\n" + decisionLine + (candidateLines.length === 0 ? "" : "\n候选 owner:\n" + candidateLines.join("\n"))
925
+ } : await library.extract(plan, origin, change);
926
+ if (result.ok && built.warnings !== void 0 && built.warnings.length > 0) result = {
927
+ ...result,
928
+ message: result.message + "\n" + built.warnings.join("\n")
929
+ };
930
+ if (args.dry_run === true) try {
931
+ const io = ctx.get("evolutionIo")?.provider();
932
+ if (io !== void 0) await writeProposalReport(io, proposalFromPlan(plan, { runId: "tool-" + Date.now().toString(36) }));
933
+ } catch {}
934
+ if (result.ok) result = {
935
+ ...result,
936
+ message: result.message + "\n" + decisionLine
937
+ };
938
+ }
939
+ return result ?? {
940
+ ok: false,
941
+ message: "extract did not produce a result"
785
942
  };
786
943
  }
787
- } else if (action === "pin") result = await library.setPinned(name, true, origin);
788
- else if (action === "unpin") result = await library.setPinned(name, false, origin);
944
+ };
945
+ if (action !== void 0 && Object.prototype.hasOwnProperty.call(simpleActions, action)) result = await commitSkillAction(simpleActions[action]);
789
946
  else result = {
790
947
  ok: false,
791
948
  message: `未知动作「${action}」。`
@@ -883,6 +1040,14 @@ function apply(ctx, rawConfig = {}) {
883
1040
  }));
884
1041
  const dedup = computeDedupGroups({ contents });
885
1042
  const groups = dedup.groups;
1043
+ const sizedLines = lines.map((line, index) => {
1044
+ const body = contents.get(list[index]?.name ?? "");
1045
+ if (body === void 0) return line;
1046
+ const oversize = body.length >= DEFAULT_HEALTH_THRESHOLDS.softBodyChars ? " [oversize]" : "";
1047
+ return `${line} chars:${body.length}${oversize}`;
1048
+ });
1049
+ const oversizeNames = list.filter((summary) => (contents.get(summary.name)?.length ?? 0) >= DEFAULT_HEALTH_THRESHOLDS.softBodyChars).map((summary) => summary.name);
1050
+ const oversizeLine = oversizeNames.length === 0 ? "" : `\nOversize skills (${oversizeNames.length}): ${oversizeNames.join(", ")} — offload whole sections to references/ before adding more body.`;
886
1051
  const dedupLines = groups.slice(0, MAX_DEDUP_GROUPS_IN_REVIEW).map((group) => `- ${group.join(" ~ ")}`);
887
1052
  if (dedup.truncated) dedupLines.push(`- note: dedup scan truncated at the pair-comparison budget (${groups.length} group(s) so far); groups may be incomplete`);
888
1053
  const excludedLine = excludedBodies === 0 ? "" : `\n${excludedBodies} skill bodies were empty and excluded from dedup grouping.`;
@@ -890,18 +1055,19 @@ function apply(ctx, rawConfig = {}) {
890
1055
  const warned = list.filter((summary) => warnedFlag(summary.name)).map((summary) => summary.name);
891
1056
  const warningLine = warned.length === 0 ? "" : `\nWarning skills (${warned.length}): ${warned.join(", ")} — low quality; consider consolidating them before authoring new skills.`;
892
1057
  return [
893
- list.length === 0 ? "No skills yet. Create one with action=create, or it is safe to author a new class-level umbrella." : `Skills: ${list.length} total. Below each name: state, use/view/patch counts, quality (0-1, ⚠ = low) and protection.${groups.length > 0 ? `\n\nNear-duplicate groups (${groups.length}):` : ""}`,
1058
+ list.length === 0 ? "No skills yet. Create one with action=create, or it is safe to author a new class-level umbrella." : `Skills: ${list.length} total. Below each name: state, use/view/patch counts, quality (0-1, ⚠ = low), protection, and body chars when readable ([oversize] = at or over the health soft line).${groups.length > 0 ? `\n\nNear-duplicate groups (${groups.length}):` : ""}`,
894
1059
  "",
895
- ...lines,
1060
+ ...sizedLines,
896
1061
  ...dedupLines,
897
1062
  ...excludedBodies > 0 ? [excludedLine] : [],
898
1063
  ...unreadableBodies > 0 ? [unreadableLine] : [],
899
- warningLine
1064
+ warningLine,
1065
+ oversizeLine
900
1066
  ].join("\n");
901
1067
  }
902
1068
  registerEvolutionTool(ctx, defineTool({
903
1069
  name: "skill_manage",
904
- description: "Manage reusable skills. review returns the library review text (state/usage/quality per skill); list returns names only; create/edit/update take full SKILL.md content (edit is an alias of update); patch applies old_string -> new_string; delete archives to .archive (absorbed_into names an umbrella skill); write_file/remove_file add or remove one support file under references/ or scripts/; pin protects a skill from deletion, background review, and the lifecycle (pin/unpin are never allowed from a background review — foreground and delegated subagents may). Per-action arguments: patch needs name + old_string + new_string and patches SKILL.md unless file_path names a support file (e.g. \"references/topic.md\"); patch replaces the FIRST occurrence only unless replace_all=true, and the result message reports how many anchors the file carried. write_file needs name + file_path + file_content; remove_file needs name + file_path; create/edit/update need name + content; delete needs name. A rejected patch names the reason and the remedy (missing anchor, stale snapshot, frontmatter that cannot be auto-quoted, byte/char limit). Protected bundled/hub skills reject any mutation; pinned skills reject deletion and are read-only to the background review.Prefer patching an umbrella over creating narrow skills. restructure moves entire body sections (by their exact \"## heading\" line, via restructure: [{heading, to_file: \"references/<topic>.md\"}]) into a references/ file and replaces each with a pointer line — the skill name and directory never change. extract moves a reusable part (exact heading, optional start/end sub-block) into an existing class-level owner: extract: [{heading, start?, end?, to_skill}]. One target per call; an empty extract list returns the child-agent proposal (outcome/target/neededOwner/parts) without writing; supply extract items to apply, and use owner_covers only as an explicit override; owner-gap is reported, never auto-created.Created/edited SKILL.md MUST start with YAML frontmatter (a name/description block), or creation is rejected. " + DSH_AUTHORING_STANDARDS,
1070
+ description: "Manage reusable skills. review returns the library review text (state/usage/quality per skill); list returns names only; create/edit/update take full SKILL.md content (edit is an alias of update); patch applies old_string -> new_string; delete archives to .archive (absorbed_into names an umbrella skill); write_file/remove_file add or remove one support file under references/ or scripts/; pin protects a skill from deletion, background review, and the lifecycle (pin/unpin are never allowed from a background review — foreground and delegated subagents may). Per-action arguments: patch needs name + old_string + new_string and patches SKILL.md unless file_path names a support file (e.g. \"references/topic.md\"); patch replaces the FIRST occurrence only unless replace_all=true, and the result message reports how many anchors the file carried. patch also accepts section: {heading, start?, end?, content} to replace one H2 section content (or an exact sub-block) in place without resending the old text; the heading line is kept for a whole-section edit. write_file needs name + file_path + file_content; remove_file needs name + file_path; create/edit/update need name + content; delete needs name. A rejected patch names the reason and the remedy (missing anchor, stale snapshot, frontmatter that cannot be auto-quoted, byte/char limit). Protected bundled/hub skills reject any mutation; pinned skills reject deletion and are read-only to the background review.Prefer patching an umbrella over creating narrow skills. restructure moves entire body sections (by their exact \"## heading\" line, or an optional start/end sub-block, via restructure: [{heading, start?, end?, to_file: \"references/<topic>.md\"}]) into a references/ file and replaces each with a pointer line — the skill name and directory never change. extract moves a reusable part (exact heading, optional start/end sub-block) into an existing class-level owner: extract: [{heading, start?, end?, to_skill}]. One target per call; an empty extract list returns the child-agent proposal (outcome/target/neededOwner/parts) without writing; supply extract items to apply, and use owner_covers only as an explicit override; owner-gap is reported, never auto-created.Created/edited SKILL.md MUST start with YAML frontmatter (a name/description block), or creation is rejected. " + DSH_AUTHORING_STANDARDS,
905
1071
  parameters: {
906
1072
  action: {
907
1073
  type: "string",
@@ -918,6 +1084,7 @@ function apply(ctx, rawConfig = {}) {
918
1084
  "remove_file",
919
1085
  "restructure",
920
1086
  "extract",
1087
+ "feedback",
921
1088
  "pin",
922
1089
  "unpin"
923
1090
  ]
@@ -930,6 +1097,30 @@ function apply(ctx, rawConfig = {}) {
930
1097
  file_path: { type: "string" },
931
1098
  file_content: { type: "string" },
932
1099
  absorbed_into: { type: "string" },
1100
+ summary: {
1101
+ type: "string",
1102
+ description: "One-line change summary for the skill history. Required for restructure/extract/delete in model-origin writes; max 50 Unicode characters by default, over-limit is rejected with the current limit."
1103
+ },
1104
+ problem: {
1105
+ type: "string",
1106
+ enum: [
1107
+ "wrong",
1108
+ "outdated",
1109
+ "incomplete",
1110
+ "unsafe"
1111
+ ],
1112
+ description: "feedback only: why the loaded skill did not help."
1113
+ },
1114
+ section: {
1115
+ type: "object",
1116
+ additionalProperties: false,
1117
+ properties: {
1118
+ heading: { type: "string" },
1119
+ start: { type: "string" },
1120
+ end: { type: "string" },
1121
+ content: { type: "string" }
1122
+ }
1123
+ },
933
1124
  restructure: {
934
1125
  type: "array",
935
1126
  items: {
@@ -937,6 +1128,8 @@ function apply(ctx, rawConfig = {}) {
937
1128
  additionalProperties: false,
938
1129
  properties: {
939
1130
  heading: { type: "string" },
1131
+ start: { type: "string" },
1132
+ end: { type: "string" },
940
1133
  to_file: { type: "string" }
941
1134
  }
942
1135
  }
@@ -1015,7 +1208,14 @@ function apply(ctx, rawConfig = {}) {
1015
1208
  args,
1016
1209
  origin: libraryOrigin,
1017
1210
  protectedNames: protectedSkillNamesOf(ctx.get("evolutionPolicy")),
1018
- readNames: sessionReadSkillNames(ctx, exec.agent?.session),
1211
+ readNames: (() => {
1212
+ const run = currentReviewContext()?.reads;
1213
+ if (run === void 0) return sessionReadSkillNames(ctx, exec.agent?.session);
1214
+ const merged = /* @__PURE__ */ new Set();
1215
+ sessionReadSkillNames(ctx, exec.agent?.session)?.forEach((name) => merged.add(name));
1216
+ run.forEach((name) => merged.add(name));
1217
+ return merged;
1218
+ })(),
1019
1219
  readSupportFiles: sessionReadSupportFiles(ctx, exec.agent?.session, { root: library.root }),
1020
1220
  confirm: async (request) => confirmSkillWrite(request, exec),
1021
1221
  confirmMode: approvalSeam !== void 0 && approvalSeam.isEnabled !== false && sessionPolicy !== "never" && (libraryOrigin === "background_review" || approvalSeam.stageForeground !== false) ? "auto" : settings().skillWriteConfirm,
@@ -57,6 +57,8 @@ export interface Config {
57
57
  * like the four caps above — the settings layer deliberately has no card for it (retention is
58
58
  * storage policy, not an authoring knob). */
59
59
  skillVersionKeep?: number;
60
+ /** Hard cap for the one-line change summary; E2 internal (restart-only), no settings card. */
61
+ skillWriteSummaryChars?: number;
60
62
  /** What the ONE confirmation before a create or a bare delete does (registry `skillWriteConfirm`).
61
63
  * Default `auto`: an unattended run must not park a tool call on a question nobody will answer. */
62
64
  skillWriteConfirm?: Volatile<WriteConfirmMode>;
@@ -75,6 +77,7 @@ export declare const Config: z<Schemastery.ObjectS<NoInfer<{
75
77
  threatExemptLabels: z<string[], string[], "defined">;
76
78
  strictCrossSource: z<boolean, boolean, "volatile-defined">;
77
79
  skillVersionKeep: z<number, number, "defined">;
80
+ skillWriteSummaryChars: z<number, number, "defined">;
78
81
  skillWriteConfirm: z<"auto" | "ask" | "timeout", "auto" | "ask" | "timeout", "volatile-defined">;
79
82
  skillWriteConfirmTimeoutSeconds: z<number, number, "volatile-defined">;
80
83
  }>>, Schemastery.ObjectT<NoInfer<{
@@ -89,6 +92,7 @@ export declare const Config: z<Schemastery.ObjectS<NoInfer<{
89
92
  threatExemptLabels: z<string[], string[], "defined">;
90
93
  strictCrossSource: z<boolean, boolean, "volatile-defined">;
91
94
  skillVersionKeep: z<number, number, "defined">;
95
+ skillWriteSummaryChars: z<number, number, "defined">;
92
96
  skillWriteConfirm: z<"auto" | "ask" | "timeout", "auto" | "ask" | "timeout", "volatile-defined">;
93
97
  skillWriteConfirmTimeoutSeconds: z<number, number, "volatile-defined">;
94
98
  }>>, "plain">;
@@ -0,0 +1,24 @@
1
+ /**
2
+ * The ONE action table for skill_manage. Handlers still live in the tool until
3
+ * the mutation pipeline is extracted, but every cross-cutting decision
4
+ * (read-only, name requirement, gate) reads this table instead of duplicating
5
+ * an action list.
6
+ */
7
+ import type { SkillActionResult } from '@lmzhen/dsh-evolution-core/skills';
8
+ export type SkillActionId = 'list' | 'review' | 'create' | 'edit' | 'update' | 'patch' | 'delete' | 'write_file' | 'remove_file' | 'restructure' | 'extract' | 'feedback' | 'pin' | 'unpin';
9
+ export interface SkillActionMeta {
10
+ /** Does this action write skill bytes (and therefore enter usage/journal)? */
11
+ readonly mutates: boolean;
12
+ /** Does the action address one skill by name? */
13
+ readonly needsName: boolean;
14
+ /** none = read-only; write = SkillLibrary write path; approval = staged gate. */
15
+ readonly gate: 'none' | 'write' | 'approval';
16
+ /** Whether the user-facing change summary is model-required, host-derived, or absent. */
17
+ readonly summary: 'required' | 'host' | 'none';
18
+ }
19
+ export declare const SKILL_ACTIONS: Readonly<Record<SkillActionId, SkillActionMeta>>;
20
+ export declare function skillActionOf(action: unknown): SkillActionMeta | undefined;
21
+ /** The one commit seam every table-dispatched action passes through. */
22
+ export declare function commitSkillAction(run: () => Promise<SkillActionResult>): Promise<SkillActionResult>;
23
+ export declare function isReadOnlySkillAction(action: unknown): boolean;
24
+ //# sourceMappingURL=skill-actions.d.ts.map
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@lmzhen/dsh-tool-skill-manage",
3
3
  "description": "Model-facing skill_manage tool (community build)",
4
- "version": "0.49.0",
4
+ "version": "0.51.0",
5
5
  "publishConfig": {
6
6
  "access": "public"
7
7
  },
@@ -29,25 +29,25 @@
29
29
  "license": "MIT",
30
30
  "dependencies": {
31
31
  "@deepseek-ai/schemastery": "^3.18.5",
32
- "@lmzhen/dsh-evolution-approval": "^0.49.0",
33
- "@lmzhen/dsh-evolution-core": "^0.49.0",
34
- "@lmzhen/dsh-evolution-skill-discovery": "^0.49.0"
32
+ "@lmzhen/dsh-evolution-approval": "^0.51.0",
33
+ "@lmzhen/dsh-evolution-core": "^0.51.0",
34
+ "@lmzhen/dsh-evolution-skill-discovery": "^0.51.0"
35
35
  },
36
36
  "peerDependencies": {
37
37
  "@deepseek-ai/cordis": "^4.0.5",
38
- "@deepseek-ai/dsh-skill": "^0.2.2-rc.0",
39
- "@deepseek-ai/dsh-system-prompt": "^0.2.2-rc.0",
40
- "@deepseek-ai/dsh-agent": "^0.2.2-rc.0",
41
- "@lmzhen/dsh-evolution-skill-discovery": "^0.49.0"
38
+ "@deepseek-ai/dsh-skill": "^0.2.2-rc.3",
39
+ "@deepseek-ai/dsh-system-prompt": "^0.2.2-rc.3",
40
+ "@deepseek-ai/dsh-agent": "^0.2.2-rc.3",
41
+ "@lmzhen/dsh-evolution-skill-discovery": "^0.51.0"
42
42
  },
43
43
  "devDependencies": {
44
- "@deepseek-ai/dsh-agent-loop-testkit": "^0.2.2-rc.0",
45
- "@deepseek-ai/dsh-skill": "^0.2.2-rc.0",
46
- "@deepseek-ai/dsh-system-prompt": "^0.2.2-rc.0",
47
- "@lmzhen/dsh-evolution-core": "^0.49.0",
48
- "@lmzhen/dsh-evolution-skill-discovery": "^0.49.0"
44
+ "@deepseek-ai/dsh-agent-loop-testkit": "^0.2.2-rc.3",
45
+ "@deepseek-ai/dsh-skill": "^0.2.2-rc.3",
46
+ "@deepseek-ai/dsh-system-prompt": "^0.2.2-rc.3",
47
+ "@lmzhen/dsh-evolution-core": "^0.51.0",
48
+ "@lmzhen/dsh-evolution-skill-discovery": "^0.51.0"
49
49
  },
50
50
  "engines": {
51
- "dsh": ">=0.2.2-rc.0 <0.2.3-0"
51
+ "dsh": ">=0.2.2-rc.3 <0.2.3-0"
52
52
  }
53
53
  }