@lmzhen/dsh-evolution-commands 0.50.0 → 0.51.1

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,13 +1,13 @@
1
1
  import { createRequire } from "node:module";
2
2
  import { commandsPort, configEditorPort, createUserMessage, pluginInventoryPort, pluginManagerPort, profileContextPort, sessionQueryPort, settingsPort, toolsPort } from "@lmzhen/dsh-evolution-core/platform";
3
- import { DEFAULT_SKILL_LIMITS, DIAGNOSTICS_FACT_KEYS, DIAGNOSTICS_RUNTIME_KEYS, DIAGNOSTICS_VIEW_SCHEMA_VERSION, EVOLUTION_PRESET_IDS, HOST_LOCALES, MAINTAINER_PRESET_ID, MAX_TIMER_DELAY_MS, PARAM_EXPOSURE, PARAM_GROUP_LABELS, PLATFORM_LINE, REVIEWER_PRESET_ID, absentHostServices, appendEvolutionEvent, applyNamespaceMigration, asRecord, atomicWriteFiles, authorityFrom, buildLearnPrompt, clampedNumber, classifyNamespaceMigration, createSubagentChannel, errorText, errorTextIn, eventsFile, evolutionHome, evolutionRoot, hostSurface, isDeprecatedParamId, isPresent, isRecord, isUnknown, liveBool, mutationLockFrom, newRunRegistry, paramSettingsId, planNamespaceMigration, policyStageLimits, probeMtime, probeText, reportsSweepLockTarget, resolveParamId, scopedPackageName, scopedProbeReport, sweepReports, transactIo } from "@lmzhen/dsh-evolution-core";
3
+ import { DEFAULT_SKILL_LIMITS, DIAGNOSTICS_FACT_KEYS, DIAGNOSTICS_RUNTIME_KEYS, DIAGNOSTICS_VIEW_SCHEMA_VERSION, EVOLUTION_PRESET_IDS, GOVERNANCE_PROMPT_TEMPLATE, HOST_LOCALES, MAINTAINER_PRESET_ID, MAX_TIMER_DELAY_MS, PARAM_EXPOSURE, PARAM_GROUP_LABELS, PLATFORM_LINE, REVIEWER_PRESET_ID, absentHostServices, appendEvolutionEvent, applyNamespaceMigration, asRecord, atomicWriteFiles, authorityFrom, buildLearnPrompt, clampedNumber, classifyNamespaceMigration, createSubagentChannel, errorText, errorTextIn, eventsFile, evolutionHome, evolutionRoot, hostSurface, isDeprecatedParamId, isPresent, isRecord, isUnknown, liveBool, markReviewChannel, mutationLockFrom, newRunRegistry, paramSettingsId, planNamespaceMigration, policyStageLimits, probeMtime, probeText, reportsSweepLockTarget, resolveParamId, reviewPrompt, scopedPackageName, scopedProbeReport, sweepReports, transactIo, withReviewContext } from "@lmzhen/dsh-evolution-core";
4
4
  import { HOST_ROUTES, json, methodNotAllowed, registerHostRoutes } from "@lmzhen/dsh-evolution-core/http-routes";
5
5
  import { existsSync, readFileSync, readdirSync } from "node:fs";
6
6
  import { dirname, join } from "node:path";
7
7
  import { fileURLToPath } from "node:url";
8
8
  import z from "@deepseek-ai/schemastery";
9
9
  import { effectiveSessionPolicy } from "@lmzhen/dsh-evolution-approval";
10
- import { buildExtractPlanFromLibrary, ownerDecisionText, proposalFromPlan, readProposalReport, writeProposalReport } from "@lmzhen/dsh-evolution-core/extract";
10
+ import { EXTRACT_PROMPT_V1, buildExtractPlanFromLibrary, ownerCandidatesFromSummaries, ownerDecisionText, proposalFromPlan, readProposalReport, writeProposalReport } from "@lmzhen/dsh-evolution-core/extract";
11
11
  import { buildEnrichment, buildMaintainFacts, enrichmentSnapshotOptions, runMaintain, snapshotFromLibrary } from "@lmzhen/dsh-evolution-maintenance";
12
12
  import { composePresetEntry, presetRowBlock, presetRowBody, presetRowId, resolveBasePresetPatch } from "@lmzhen/dsh-evolution-core/composition";
13
13
  import { processScopeViolations } from "@lmzhen/dsh-evolution-state";
@@ -1001,6 +1001,16 @@ const HOST_COMMANDS = {
1001
1001
  "ru": "Отправить запрос на обучение в эту сессию",
1002
1002
  "pt": "Enviar uma solicitação de aprendizado para esta sessão"
1003
1003
  },
1004
+ "summary.review": {
1005
+ "zh": "立即向本会话注入一次复盘(不等空闲)",
1006
+ "en": "Inject one review into this session now (no idle wait)",
1007
+ "ja": "このセッションに今すぐレビューを注入(idle 待ちなし)",
1008
+ "es": "Inyectar una revisión en esta sesión ahora (sin esperar idle)",
1009
+ "fr": "Injecter une revue dans cette session maintenant (sans attendre idle)",
1010
+ "de": "Jetzt eine Review in diese Sitzung einspeisen (ohne Idle-Warten)",
1011
+ "ru": "Сразу внедрить проверку в эту сессию (без ожидания idle)",
1012
+ "pt": "Injetar uma revisão nesta sessão agora (sem esperar idle)"
1013
+ },
1004
1014
  "summary.maintain": {
1005
1015
  "zh": "起一次维护扫描并立即回 run id(后台跑;--facts 为 0 token 预览)",
1006
1016
  "en": "Start a maintenance scan and return the run id immediately (runs in the background; --facts is a 0-token preview)",
@@ -1101,6 +1111,26 @@ const HOST_COMMANDS = {
1101
1111
  "ru": "Перенести один раздел текста навыка в файл references",
1102
1112
  "pt": "Mover uma seção do corpo de uma skill para um arquivo references"
1103
1113
  },
1114
+ "summary.offload": {
1115
+ "zh": "把技能正文的会话细节章节移到 references(后台子智能体,--dry-run 只预览)",
1116
+ "en": "Move session-detail sections from a skill body into references (background subagent; --dry-run previews only)",
1117
+ "ja": "スキル本文のセッション詳細セクションを references へ移す(バックグラウンド子エージェント、--dry-run はプレビューのみ)",
1118
+ "es": "Mover secciones de detalle de sesión del cuerpo de un skill a references (subagente en segundo plano; --dry-run solo previsualiza)",
1119
+ "fr": "Déplacer les sections de détail de session d’un skill vers references (sous-agent en arrière-plan ; --dry-run prévisualise seulement)",
1120
+ "de": "Sitzungsdetail-Abschnitte aus einem Skill-Text nach references verschieben (Hintergrund-Subagent; --dry-run zeigt nur die Vorschau)",
1121
+ "ru": "Перенести разделы с деталями сессии из текста навыка в references (фоновый подагент; --dry-run только предпросмотр)",
1122
+ "pt": "Mover seções de detalhe de sessão do corpo de uma skill para references (subagente em segundo plano; --dry-run apenas pré-visualiza)"
1123
+ },
1124
+ "summary.condense": {
1125
+ "zh": "逐章节压缩技能正文(后台子智能体,多次小改,--dry-run 只预览)",
1126
+ "en": "Condense a skill body section by section (background subagent, repeated small edits; --dry-run previews only)",
1127
+ "ja": "スキル本文をセクション単位で圧縮(バックグラウンド子エージェント、小さな編集を繰り返す、--dry-run はプレビューのみ)",
1128
+ "es": "Condensar el cuerpo de un skill sección por sección (subagente en segundo plano, ediciones pequeñas repetidas; --dry-run solo previsualiza)",
1129
+ "fr": "Condenser le corps d’un skill section par section (sous-agent en arrière-plan, petites modifications répétées ; --dry-run prévisualise seulement)",
1130
+ "de": "Einen Skill-Text Abschnitt für Abschnitt verdichten (Hintergrund-Subagent, wiederholte kleine Änderungen; --dry-run zeigt nur die Vorschau)",
1131
+ "ru": "Сжимать текст навыка по разделам (фоновый подагент, повторные небольшие правки; --dry-run только предпросмотр)",
1132
+ "pt": "Condensar o corpo de uma skill seção por seção (subagente em segundo plano, pequenas edições repetidas; --dry-run apenas pré-visualiza)"
1133
+ },
1104
1134
  "summary.extract": {
1105
1135
  "zh": "预览把源技能的可复用部分提取到已有类级 owner;默认 plan,--apply 才写(多根一次事务)",
1106
1136
  "en": "Preview extracting a source skill's reusable part into an existing class-level owner; by default it produces a plan, and only --apply writes (multiple roots in one transaction)",
@@ -1757,6 +1787,18 @@ const HOST_COMMAND_DEFS = [
1757
1787
  fallback: "learn [request]",
1758
1788
  usageLine: "learn [request]"
1759
1789
  },
1790
+ {
1791
+ id: "review",
1792
+ words: ["review"],
1793
+ summaryKey: "summary.review",
1794
+ helpKey: "help.review",
1795
+ flags: [],
1796
+ positional: [],
1797
+ readOnly: false,
1798
+ needsRun: false,
1799
+ fallback: "review [memory|skill|combined]",
1800
+ usageLine: "review [memory|skill|combined]"
1801
+ },
1760
1802
  {
1761
1803
  id: "maintain",
1762
1804
  words: ["maintain"],
@@ -1846,15 +1888,58 @@ const HOST_COMMAND_DEFS = [
1846
1888
  words: ["restructure"],
1847
1889
  summaryKey: "summary.restructure",
1848
1890
  helpKey: "help.restructure",
1891
+ flags: [
1892
+ {
1893
+ name: "plan",
1894
+ kind: "value"
1895
+ },
1896
+ {
1897
+ name: "start",
1898
+ kind: "value"
1899
+ },
1900
+ {
1901
+ name: "end",
1902
+ kind: "value"
1903
+ }
1904
+ ],
1905
+ positional: [],
1906
+ readOnly: false,
1907
+ needsRun: false,
1908
+ fallback: "restructure <name> \"<heading>\" <to_file> [--start <line>] [--end <line>] [--plan <runId>]",
1909
+ usageLine: "restructure <name> \"<heading>\" <to_file> [--start <line>] [--end <line>] [--plan <runId>]"
1910
+ },
1911
+ {
1912
+ id: "offload",
1913
+ words: ["offload"],
1914
+ summaryKey: "summary.offload",
1915
+ helpKey: "help.offload",
1849
1916
  flags: [{
1850
- name: "plan",
1917
+ name: "heading",
1851
1918
  kind: "value"
1919
+ }, {
1920
+ name: "dry-run",
1921
+ kind: "boolean"
1922
+ }],
1923
+ positional: [],
1924
+ readOnly: false,
1925
+ needsRun: false,
1926
+ fallback: "offload <name> [--heading <heading>] [--dry-run]",
1927
+ usageLine: "offload <name> [--heading <heading>] [--dry-run]"
1928
+ },
1929
+ {
1930
+ id: "condense",
1931
+ words: ["condense"],
1932
+ summaryKey: "summary.condense",
1933
+ helpKey: "help.condense",
1934
+ flags: [{
1935
+ name: "dry-run",
1936
+ kind: "boolean"
1852
1937
  }],
1853
1938
  positional: [],
1854
1939
  readOnly: false,
1855
1940
  needsRun: false,
1856
- fallback: "restructure <name> \"<heading>\" <to_file> [--plan <runId>]",
1857
- usageLine: "restructure <name> \"<heading>\" <to_file> [--plan <runId>]"
1941
+ fallback: "condense <name> [--dry-run]",
1942
+ usageLine: "condense <name> [--dry-run]"
1858
1943
  },
1859
1944
  {
1860
1945
  id: "extract",
@@ -1890,8 +1975,8 @@ const HOST_COMMAND_DEFS = [
1890
1975
  positional: [],
1891
1976
  readOnly: false,
1892
1977
  needsRun: false,
1893
- fallback: "extract <source> <target> \"<heading>\" [--start <line>] [--end <line>] [--outcome extract|mixed] [--proposal <id>] [--owner-covers] [--apply]",
1894
- usageLine: "extract <source> <target> \"<heading>\" [--start <line>] [--end <line>] [--outcome extract|mixed] [--proposal <id>] [--owner-covers] [--apply]"
1978
+ fallback: "extract <source> [<target> \"<heading>\"] [--start <line>] [--end <line>] [--outcome extract|mixed] [--proposal <id>] [--owner-covers] [--apply]",
1979
+ usageLine: "extract <source> [<target> \"<heading>\"] [--start <line>] [--end <line>] [--outcome extract|mixed] [--proposal <id>] [--owner-covers] [--apply]"
1895
1980
  },
1896
1981
  {
1897
1982
  id: "replay",
@@ -3485,7 +3570,7 @@ async function runSkillHistoryCommand(context) {
3485
3570
  const versions = await curator.history(name);
3486
3571
  if (versions.length === 0) return ok$1(`技能 "${name}" 还没有内容版本:下一次经 skill_manage 写入后才会出现。`);
3487
3572
  const groups = partitionVersions(versions);
3488
- const row = (entry) => `v${entry.v}\t${entry.at}\t${entry.action}\t${entry.chars} chars\t${entry.hash.slice(0, 12)}${entry.unitId === void 0 ? "" : `\tunit:${entry.unitId}`}`;
3573
+ const row = (entry) => `v${entry.v}\t${entry.at}\t${entry.action}\t${entry.chars} chars\t${entry.hash.slice(0, 12)}${entry.unitId === void 0 ? "" : `\tunit:${entry.unitId}`}${entry.summary === void 0 ? "" : `\t${entry.summary}`}`;
3489
3574
  const lines = [`技能 "${name}" 的内容版本(由旧到新,${groups.content.length} 条,最多保留这么多):`, ...groups.content.map(row)];
3490
3575
  if (groups.support.length > 0) lines.push("支撑文件版本(仅在历史里 —— 撤销恢复的是 SKILL.md,不是这些字节):", ...groups.support.map(row));
3491
3576
  return ok$1(lines.join("\n"));
@@ -3777,13 +3862,121 @@ function renderRunRecord(record) {
3777
3862
  if (record.resultRef !== void 0) parts.push(`→ ${record.resultRef}`);
3778
3863
  return parts.join(" ");
3779
3864
  }
3780
- /** The newest MAINTENANCE run this home knows — the default when a subcommand omits its id
3781
- * (G2/0.20.0). The registry view is newest-first and already carries the cross-plane rows. The
3782
- * index is a file a user can hand-edit, so a row with a blank id is skipped rather than answered
3783
- * from (review P2-7: it produced text like `Run (succeeded) …`). `RunKind` has one member today,
3784
- * so kind needs no filter — a second kind must add one here when it lands. */
3785
- function newestRun(registry) {
3786
- return registry.runs().find((record) => record.id.trim() !== "");
3865
+ /** The newest run of one kind this home knows — the default when a subcommand omits its id.
3866
+ * The registry view is newest-first and already carries the cross-plane rows. The index is a file
3867
+ * a user can hand-edit, so a row with a blank id is skipped rather than answered from. */
3868
+ const GOVERNANCE_DISPOSE_TIMEOUT_MS = 5e3;
3869
+ const GOVERNANCE_REPORT_TIMEOUT_MS = 1e4;
3870
+ function newestRun(registry, kind = "maintain") {
3871
+ return registry.runs(kind).find((record) => record.id.trim() !== "");
3872
+ }
3873
+ /** Source-only extract discovery: the child proposes an owner; it never writes. */
3874
+ async function discoverExtract(ctx, parent, source, library, io) {
3875
+ const body = await library.read(source);
3876
+ if (body === null) return `技能「${source}」不存在。`;
3877
+ const lookup = ownerCandidatesFromSummaries(source, await library.model.list({
3878
+ withContent: true,
3879
+ withFrontmatter: true
3880
+ }));
3881
+ const support = await library.listSupportFiles(source);
3882
+ const input = JSON.stringify({
3883
+ source,
3884
+ body,
3885
+ support: isPresent(support) ? support.value : null,
3886
+ candidates: lookup.candidates.map((candidate) => ({
3887
+ name: candidate.name,
3888
+ description: candidate.description,
3889
+ whenToUse: candidate.whenToUse ?? null,
3890
+ headings: candidate.headings
3891
+ })),
3892
+ excluded: lookup.excluded
3893
+ });
3894
+ const outcome = await createSubagentChannel(ctx).run({
3895
+ parent,
3896
+ label: "dsh-evolution-extract",
3897
+ kind: "maintainer",
3898
+ allow: ["skill"],
3899
+ promptText: EXTRACT_PROMPT_V1 + "\n\nEXTRACT INPUT\n" + input,
3900
+ timeoutMs: 12e4,
3901
+ outputSchema: {
3902
+ type: "object",
3903
+ additionalProperties: false,
3904
+ required: ["outcome", "reason"],
3905
+ properties: {
3906
+ outcome: {
3907
+ type: "string",
3908
+ enum: [
3909
+ "keep",
3910
+ "extract",
3911
+ "mixed",
3912
+ "owner-gap"
3913
+ ]
3914
+ },
3915
+ target: { type: "string" },
3916
+ neededOwner: { type: "string" },
3917
+ reason: { type: "string" },
3918
+ parts: {
3919
+ type: "array",
3920
+ items: {
3921
+ type: "object",
3922
+ additionalProperties: false,
3923
+ required: ["heading"],
3924
+ properties: {
3925
+ heading: { type: "string" },
3926
+ start: { type: "string" },
3927
+ end: { type: "string" }
3928
+ }
3929
+ }
3930
+ }
3931
+ }
3932
+ }
3933
+ });
3934
+ if (outcome.kind !== "ok") return `extract proposal 不可用:${"reason" in outcome ? outcome.reason : outcome.kind}`;
3935
+ const proposal = outcome.structured;
3936
+ const parts = Array.isArray(proposal.parts) ? proposal.parts.map((part) => part.heading).filter((heading) => typeof heading === "string") : [];
3937
+ const outcomeName = proposal.outcome === "extract" || proposal.outcome === "mixed" ? proposal.outcome : proposal.outcome === "keep" ? "keep" : "owner-gap";
3938
+ const runId = "extract-" + Date.now().toString(36);
3939
+ const target = typeof proposal.target === "string" && proposal.target !== "" ? proposal.target : void 0;
3940
+ const record = {
3941
+ version: 1,
3942
+ id: "extract-" + runId + "-" + source,
3943
+ source,
3944
+ outcome: outcomeName,
3945
+ parts: Array.isArray(proposal.parts) ? proposal.parts.filter((part) => typeof part.heading === "string").map((part) => ({
3946
+ heading: part.heading,
3947
+ anchor: { heading: part.heading },
3948
+ reason: "proposed by extract agent"
3949
+ })) : [],
3950
+ owner: {
3951
+ mode: target === void 0 ? "owner-gap" : "covered",
3952
+ ...target === void 0 ? {} : { name: target },
3953
+ ...proposal.neededOwner === void 0 ? {} : { neededOwner: proposal.neededOwner },
3954
+ triggerCovers: target !== void 0,
3955
+ outcomeCovers: target !== void 0,
3956
+ reason: String(proposal.reason ?? "")
3957
+ },
3958
+ warnings: [],
3959
+ provenance: {
3960
+ promptVersion: "v1",
3961
+ runId,
3962
+ at: Date.now()
3963
+ },
3964
+ status: "proposed"
3965
+ };
3966
+ let proposalLine = "proposal: —";
3967
+ try {
3968
+ await writeProposalReport(io, record);
3969
+ proposalLine = `proposal: ${record.id}\n应用:/evolution extract ${source} --proposal ${record.id}`;
3970
+ } catch {}
3971
+ return [
3972
+ "extract proposal(未写入)",
3973
+ "outcome: " + String(proposal.outcome ?? "unknown"),
3974
+ "target: " + String(proposal.target ?? "—"),
3975
+ "neededOwner: " + String(proposal.neededOwner ?? "—"),
3976
+ "parts: " + (parts.length === 0 ? "—" : parts.join(", ")),
3977
+ "reason: " + String(proposal.reason ?? "—"),
3978
+ proposalLine
3979
+ ].join("\n");
3787
3980
  }
3788
3981
  /** Sentence F, ONE wording for the three id-less forms (design `10` cell 13): an index that could
3789
3982
  * not be read must never answer as "there is no recent run" (G2/0.20.0). */
@@ -4075,6 +4268,33 @@ function apply(ctx, rawConfig = {}) {
4075
4268
  ...rows.map(line)
4076
4269
  ].join("\n"));
4077
4270
  }
4271
+ case "review": {
4272
+ const requested = ("positionals" in command ? command.positionals[0] : void 0) ?? "combined";
4273
+ if (requested !== "memory" && requested !== "skill" && requested !== "combined") return err("用法:/evolution review [memory|skill|combined]");
4274
+ const missing = agentMissing("review");
4275
+ if (missing) return missing;
4276
+ const reviewSession = invocationAgent?.session;
4277
+ const message = createUserMessage({
4278
+ content: [{
4279
+ type: "text",
4280
+ text: reviewPrompt(requested, "inject")
4281
+ }],
4282
+ source: {
4283
+ kind: "evolution-commands",
4284
+ form: "notice",
4285
+ summary: "manual evolution review"
4286
+ }
4287
+ });
4288
+ const agent = invocationAgent;
4289
+ let woke = false;
4290
+ if (typeof agent.followup === "function") {
4291
+ agent.followup(message);
4292
+ woke = true;
4293
+ } else if (typeof agent.inject === "function") agent.inject(message);
4294
+ else return err(hostError("e-305-the-invocation-agent-exposes", { a1: "this review request" }));
4295
+ if (reviewSession?.id !== void 0) markReviewChannel(String(reviewSession.id));
4296
+ return ok(`已注入 ${requested} 复审请求;${woke ? "它会在当前会话立即执行。" : "它会在下一次唤醒时执行。"}`);
4297
+ }
4078
4298
  case "learn": {
4079
4299
  const request = rawInputTrimmed === "learn" ? "" : rawInputTrimmed.slice(6).trim();
4080
4300
  const message = createUserMessage({
@@ -4113,6 +4333,17 @@ function apply(ctx, rawConfig = {}) {
4113
4333
  const proposalFlag = command.flags.get("proposal");
4114
4334
  const ioRegistry = ctx.get("evolutionIo");
4115
4335
  if (!ioRegistry) return err("未挂载 evolution-io 注册表:无法执行 extract。");
4336
+ const library = newSkillLibrary({
4337
+ authority: authorityFrom({ origin: "foreground" }),
4338
+ config: { root: skillsRootValue },
4339
+ io: ioRegistry.provider(),
4340
+ ctx,
4341
+ threatExemptLabels: config.threatExemptLabels,
4342
+ limits: {
4343
+ ...DEFAULT_SKILL_LIMITS,
4344
+ ...policyStageLimits(ctx.get("evolutionPolicy")?.get?.())
4345
+ }
4346
+ });
4116
4347
  let target = command.positionals[1] ?? "";
4117
4348
  let heading = command.positionals[2] ?? "";
4118
4349
  let start;
@@ -4135,7 +4366,9 @@ function apply(ctx, rawConfig = {}) {
4135
4366
  to_skill: target
4136
4367
  }));
4137
4368
  } else {
4138
- if (source === "" || target === "" || heading === "") return err("用法:/evolution extract <source> <target> \"<heading>\" [--start <line>] [--end <line>]");
4369
+ if (source === "") return err("用法:/evolution extract <source> [<target> \"<heading>\"] [--start <line>] [--end <line>]");
4370
+ if (target === "" && heading === "") return ok(await discoverExtract(ctx, invocationAgent, source, library, ioRegistry.provider()));
4371
+ if (target === "" || heading === "") return err("用法:/evolution extract <source> <target> \"<heading>\" [--start <line>] [--end <line>]");
4139
4372
  const startFlag = command.flags.get("start");
4140
4373
  const endFlag = command.flags.get("end");
4141
4374
  start = typeof startFlag === "string" ? startFlag : void 0;
@@ -4150,17 +4383,6 @@ function apply(ctx, rawConfig = {}) {
4150
4383
  const ownerCovers = command.flags.has("owner-covers");
4151
4384
  const outcomeFlag = command.flags.get("outcome");
4152
4385
  if (outcomeFlag !== void 0 && outcomeFlag !== "extract" && outcomeFlag !== "mixed") return err("--outcome 只能是 extract 或 mixed。");
4153
- const library = newSkillLibrary({
4154
- authority: authorityFrom({ origin: "foreground" }),
4155
- config: { root: skillsRootValue },
4156
- io: ioRegistry.provider(),
4157
- ctx,
4158
- threatExemptLabels: config.threatExemptLabels,
4159
- limits: {
4160
- ...DEFAULT_SKILL_LIMITS,
4161
- ...policyStageLimits(ctx.get("evolutionPolicy")?.get?.())
4162
- }
4163
- });
4164
4386
  const built = await buildExtractPlanFromLibrary(library, {
4165
4387
  source,
4166
4388
  items: extractItems,
@@ -4214,6 +4436,17 @@ function apply(ctx, rawConfig = {}) {
4214
4436
  if (name === "" || heading === "" || toFile === "") return err("用法:/evolution restructure <name> \"<heading>\" <to_file>");
4215
4437
  const planFlag = command.flags.get("plan");
4216
4438
  const planRunId = typeof planFlag === "string" ? planFlag : void 0;
4439
+ const startFlag = command.flags.get("start");
4440
+ const endFlag = command.flags.get("end");
4441
+ const start = typeof startFlag === "string" ? startFlag : void 0;
4442
+ const end = typeof endFlag === "string" ? endFlag : void 0;
4443
+ if (start === void 0 !== (end === void 0)) return err("--start 和 --end 必须同时提供。");
4444
+ const move = {
4445
+ heading,
4446
+ ...start === void 0 ? {} : { start },
4447
+ ...end === void 0 ? {} : { end },
4448
+ toFile
4449
+ };
4217
4450
  if (!toFile.startsWith("references/")) return err("to_file 必须位于 references/ 之下(日志或明细的落地位置)。");
4218
4451
  const ioRegistry = ctx.get("evolutionIo");
4219
4452
  if (!ioRegistry) return err("未挂载 evolution-io 注册表:无法重构。");
@@ -4232,6 +4465,8 @@ function apply(ctx, rawConfig = {}) {
4232
4465
  name,
4233
4466
  restructure: [{
4234
4467
  heading,
4468
+ ...start === void 0 ? {} : { start },
4469
+ ...end === void 0 ? {} : { end },
4235
4470
  to_file: toFile
4236
4471
  }]
4237
4472
  },
@@ -4257,14 +4492,195 @@ function apply(ctx, rawConfig = {}) {
4257
4492
  ...DEFAULT_SKILL_LIMITS,
4258
4493
  ...policyStageLimits(ctx.get("evolutionPolicy")?.get?.())
4259
4494
  }
4260
- }).restructure(name, [{
4261
- heading,
4262
- toFile
4263
- }], "foreground");
4495
+ }).restructure(name, [move], "foreground");
4264
4496
  if (!result.ok) return err(result.message);
4265
4497
  await ctx.get("skillUsage")?.record?.(name, "patch");
4266
4498
  return ok(planRunId ? `${result.message}\n[audit] plan=${planRunId}` : result.message);
4267
4499
  }
4500
+ case "offload": {
4501
+ if (!("positionals" in command)) return err("用法:/evolution offload <skill> [--heading <heading>] [--dry-run]");
4502
+ const target = command.positionals[0] ?? "";
4503
+ if (target === "") return err("用法:/evolution offload <skill> [--heading <heading>] [--dry-run]");
4504
+ const headingFlag = command.flags.get("heading");
4505
+ const heading = typeof headingFlag === "string" && headingFlag.trim() !== "" ? headingFlag.trim() : void 0;
4506
+ const dryRun = command.flags.has("dry-run");
4507
+ if (!dryRun && approval !== void 0 && approval.isEnabled !== false) return err("当前部署开启了写入审批:offload 的子智能体是 background origin,写入会被暂存。请先关闭审批,或用 --dry-run 预览。");
4508
+ const agent = invocationAgent;
4509
+ if (agent === void 0) return err(hostError("e-305-this-invocation-carries-no", { a1: "offload subagent" }));
4510
+ const channel = createSubagentChannel(ctx);
4511
+ if (channel.state.kind !== "available") return err(`offload 子智能体不可用:${channel.state.reason}`);
4512
+ if (channel.open === void 0) return err("当前部署的 subagent 通道不支持 offload。");
4513
+ const allow = dryRun ? [
4514
+ "skill",
4515
+ "read",
4516
+ "glob",
4517
+ "grep"
4518
+ ] : [
4519
+ "skill",
4520
+ "read",
4521
+ "glob",
4522
+ "grep",
4523
+ "skill_manage"
4524
+ ];
4525
+ const prepared = await channel.prepare({
4526
+ kind: "governance",
4527
+ allow
4528
+ });
4529
+ if (prepared.kind !== "available") return err(`offload 子智能体不可用:${prepared.reason}`);
4530
+ const prompt = GOVERNANCE_PROMPT_TEMPLATE.replace("%SKILL%", target).replace("%MODE%", "offload").replace("%HEADING%", heading ?? "whole skill").replace("%DRY%", dryRun ? "yes (no writes)" : "no");
4531
+ const runId = "offload-" + Date.now().toString(36);
4532
+ const opened = await withReviewContext({
4533
+ reviewId: runId,
4534
+ runId,
4535
+ reads: /* @__PURE__ */ new Set()
4536
+ }, async () => await channel.open({
4537
+ parent: agent,
4538
+ label: `offload:${target}`,
4539
+ promptText: prompt,
4540
+ kind: "governance",
4541
+ allow,
4542
+ ...invocation.signal === void 0 ? {} : { signal: invocation.signal },
4543
+ timeoutMs: 900 * 1e3
4544
+ }));
4545
+ if (opened.kind === "ok") {
4546
+ await channel.dispose?.(opened.childId).catch(() => {});
4547
+ return ok(opened.turn.text);
4548
+ }
4549
+ if (opened.kind === "unavailable") return err(`offload 子智能体不可用:${opened.reason}`);
4550
+ return err("offload 已取消。");
4551
+ }
4552
+ case "condense": {
4553
+ if (!("positionals" in command)) return err("用法:/evolution condense <skill> [--dry-run]");
4554
+ const target = command.positionals[0] ?? "";
4555
+ if (target === "") return err("用法:/evolution condense <skill> [--dry-run]");
4556
+ const mode = "condense";
4557
+ const dryRun = command.flags.has("dry-run");
4558
+ if (!dryRun && approval !== void 0 && approval.isEnabled !== false) return err("当前部署开启了写入审批:治理子智能体是 background origin,写入会被暂存,无法保证历史 unit。请先关闭审批,或用 --dry-run 预览。");
4559
+ const agent = invocationAgent;
4560
+ if (agent === void 0) return err(hostError("e-305-this-invocation-carries-no", { a1: "governance subagent" }));
4561
+ const ioRegistry = ctx.get("evolutionIo");
4562
+ if (ioRegistry !== void 0) {
4563
+ if (await newSkillLibrary({
4564
+ authority: authorityFrom({ origin: "foreground" }),
4565
+ config: { root: skillsRootValue },
4566
+ io: ioRegistry.provider(),
4567
+ ctx,
4568
+ threatExemptLabels: config.threatExemptLabels,
4569
+ limits: {
4570
+ ...DEFAULT_SKILL_LIMITS,
4571
+ ...policyStageLimits(ctx.get("evolutionPolicy")?.get?.())
4572
+ }
4573
+ }).isPinned(target)) return err(`技能「${target}」已固定(pinned),治理子智能体不能修改;先 /evolution skill unpin ${target}。`);
4574
+ }
4575
+ const channel = createSubagentChannel(ctx);
4576
+ if (channel.state.kind !== "available") return err(`治理子智能体不可用:${channel.state.reason}`);
4577
+ if (channel.open === void 0) return err("当前部署的 subagent 通道不支持治理运行。");
4578
+ if (runs === void 0) return err("未挂载 evolution-io 注册表:无法记录治理运行。");
4579
+ const allow = dryRun ? [
4580
+ "skill",
4581
+ "read",
4582
+ "glob",
4583
+ "grep"
4584
+ ] : [
4585
+ "skill",
4586
+ "read",
4587
+ "glob",
4588
+ "grep",
4589
+ "skill_manage"
4590
+ ];
4591
+ const prepared = await channel.prepare({
4592
+ kind: "governance",
4593
+ allow
4594
+ });
4595
+ if (prepared.kind !== "available") return err(`治理子智能体不可用:${prepared.reason}`);
4596
+ const active = await runs.findActive("governance");
4597
+ if (active !== void 0) return err(`已有治理运行在跑:${active.id}。先等它完成,或用 /evolution maintain status ${active.id} 查看。`);
4598
+ let run;
4599
+ try {
4600
+ run = await runs.begin("governance", { exclusive: true });
4601
+ } catch {
4602
+ const current = runs.inFlight("governance");
4603
+ return err(current === void 0 ? "已有治理运行在跑。先等它完成,或用 /evolution maintain status 查看。" : `已有治理运行在跑:${current.id}。先等它完成,或用 /evolution maintain status ${current.id} 查看。`);
4604
+ }
4605
+ await runs.stage(run.id, "author", {
4606
+ done: 0,
4607
+ total: 1
4608
+ });
4609
+ const prompt = GOVERNANCE_PROMPT_TEMPLATE.replace("%SKILL%", target).replace("%MODE%", mode).replace("%HEADING%", "whole skill").replace("%DRY%", dryRun ? "yes (no writes)" : "no");
4610
+ const io = ctx.get("evolutionIo")?.provider?.();
4611
+ const reportPath = join(evolutionHome(), "reports", `governance-${run.id}.json`);
4612
+ const writeReport = async (state, text, failure) => {
4613
+ if (io === void 0) return false;
4614
+ try {
4615
+ const write = io.writeText(reportPath, JSON.stringify({
4616
+ version: 1,
4617
+ runId: run.id,
4618
+ target,
4619
+ mode,
4620
+ dryRun,
4621
+ state,
4622
+ startedAt: run.startedAt,
4623
+ finishedAt: (/* @__PURE__ */ new Date()).toISOString(),
4624
+ text,
4625
+ ...failure === void 0 ? {} : { failure }
4626
+ }, null, 2) + "\n").then(() => true).catch(() => false);
4627
+ return await Promise.race([write, new Promise((resolve) => setTimeout(() => resolve(false), GOVERNANCE_REPORT_TIMEOUT_MS))]);
4628
+ } catch (error) {
4629
+ ctx.logger.warn(`dsh-evolution-commands: tidy ${target} report write failed: ${error instanceof Error ? error.message : String(error)}`);
4630
+ return false;
4631
+ }
4632
+ };
4633
+ const open = channel.open.bind(channel);
4634
+ (async () => {
4635
+ try {
4636
+ const opened = await withReviewContext({
4637
+ reviewId: run.id,
4638
+ runId: run.id,
4639
+ reads: /* @__PURE__ */ new Set()
4640
+ }, async () => await open({
4641
+ parent: agent,
4642
+ label: `governance:${target}`,
4643
+ promptText: prompt,
4644
+ kind: "governance",
4645
+ allow,
4646
+ timeoutMs: 900 * 1e3,
4647
+ signal: run.signal
4648
+ }));
4649
+ if (opened.kind === "ok") {
4650
+ const dispose = channel.dispose?.(opened.childId);
4651
+ if (dispose !== void 0) await Promise.race([dispose.catch(() => {}), new Promise((resolve) => setTimeout(resolve, GOVERNANCE_DISPOSE_TIMEOUT_MS))]);
4652
+ const wrote = await writeReport("succeeded", opened.turn.text);
4653
+ await runs.stage(run.id, "settle", {
4654
+ done: 1,
4655
+ total: 1
4656
+ });
4657
+ await runs.settle(run.id, {
4658
+ state: "succeeded",
4659
+ ...wrote ? { resultRef: reportPath } : {}
4660
+ });
4661
+ return;
4662
+ }
4663
+ const state = opened.kind === "aborted" ? "cancelled" : "failed";
4664
+ const failure = opened.kind === "aborted" ? "cancelled" : opened.reason;
4665
+ const wrote = await writeReport(state, "", failure);
4666
+ await runs.settle(run.id, {
4667
+ state,
4668
+ ...wrote ? { resultRef: reportPath } : {},
4669
+ ...failure === void 0 ? {} : { failure }
4670
+ });
4671
+ } catch (error) {
4672
+ const failure = error instanceof Error ? error.message : String(error);
4673
+ ctx.logger.warn(`dsh-evolution-commands: tidy ${target} failed: ${failure}`);
4674
+ const wrote = await writeReport("failed", "", failure);
4675
+ await runs.settle(run.id, {
4676
+ state: "failed",
4677
+ ...wrote ? { resultRef: reportPath } : {},
4678
+ failure
4679
+ });
4680
+ }
4681
+ })();
4682
+ return ok(`已启动治理:${target}(mode=${mode}${dryRun ? ",dry-run" : ""};run=${run.id})。完成后在技能历史查看摘要;用 /evolution maintain status ${run.id} 查状态;报告 ${reportPath}。`);
4683
+ }
4268
4684
  case "merge": {
4269
4685
  const merge = ctx.get("evolutionMerge");
4270
4686
  if (merge === void 0) return err("merge 未挂载:当前安装形态没有 evolution-merge 行(安装形态与命令可用性见 INSTALL.md),或先运行 /evolution doctor。");
@@ -182,6 +182,16 @@ export declare const HOST_COMMANDS: {
182
182
  readonly ru: "Отправить запрос на обучение в эту сессию";
183
183
  readonly pt: "Enviar uma solicitação de aprendizado para esta sessão";
184
184
  };
185
+ readonly "summary.review": {
186
+ readonly zh: "立即向本会话注入一次复盘(不等空闲)";
187
+ readonly en: "Inject one review into this session now (no idle wait)";
188
+ readonly ja: "このセッションに今すぐレビューを注入(idle 待ちなし)";
189
+ readonly es: "Inyectar una revisión en esta sesión ahora (sin esperar idle)";
190
+ readonly fr: "Injecter une revue dans cette session maintenant (sans attendre idle)";
191
+ readonly de: "Jetzt eine Review in diese Sitzung einspeisen (ohne Idle-Warten)";
192
+ readonly ru: "Сразу внедрить проверку в эту сессию (без ожидания idle)";
193
+ readonly pt: "Injetar uma revisão nesta sessão agora (sem esperar idle)";
194
+ };
185
195
  readonly "summary.maintain": {
186
196
  readonly zh: "起一次维护扫描并立即回 run id(后台跑;--facts 为 0 token 预览)";
187
197
  readonly en: "Start a maintenance scan and return the run id immediately (runs in the background; --facts is a 0-token preview)";
@@ -282,6 +292,26 @@ export declare const HOST_COMMANDS: {
282
292
  readonly ru: "Перенести один раздел текста навыка в файл references";
283
293
  readonly pt: "Mover uma seção do corpo de uma skill para um arquivo references";
284
294
  };
295
+ readonly "summary.offload": {
296
+ readonly zh: "把技能正文的会话细节章节移到 references(后台子智能体,--dry-run 只预览)";
297
+ readonly en: "Move session-detail sections from a skill body into references (background subagent; --dry-run previews only)";
298
+ readonly ja: "スキル本文のセッション詳細セクションを references へ移す(バックグラウンド子エージェント、--dry-run はプレビューのみ)";
299
+ readonly es: "Mover secciones de detalle de sesión del cuerpo de un skill a references (subagente en segundo plano; --dry-run solo previsualiza)";
300
+ readonly fr: "Déplacer les sections de détail de session d’un skill vers references (sous-agent en arrière-plan ; --dry-run prévisualise seulement)";
301
+ readonly de: "Sitzungsdetail-Abschnitte aus einem Skill-Text nach references verschieben (Hintergrund-Subagent; --dry-run zeigt nur die Vorschau)";
302
+ readonly ru: "Перенести разделы с деталями сессии из текста навыка в references (фоновый подагент; --dry-run только предпросмотр)";
303
+ readonly pt: "Mover seções de detalhe de sessão do corpo de uma skill para references (subagente em segundo plano; --dry-run apenas pré-visualiza)";
304
+ };
305
+ readonly "summary.condense": {
306
+ readonly zh: "逐章节压缩技能正文(后台子智能体,多次小改,--dry-run 只预览)";
307
+ readonly en: "Condense a skill body section by section (background subagent, repeated small edits; --dry-run previews only)";
308
+ readonly ja: "スキル本文をセクション単位で圧縮(バックグラウンド子エージェント、小さな編集を繰り返す、--dry-run はプレビューのみ)";
309
+ readonly es: "Condensar el cuerpo de un skill sección por sección (subagente en segundo plano, ediciones pequeñas repetidas; --dry-run solo previsualiza)";
310
+ readonly fr: "Condenser le corps d’un skill section par section (sous-agent en arrière-plan, petites modifications répétées ; --dry-run prévisualise seulement)";
311
+ readonly de: "Einen Skill-Text Abschnitt für Abschnitt verdichten (Hintergrund-Subagent, wiederholte kleine Änderungen; --dry-run zeigt nur die Vorschau)";
312
+ readonly ru: "Сжимать текст навыка по разделам (фоновый подагент, повторные небольшие правки; --dry-run только предпросмотр)";
313
+ readonly pt: "Condensar o corpo de uma skill seção por seção (subagente em segundo plano, pequenas edições repetidas; --dry-run apenas pré-visualiza)";
314
+ };
285
315
  readonly "summary.extract": {
286
316
  readonly zh: "预览把源技能的可复用部分提取到已有类级 owner;默认 plan,--apply 才写(多根一次事务)";
287
317
  readonly en: "Preview extracting a source skill's reusable part into an existing class-level owner; by default it produces a plan, and only --apply writes (multiple roots in one transaction)";
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@lmzhen/dsh-evolution-commands",
3
3
  "description": "Human commands for the evolution family (/evolution pending|curator|maintain|doctor) (community build)",
4
- "version": "0.50.0",
4
+ "version": "0.51.1",
5
5
  "publishConfig": {
6
6
  "access": "public"
7
7
  },
@@ -29,13 +29,13 @@
29
29
  "license": "MIT",
30
30
  "dependencies": {
31
31
  "@deepseek-ai/schemastery": "^3.18.5",
32
- "@lmzhen/dsh-evolution-approval": "^0.50.0",
33
- "@lmzhen/dsh-evolution-core": "^0.50.0",
34
- "@lmzhen/dsh-evolution-maintenance": "^0.50.0",
35
- "@lmzhen/dsh-evolution-state": "^0.50.0"
32
+ "@lmzhen/dsh-evolution-approval": "^0.51.1",
33
+ "@lmzhen/dsh-evolution-core": "^0.51.1",
34
+ "@lmzhen/dsh-evolution-maintenance": "^0.51.1",
35
+ "@lmzhen/dsh-evolution-state": "^0.51.1"
36
36
  },
37
37
  "optionalDependencies": {
38
- "@lmzhen/dsh-evolution-agent-preset": "^0.50.0"
38
+ "@lmzhen/dsh-evolution-agent-preset": "^0.51.1"
39
39
  },
40
40
  "peerDependencies": {
41
41
  "@deepseek-ai/cordis": "^4.0.5",