@lmzhen/dsh-evolution-commands 0.47.0 → 0.48.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
@@ -40,6 +40,12 @@ const COMMAND_FALLBACKS = {
40
40
  };
41
41
  //#endregion
42
42
  //#region lib/types/doctor-view.js
43
+ /** The ONE install-form decision; callers only supply the facts their detection read. */
44
+ function classifyInstallForm(input) {
45
+ if (input.full || input.preset) return input.humanGated ? "human-gated" : input.full ? "full" : "preset";
46
+ if (input.host) return input.layeredPreset ? "layered" : "host";
47
+ return input.presetDirInstalled ? "preset-only" : "none";
48
+ }
43
49
  const FACT_HOMES = {
44
50
  "platform-line": "README.md(兼容线声明)",
45
51
  "family-version": "README.md(家族版本)",
@@ -492,15 +498,23 @@ async function assembleDoctorInputs(ctx, extras = {}) {
492
498
  const hasHost = bundles.some((name) => name.endsWith("dsh-evolution-host"));
493
499
  const hasFamilyPreset = listed.some((entry) => typeof entry.id === "string" && EVOLUTION_PRESET_IDS.includes(entry.id));
494
500
  const humanGated = get("evolutionApproval")?.isEnabled === true;
495
- const detectedForm = hasAll || hasPreset ? {
496
- id: humanGated ? "human-gated" : hasAll ? "full" : "preset",
501
+ const detectedId = classifyInstallForm({
502
+ full: hasAll,
503
+ preset: hasPreset,
504
+ host: hasHost,
505
+ humanGated,
506
+ layeredPreset: hasFamilyPreset,
507
+ presetDirInstalled: false
508
+ });
509
+ const detectedForm = detectedId === "full" || detectedId === "preset" || detectedId === "human-gated" ? {
510
+ id: detectedId,
497
511
  evidence: [hasAll ? "bundle dsh-evolution-all installed" : "bundle dsh-evolution-preset installed", ...humanGated ? ["approval.enabled: true"] : []],
498
512
  confidence: "declared"
499
- } : hasHost ? hasFamilyPreset ? {
513
+ } : detectedId === "layered" ? {
500
514
  id: "layered",
501
515
  evidence: ["bundle dsh-evolution-host installed", "family agent preset registered"],
502
516
  confidence: "declared"
503
- } : {
517
+ } : detectedId === "host" ? {
504
518
  id: "host",
505
519
  evidence: ["bundle dsh-evolution-host installed"],
506
520
  confidence: "declared"
@@ -1096,14 +1110,14 @@ const HOST_COMMANDS = {
1096
1110
  "pt": "atualizado — uma nova geração corresponde byte a byte a este arquivo"
1097
1111
  },
1098
1112
  "doctor.presetDiffers": {
1099
- "zh": "与最新生成不同 — 这是安装时快照;重新运行安装器(/evolution preset install)以重新生成",
1100
- "en": "DIFFERS from a fresh generation — it is an install-time snapshot; re-run the installer (/evolution preset install) to regenerate",
1101
- "ja": "最新の生成結果と異なります — インストール時のスナップショットです。インストーラー(/evolution preset install)を再実行して再生成してください",
1102
- "es": "DIFIERE de una generación nueva — es una instantánea del momento de instalar; vuelve a ejecutar el instalador (/evolution preset install) para regenerarla",
1103
- "fr": "DIFFÈRE d’une nouvelle génération — c’est un instantané de l’installation ; relancez l’installateur (/evolution preset install) pour la régénérer",
1104
- "de": "WEICHT von einer neuen Erzeugung ab — es ist ein Installations-Snapshot; Installer erneut ausführen (/evolution preset install), um ihn neu zu erzeugen",
1105
- "ru": "ОТЛИЧАЕТСЯ от новой генерации — это снимок на момент установки; запустите установщик повторно (/evolution preset install)",
1106
- "pt": "DIFERE de uma nova geração — é um instantâneo do momento da instalação; execute o instalador novamente (/evolution preset install)"
1113
+ "zh": "与最新生成不同 — 这是安装时快照;重新运行安装器(all/host)以重新生成",
1114
+ "en": "DIFFERS from a fresh generation — it is an install-time snapshot; re-run the installer (all/host) to regenerate",
1115
+ "ja": "最新の生成結果と異なります — インストール時のスナップショットです。インストーラー(all/host)を再実行して再生成してください",
1116
+ "es": "DIFIERE de una generación nueva — es una instantánea del momento de instalar; vuelve a ejecutar el instalador (all/host) para regenerarla",
1117
+ "fr": "DIFFÈRE d’une nouvelle génération — c’est un instantané de l’installation ; relancez l’installateur (all/host) pour la régénérer",
1118
+ "de": "WEICHT von einer neuen Erzeugung ab — es ist ein Installations-Snapshot; Installer erneut ausführen (all/host), um ihn neu zu erzeugen",
1119
+ "ru": "ОТЛИЧАЕТСЯ от новой генерации — это снимок на момент установки; запустите установщик повторно (all/host)",
1120
+ "pt": "DIFERE de uma nova geração — é um instantâneo do momento da instalação; execute o instalador novamente (all/host)"
1107
1121
  },
1108
1122
  "doctor.presetUnknown": {
1109
1123
  "zh": "未知 — 无法重新生成({detail})",
@@ -2250,7 +2264,7 @@ async function diagnose(ctx, options = {}) {
2250
2264
  let pendingTtlMs = null;
2251
2265
  const approvalService = ctx.get("evolutionApproval");
2252
2266
  if (typeof approvalService?.ttlMs === "number" && Number.isFinite(approvalService.ttlMs)) pendingTtlMs = approvalService.ttlMs;
2253
- const approvalList = approvalService?.list?.bind(approvalService);
2267
+ const approvalList = (approvalService?.listReadonly ?? approvalService?.list)?.bind(approvalService);
2254
2268
  if (approvalList !== void 0) try {
2255
2269
  const pendingProbe = await probeBounded(() => approvalList("pending"), "approval pending listing");
2256
2270
  const rows = pendingProbe.ok ? pendingProbe.value : void 0;
@@ -2262,8 +2276,14 @@ async function diagnose(ctx, options = {}) {
2262
2276
  pendingCount = null;
2263
2277
  executingCount = null;
2264
2278
  }
2265
- const humanGated = ctx.get("evolutionApproval")?.isEnabled === true;
2266
- const installForm = full || preset ? humanGated ? "human-gated" : full ? "full" : "preset" : layered ? "layered" : host ? "host" : presetDirInstalled ? "preset-only" : "none";
2279
+ const installForm = classifyInstallForm({
2280
+ full,
2281
+ preset,
2282
+ host,
2283
+ humanGated: ctx.get("evolutionApproval")?.isEnabled === true,
2284
+ layeredPreset: layered,
2285
+ presetDirInstalled
2286
+ });
2267
2287
  const mountConflicts = conflicts.filter((row) => !row.includes("DEGRADED"));
2268
2288
  const undecidable = mountConflicts.length !== conflicts.length;
2269
2289
  const scopedProbe = {
@@ -2290,7 +2310,7 @@ async function diagnose(ctx, options = {}) {
2290
2310
  const queryIssues = await sessionQueryIssues(ctx);
2291
2311
  if (queryIssues.length > 0) actions.push("Session search is degraded: isolate the session named above (or wait for the platform fix described in the family maintenance notes) before retrying the same query");
2292
2312
  if (paramIssues.length > 0) actions.push("Review the parameter divergences above: /evolution params shows every row with its source, /evolution policy set writes a user value, and a declared-but-unreachable row needs its owning plugin row mounted in this profile.");
2293
- if (budgetIssues.length > 0) actions.push("Align the memory budget: leave memory-files memoryCharLimit/userCharLimit UNSET so the store follows evolution-policy, or set both surfaces to the same value (the review plans against the policy value while the store enforces its own)");
2313
+ if (budgetIssues.length > 0) actions.push("Align the memory budget: leave memory-files memoryChars/userChars UNSET so the store follows evolution-policy, or set both surfaces to the same value (the review plans against the policy value while the store enforces its own)");
2294
2314
  if (scopedProbe.rows !== null && scopedProbe.rows.length > 0 && scopedProbe.verdict === "never-hit") actions.push("The session-scoped rows are mounted but the family-tool probe has never matched in this process — review injection and skill-usage telemetry skipped every session observed. HOST-ONLY install: the model rows (tool-memory / tool-skill-manage) sit in evolution-host devDependencies, so no session carries them; install a bundle that mounts them (see INSTALL.md). VARIANT install: only a session on the Evolution preset matches, so open one — a session on a platform original preset is the intended skip, not a fault. Either way, check that no profile overlay disables those two rows.");
2295
2315
  if ((executingCount ?? 0) > 0) actions.push(`${executingCount} staged write(s) are EXECUTING (an approve crashed mid-run — or one is still in flight). Inspect with /evolution pending: if you started the approve, verify the landed write and do not reject it; only reject after verifying no write is intended. For a verified orphan (this build: S2-P2-22), /evolution release <id> returns it to the pending window instead.`);
2296
2316
  for (const row of presetFreshness) {
@@ -2362,7 +2382,7 @@ async function mergeDoctorLine(ctx) {
2362
2382
  }
2363
2383
  /**
2364
2384
  * S2-12③ (FLOW5-4): the memory budget is configured in TWO places —
2365
- * `memory-files`' `memoryCharLimit`/`userCharLimit` (what the STORE enforces)
2385
+ * `memory-files`' `memoryChars`/`userChars` (what the STORE enforces)
2366
2386
  * and `evolution-policy`'s `memoryChars`/`userChars` (what the review PLANS
2367
2387
  * against; `memory-files` follows the policy only for an UNSET limit). A
2368
2388
  * disagreement therefore means an explicit contradiction, or a `memory-files`
@@ -2445,8 +2465,8 @@ function memoryBudgetIssues(ctx) {
2445
2465
  const policy = ctx.get("evolutionPolicy")?.get?.();
2446
2466
  if (budget === void 0 || policy === void 0) return [];
2447
2467
  const issues = [];
2448
- if (budget.memoryCharLimit !== void 0 && policy.memoryChars !== void 0 && budget.memoryCharLimit !== policy.memoryChars) issues.push(`store enforces memoryCharLimit=${budget.memoryCharLimit} (source: ${budget.memorySource ?? "unknown"}) while evolution-policy declares memoryChars=${policy.memoryChars} — the review plans against the policy value and the store refuses what exceeds its own`);
2449
- if (budget.userCharLimit !== void 0 && policy.userChars !== void 0 && budget.userCharLimit !== policy.userChars) issues.push(`store enforces userCharLimit=${budget.userCharLimit} (source: ${budget.userSource ?? "unknown"}) while evolution-policy declares userChars=${policy.userChars} — same divergence as the memory limit`);
2468
+ if (budget.memoryChars !== void 0 && policy.memoryChars !== void 0 && budget.memoryChars !== policy.memoryChars) issues.push(`store enforces memoryChars=${budget.memoryChars} (source: ${budget.memorySource ?? "unknown"}) while evolution-policy declares memoryChars=${policy.memoryChars} — the review plans against the policy value and the store refuses what exceeds its own`);
2469
+ if (budget.userChars !== void 0 && policy.userChars !== void 0 && budget.userChars !== policy.userChars) issues.push(`store enforces userChars=${budget.userChars} (source: ${budget.userSource ?? "unknown"}) while evolution-policy declares userChars=${policy.userChars} — same divergence as the memory limit`);
2450
2470
  return issues;
2451
2471
  }
2452
2472
  /** S0-4 (v43 G-1 / J-1): the scoped-row reconciliation line. The verdict is the
@@ -2705,226 +2725,448 @@ function renderParamJson(rows) {
2705
2725
  return JSON.stringify({ params: rows }, null, 2);
2706
2726
  }
2707
2727
  //#endregion
2708
- //#region lib/types/registry.js
2709
- /**
2710
- * Subcommand registry — the SINGLE SOURCE for the /evolution command surface.
2711
- *
2712
- * 0.3.55 (WD1): the input-declaration hint, the bare `/evolution` help output
2713
- * and the README command table all render FROM this table; a hand-written
2714
- * copy anywhere is drift waiting to happen (v10 R-13 proved it once).
2715
- * PLAN S5.3 (2026-09-16): "the README command table" means the FAMILY README
2716
- * (`packages/README.md` — the T-WD2 anchor). Package-level READMEs cite that
2717
- * home instead of restating the table (doc-facts rule N19).
2718
- * Keep `usage` in the exact shape a user can type after `/evolution`.
2719
- */
2720
- /** The flags the TABLE declares for one subcommand (name → `--flag`), DERIVED from its usage. */
2721
- function flagsOf(name) {
2722
- const entry = COMMAND_ENTRIES.find((candidate) => entryName(candidate) === name);
2723
- return entry === void 0 ? [] : entryFlags(entry);
2724
- }
2725
- /**
2726
- * C7 shape, DERIVED: the entry IDENTITY key, and it is HIERARCHICAL (E-08).
2727
- *
2728
- * The key used to be the first token alone, and `flagsOf` finds an entry with `.find(...)` - the FIRST
2729
- * match - so `maintain handoff` / `maintain cancel` and `skill restore` / `skill history` / `skill undo` /
2730
- * `skill pin` all derived the SAME key as their parent and every flag lookup silently saw the parent entry
2731
- * only (nine collisions). A bare parent (`maintain [--timeout]`) keeps its one-token key, so parent lookups
2732
- * still resolve: the one call site that named an entry by a name the key no longer produced was the preset
2733
- * dispatch branch, and it now asks for the entry own key (`preset install`).
2734
- */
2735
- function entryName(entry) {
2736
- const [head = "", second = ""] = entry.usage.split(" ");
2737
- const name = head.split("|")[0] ?? "";
2738
- return /^[a-z][a-z-]*$/.test(second) && !second.startsWith("--") ? name + " " + second : name;
2739
- }
2740
- /** C7 shape, DERIVED: the flags a `usage` declares, in the form `--flag` (value flags keep their name). */
2741
- function entryFlags(entry) {
2742
- const found = [];
2743
- for (const match of entry.usage.matchAll(/--[a-z][a-z-]*/g)) if (!found.includes(match[0])) found.push(match[0]);
2744
- return found;
2745
- }
2746
- const COMMAND_ENTRIES = [
2728
+ //#region lib/types/host-command-defs.js
2729
+ const HOST_COMMAND_DEFS = [
2747
2730
  {
2748
- readonly: false,
2749
- usage: "merge <subcommand> [<args>]",
2750
- summary: "技能自动合并(扫描/待批准/重跑/报告/撤销)"
2731
+ id: "merge",
2732
+ words: ["merge"],
2733
+ summaryKey: "summary.merge",
2734
+ helpKey: "help.merge",
2735
+ flags: [],
2736
+ positional: [],
2737
+ readOnly: false,
2738
+ needsRun: false,
2739
+ fallback: "merge <subcommand> [<args>]",
2740
+ usageLine: "merge <subcommand> [<args>]"
2751
2741
  },
2752
2742
  {
2753
- readonly: true,
2754
- usage: "pending [--detail]",
2755
- summary: "列出暂存的写入(--detail 显示参数)"
2743
+ id: "pending",
2744
+ words: ["pending"],
2745
+ summaryKey: "summary.pending",
2746
+ helpKey: "help.pending",
2747
+ flags: [{
2748
+ name: "detail",
2749
+ kind: "boolean"
2750
+ }],
2751
+ positional: [],
2752
+ readOnly: true,
2753
+ needsRun: false,
2754
+ fallback: "pending [--detail]",
2755
+ usageLine: "pending [--detail]"
2756
2756
  },
2757
2757
  {
2758
- readonly: false,
2759
- usage: "approve <id>",
2760
- summary: "执行一条已批准的写入"
2758
+ id: "approve",
2759
+ words: ["approve"],
2760
+ summaryKey: "summary.approve",
2761
+ helpKey: "help.approve",
2762
+ flags: [],
2763
+ positional: [],
2764
+ readOnly: false,
2765
+ needsRun: false,
2766
+ fallback: "approve <id>",
2767
+ usageLine: "approve <id>"
2761
2768
  },
2762
2769
  {
2763
- readonly: false,
2764
- usage: "reject <id>",
2765
- summary: "丢弃一条暂存写入,不执行"
2770
+ id: "reject",
2771
+ words: ["reject"],
2772
+ summaryKey: "summary.reject",
2773
+ helpKey: "help.reject",
2774
+ flags: [],
2775
+ positional: [],
2776
+ readOnly: false,
2777
+ needsRun: false,
2778
+ fallback: "reject <id>",
2779
+ usageLine: "reject <id>"
2766
2780
  },
2767
2781
  {
2768
- readonly: false,
2769
- usage: "release <id>",
2770
- summary: "把卡在执行中的写入放回待批窗口(先确认效果再批准或驳回)"
2782
+ id: "release",
2783
+ words: ["release"],
2784
+ summaryKey: "summary.release",
2785
+ helpKey: "help.release",
2786
+ flags: [],
2787
+ positional: [],
2788
+ readOnly: false,
2789
+ needsRun: false,
2790
+ fallback: "release <id>",
2791
+ usageLine: "release <id>"
2771
2792
  },
2772
2793
  {
2773
- readonly: true,
2774
- usage: "doctor [--json]",
2775
- summary: "只读自检:安装形态、冲突、环境、服务(--json 供脚本用)"
2794
+ id: "doctor",
2795
+ words: ["doctor"],
2796
+ summaryKey: "summary.doctor",
2797
+ helpKey: "help.doctor",
2798
+ flags: [{
2799
+ name: "json",
2800
+ kind: "boolean"
2801
+ }],
2802
+ positional: [],
2803
+ readOnly: true,
2804
+ needsRun: false,
2805
+ fallback: "doctor [--json]",
2806
+ usageLine: "doctor [--json]"
2776
2807
  },
2777
2808
  {
2778
- readonly: false,
2779
- usage: "curator run|pause|resume|status|report|scope",
2780
- summary: "立即运行一次自动整理,或暂停/恢复/查看状态"
2809
+ id: "curator",
2810
+ words: ["curator"],
2811
+ summaryKey: "summary.curator",
2812
+ helpKey: "help.curator",
2813
+ flags: [],
2814
+ positional: [],
2815
+ readOnly: false,
2816
+ needsRun: false,
2817
+ fallback: "curator run|pause|resume|status|report|scope",
2818
+ usageLine: "curator run|pause|resume|status|report|scope"
2781
2819
  },
2782
2820
  {
2783
- readonly: true,
2784
- usage: "mutations",
2785
- summary: "列出技能改动记录"
2821
+ id: "mutations",
2822
+ words: ["mutations"],
2823
+ summaryKey: "summary.mutations",
2824
+ helpKey: "help.mutations",
2825
+ flags: [],
2826
+ positional: [],
2827
+ readOnly: true,
2828
+ needsRun: false,
2829
+ fallback: "mutations",
2830
+ usageLine: "mutations"
2786
2831
  },
2787
2832
  {
2788
- readonly: false,
2789
- usage: "restore",
2790
- summary: "从最近的快照恢复技能"
2833
+ id: "restore",
2834
+ words: ["restore"],
2835
+ summaryKey: "summary.restore",
2836
+ helpKey: "help.restore",
2837
+ flags: [],
2838
+ positional: [],
2839
+ readOnly: false,
2840
+ needsRun: false,
2841
+ fallback: "restore",
2842
+ usageLine: "restore"
2791
2843
  },
2792
2844
  {
2793
- readonly: false,
2794
- usage: "skill restore <name>",
2795
- summary: "按名字恢复一个已归档的技能"
2845
+ id: "skill.restore",
2846
+ words: ["skill", "restore"],
2847
+ summaryKey: "summary.skill restore",
2848
+ helpKey: "help.skill restore",
2849
+ flags: [],
2850
+ positional: [],
2851
+ readOnly: false,
2852
+ needsRun: false,
2853
+ fallback: "skill restore <name>",
2854
+ usageLine: "skill restore <name>"
2796
2855
  },
2797
2856
  {
2798
- readonly: true,
2799
- usage: "skill history <name>",
2800
- summary: "列出某个技能的内容版本(含时间、动作、字符数、哈希前缀)"
2857
+ id: "skill.history",
2858
+ words: ["skill", "history"],
2859
+ summaryKey: "summary.skill history",
2860
+ helpKey: "help.skill history",
2861
+ flags: [],
2862
+ positional: [],
2863
+ readOnly: true,
2864
+ needsRun: false,
2865
+ fallback: "skill history <name>",
2866
+ usageLine: "skill history <name>"
2801
2867
  },
2802
2868
  {
2803
- readonly: false,
2804
- usage: "skill undo <name> [--to v<N>]",
2805
- summary: "把某个技能的内容回退到某一版(默认上一版;只动内容,撤销本身也记为一版)"
2869
+ id: "skill.undo",
2870
+ words: ["skill", "undo"],
2871
+ summaryKey: "summary.skill undo",
2872
+ helpKey: "help.skill undo",
2873
+ flags: [{
2874
+ name: "to",
2875
+ kind: "value"
2876
+ }],
2877
+ positional: [],
2878
+ readOnly: false,
2879
+ needsRun: false,
2880
+ fallback: "skill undo <name> [--to v<N>]",
2881
+ usageLine: "skill undo <name> [--to v<N>]"
2806
2882
  },
2807
2883
  {
2808
- readonly: false,
2809
- usage: "skill pin <name>",
2810
- summary: "钉住一个技能:免于删除、后台审查与生命周期整理(立即生效、随时可解钉;与 skill_manage 的 pin 动作同一语义,不走审批)"
2884
+ id: "skill.pin",
2885
+ words: ["skill", "pin"],
2886
+ summaryKey: "summary.skill pin",
2887
+ helpKey: "help.skill pin",
2888
+ flags: [],
2889
+ positional: [],
2890
+ readOnly: false,
2891
+ needsRun: false,
2892
+ fallback: "skill pin <name>",
2893
+ usageLine: "skill pin <name>"
2811
2894
  },
2812
2895
  {
2813
- readonly: false,
2814
- usage: "skill unpin <name>",
2815
- summary: "解钉一个技能:撤销上面的冻结(立即生效、不走审批)"
2896
+ id: "skill.unpin",
2897
+ words: ["skill", "unpin"],
2898
+ summaryKey: "summary.skill unpin",
2899
+ helpKey: "help.skill unpin",
2900
+ flags: [],
2901
+ positional: [],
2902
+ readOnly: false,
2903
+ needsRun: false,
2904
+ fallback: "skill unpin <name>",
2905
+ usageLine: "skill unpin <name>"
2816
2906
  },
2817
2907
  {
2818
- readonly: false,
2819
- usage: "propose",
2820
- summary: "为 body-oversize 技能写 keep 提议(不自动拆分;同一 reports store)"
2908
+ id: "propose",
2909
+ words: ["propose"],
2910
+ summaryKey: "summary.propose",
2911
+ helpKey: "help.propose",
2912
+ flags: [],
2913
+ positional: [],
2914
+ readOnly: false,
2915
+ needsRun: false,
2916
+ fallback: "propose",
2917
+ usageLine: "propose"
2821
2918
  },
2822
2919
  {
2823
- readonly: true,
2824
- usage: "skills health",
2825
- summary: "技能库结构体检"
2920
+ id: "skills.health",
2921
+ words: ["skills", "health"],
2922
+ summaryKey: "summary.skills health",
2923
+ helpKey: "help.skills health",
2924
+ flags: [],
2925
+ positional: [],
2926
+ readOnly: true,
2927
+ needsRun: false,
2928
+ fallback: "skills health",
2929
+ usageLine: "skills health"
2826
2930
  },
2827
2931
  {
2828
- readonly: false,
2829
- usage: "skills refresh",
2830
- summary: "丢弃目录缓存并重新读取技能树"
2932
+ id: "skills.refresh",
2933
+ words: ["skills", "refresh"],
2934
+ summaryKey: "summary.skills refresh",
2935
+ helpKey: "help.skills refresh",
2936
+ flags: [],
2937
+ positional: [],
2938
+ readOnly: false,
2939
+ needsRun: false,
2940
+ fallback: "skills refresh",
2941
+ usageLine: "skills refresh"
2831
2942
  },
2832
2943
  {
2833
- readonly: false,
2834
- usage: "learn [request]",
2835
- summary: "向本会话发一条学习请求"
2944
+ id: "learn",
2945
+ words: ["learn"],
2946
+ summaryKey: "summary.learn",
2947
+ helpKey: "help.learn",
2948
+ flags: [],
2949
+ positional: [],
2950
+ readOnly: false,
2951
+ needsRun: false,
2952
+ fallback: "learn [request]",
2953
+ usageLine: "learn [request]"
2836
2954
  },
2837
2955
  {
2838
- readonly: false,
2839
- usage: "maintain [--timeout=<ms> | --facts]",
2840
- summary: "起一次维护扫描并立即回 run id(后台跑;--facts 为 0 token 预览)"
2956
+ id: "maintain",
2957
+ words: ["maintain"],
2958
+ summaryKey: "summary.maintain",
2959
+ helpKey: "help.maintain",
2960
+ flags: [{
2961
+ name: "timeout",
2962
+ kind: "value"
2963
+ }, {
2964
+ name: "facts",
2965
+ kind: "boolean"
2966
+ }],
2967
+ positional: [],
2968
+ readOnly: false,
2969
+ needsRun: false,
2970
+ fallback: "maintain [--timeout=<ms> | --facts]",
2971
+ usageLine: "maintain [--timeout=<ms> | --facts]"
2841
2972
  },
2842
2973
  {
2843
- readonly: true,
2844
- usage: "maintain status [<id>]",
2845
- summary: "看维护扫描:在飞的那次(含已跑多久)或某个 run 的终态"
2974
+ id: "maintain.status",
2975
+ words: ["maintain", "status"],
2976
+ summaryKey: "summary.maintain status",
2977
+ helpKey: "help.maintain status",
2978
+ flags: [],
2979
+ positional: [],
2980
+ readOnly: true,
2981
+ needsRun: false,
2982
+ fallback: "maintain status [<id>]",
2983
+ usageLine: "maintain status [<id>]"
2846
2984
  },
2847
2985
  {
2848
- readonly: true,
2849
- usage: "maintain report [<id>]",
2850
- summary: "读某个 run 的结果正文(省略 id 取本 home 最新一条;没有结果就明说,不装成空结果)"
2986
+ id: "maintain.report",
2987
+ words: ["maintain", "report"],
2988
+ summaryKey: "summary.maintain report",
2989
+ helpKey: "help.maintain report",
2990
+ flags: [],
2991
+ positional: [],
2992
+ readOnly: true,
2993
+ needsRun: false,
2994
+ fallback: "maintain report [<id>]",
2995
+ usageLine: "maintain report [<id>]"
2851
2996
  },
2852
2997
  {
2853
- readonly: false,
2854
- usage: "maintain handoff [<id>]",
2855
- summary: "把某次维护报告交给模型:注入指针与汇报协议,模型只汇报、等你确认后再动手"
2998
+ id: "maintain.handoff",
2999
+ words: ["maintain", "handoff"],
3000
+ summaryKey: "summary.maintain handoff",
3001
+ helpKey: "help.maintain handoff",
3002
+ flags: [],
3003
+ positional: [],
3004
+ readOnly: false,
3005
+ needsRun: false,
3006
+ fallback: "maintain handoff [<id>]",
3007
+ usageLine: "maintain handoff [<id>]"
2856
3008
  },
2857
3009
  {
2858
- readonly: false,
2859
- usage: "maintain cancel [<id>]",
2860
- summary: "停掉在飞的那次维护扫描(省略 id 仅当最新一条是本进程在跑的那次)"
3010
+ id: "maintain.cancel",
3011
+ words: ["maintain", "cancel"],
3012
+ summaryKey: "summary.maintain cancel",
3013
+ helpKey: "help.maintain cancel",
3014
+ flags: [],
3015
+ positional: [],
3016
+ readOnly: false,
3017
+ needsRun: false,
3018
+ fallback: "maintain cancel [<id>]",
3019
+ usageLine: "maintain cancel [<id>]"
2861
3020
  },
2862
3021
  {
2863
- readonly: true,
2864
- usage: "params [--group <name>] [--json]",
2865
- summary: "列出全部参数:分组、档位、生效时机、来源与当前值(--json 便于脚本处理)"
3022
+ id: "params",
3023
+ words: ["params"],
3024
+ summaryKey: "summary.params",
3025
+ helpKey: "help.params",
3026
+ flags: [{
3027
+ name: "group",
3028
+ kind: "value"
3029
+ }, {
3030
+ name: "json",
3031
+ kind: "boolean"
3032
+ }],
3033
+ positional: [],
3034
+ readOnly: true,
3035
+ needsRun: false,
3036
+ fallback: "params [--group <name>] [--json]",
3037
+ usageLine: "params [--group <name>] [--json]"
2866
3038
  },
2867
3039
  {
2868
- readonly: false,
2869
- usage: "restructure <name> \"<heading>\" <to_file> [--plan <runId>]",
2870
- summary: "把技能正文的一节移到 references 文件"
3040
+ id: "restructure",
3041
+ words: ["restructure"],
3042
+ summaryKey: "summary.restructure",
3043
+ helpKey: "help.restructure",
3044
+ flags: [{
3045
+ name: "plan",
3046
+ kind: "value"
3047
+ }],
3048
+ positional: [],
3049
+ readOnly: false,
3050
+ needsRun: false,
3051
+ fallback: "restructure <name> \"<heading>\" <to_file> [--plan <runId>]",
3052
+ usageLine: "restructure <name> \"<heading>\" <to_file> [--plan <runId>]"
2871
3053
  },
2872
3054
  {
2873
- readonly: false,
2874
- usage: "extract <source> <target> \"<heading>\" [--start <line>] [--end <line>] [--outcome extract|mixed] [--proposal <id>] [--owner-covers] [--apply]",
2875
- summary: "预览把源技能的可复用部分提取到已有类级 owner;默认 plan,--apply 才写(多根一次事务)"
3055
+ id: "extract",
3056
+ words: ["extract"],
3057
+ summaryKey: "summary.extract",
3058
+ helpKey: "help.extract",
3059
+ flags: [
3060
+ {
3061
+ name: "start",
3062
+ kind: "value"
3063
+ },
3064
+ {
3065
+ name: "end",
3066
+ kind: "value"
3067
+ },
3068
+ {
3069
+ name: "outcome",
3070
+ kind: "value"
3071
+ },
3072
+ {
3073
+ name: "proposal",
3074
+ kind: "value"
3075
+ },
3076
+ {
3077
+ name: "owner-covers",
3078
+ kind: "boolean"
3079
+ },
3080
+ {
3081
+ name: "apply",
3082
+ kind: "boolean"
3083
+ }
3084
+ ],
3085
+ positional: [],
3086
+ readOnly: false,
3087
+ needsRun: false,
3088
+ fallback: "extract <source> <target> \"<heading>\" [--start <line>] [--end <line>] [--outcome extract|mixed] [--proposal <id>] [--owner-covers] [--apply]",
3089
+ usageLine: "extract <source> <target> \"<heading>\" [--start <line>] [--end <line>] [--outcome extract|mixed] [--proposal <id>] [--owner-covers] [--apply]"
2876
3090
  },
2877
3091
  {
2878
- readonly: true,
2879
- usage: "replay",
2880
- summary: "比较不同会话与重启之间的计划结果(从活动记录回填)"
3092
+ id: "replay",
3093
+ words: ["replay"],
3094
+ summaryKey: "summary.replay",
3095
+ helpKey: "help.replay",
3096
+ flags: [],
3097
+ positional: [],
3098
+ readOnly: true,
3099
+ needsRun: false,
3100
+ fallback: "replay",
3101
+ usageLine: "replay"
2881
3102
  }
2882
3103
  ];
3104
+ //#endregion
3105
+ //#region lib/types/registry.js
3106
+ /**
3107
+ * Command surface rendering. HOST_COMMAND_DEFS is the one table; every renderer here reads it.
3108
+ * Keep `usageLine` in the exact shape a user can type after `/evolution`.
3109
+ */
3110
+ /** The flags the TABLE declares for one subcommand (name → `--flag`). */
3111
+ function flagsOf(name) {
3112
+ return HOST_COMMAND_DEFS.find((candidate) => entryName(candidate) === name)?.flags.map((flag) => "--" + flag.name) ?? [];
3113
+ }
3114
+ /**
3115
+ * C7 shape, DERIVED: the entry IDENTITY key, and it is HIERARCHICAL (E-08).
3116
+ *
3117
+ * The key used to be the first token alone, and `flagsOf` finds an entry with `.find(...)` - the FIRST
3118
+ * match - so `maintain handoff` / `maintain cancel` and `skill restore` / `skill history` / `skill undo` /
3119
+ * `skill pin` all derived the SAME key as their parent and every flag lookup silently saw the parent entry
3120
+ * only (nine collisions). A bare parent (`maintain [--timeout]`) keeps its one-token key, so parent lookups
3121
+ * still resolve: the one call site that named an entry by a name the key no longer produced was the preset
3122
+ * dispatch branch, and it now asks for the entry own key (`preset install`).
3123
+ */
3124
+ function entryName(entry) {
3125
+ return entry.words.join(" ");
3126
+ }
3127
+ /** The one summary source: the generated command i18n catalog. */
3128
+ function summaryOf(entry, locale = "zh") {
3129
+ const text = HOST_COMMANDS["summary." + entryName(entry)]?.[locale];
3130
+ if (text === void 0) throw new Error("registry: no generated summary for " + entryName(entry) + " (" + locale + ")");
3131
+ return text;
3132
+ }
2883
3133
  /** The input-declaration hint (single line, ` | `-separated). */
2884
3134
  function renderHint() {
2885
- return COMMAND_ENTRIES.map((entry) => entry.usage).join(" | ");
3135
+ return HOST_COMMAND_DEFS.map((entry) => entry.usageLine).join(" | ");
2886
3136
  }
2887
3137
  /** The bare `/evolution` help body (one line per subcommand). */
2888
3138
  function renderHelpText(locale = "zh") {
2889
3139
  return [
2890
- (HOST_COMMANDS["help.subcommands"][locale] ?? HOST_COMMANDS["help.subcommands"].en).replace("{count}", String(COMMAND_ENTRIES.length)),
3140
+ (HOST_COMMANDS["help.subcommands"][locale] ?? HOST_COMMANDS["help.subcommands"].en).replace("{count}", String(HOST_COMMAND_DEFS.length)),
2891
3141
  "",
2892
- ...COMMAND_ENTRIES.map((entry) => ` ${entry.usage.padEnd(44)} ${HOST_COMMANDS["summary." + entryName(entry)]?.[locale] ?? entry.summary}`)
3142
+ ...HOST_COMMAND_DEFS.map((entry) => ` ${entry.usageLine.padEnd(44)} ${summaryOf(entry, locale)}`)
2893
3143
  ].join("\n");
2894
3144
  }
2895
- /**
2896
- * The flags whose declared form takes a value, DERIVED from the usage text: a flag followed by
2897
- * `=` or by a placeholder token (not another flag/bracket) is a value flag. Boolean flags stay
2898
- * out. The parser imports this, so `--proposal p1` cannot be read as a bare boolean again.
2899
- */
2900
- function entryValueFlags(entry) {
2901
- const found = [];
2902
- const tokens = entry.usage.split(/\s+/);
2903
- for (let index = 0; index < tokens.length; index += 1) {
2904
- const token = (tokens[index] ?? "").replace(/^\[+/, "").replace(/\]+$/, "");
2905
- if (!token.startsWith("--")) continue;
2906
- const name = token.slice(2).split("=")[0] ?? "";
2907
- if (name === "") continue;
2908
- if (token.includes("=")) {
2909
- if (!found.includes(name)) found.push(name);
2910
- continue;
2911
- }
2912
- const next = (tokens[index + 1] ?? "").replace(/^\[+/, "");
2913
- if (next !== "" && !next.startsWith("--") && next !== "]" && next !== "|") {
2914
- if (!found.includes(name)) found.push(name);
2915
- }
2916
- }
2917
- return found;
2918
- }
2919
- /** Union of every usage's value flags (the parse table's ONE source). */
3145
+ /** Union of every entry's authored value flags. */
2920
3146
  const VALUE_FLAGS = (() => {
2921
3147
  const names = [];
2922
- for (const entry of COMMAND_ENTRIES) for (const name of entryValueFlags(entry)) if (!names.includes(name)) names.push(name);
3148
+ for (const entry of HOST_COMMAND_DEFS) for (const flag of entry.flags) if (flag.kind === "value" && !names.includes(flag.name)) names.push(flag.name);
2923
3149
  return names;
2924
3150
  })();
2925
3151
  //#endregion
2926
3152
  //#region lib/types/parse.js
2927
3153
  /**
3154
+ * F-4/G7.4 (C7): the ONE parser for the /evolution command surface.
3155
+ *
3156
+ * The surface used to answer each subcommand with its own regex (`^params(?: --group ([a-z-]+))?(?: --json)?$`
3157
+ * and nine siblings), so `params --json --group review` and `params --group=review` were refused as
3158
+ * "not a subcommand", while a sibling regex accepted `=` — and a mistyped group name degraded into the
3159
+ * generic error instead of the one that lists the known groups.
3160
+ *
3161
+ * This parser is order- and `=`-tolerant, matches the subcommand name case-insensitively, keeps a flag
3162
+ * VALUE's case intact (the domain layer is the one that validates it), and answers a SYNTAX failure when a
3163
+ * declared value flag is left without its value (F-3: `extract --start 3` must not read
3164
+ * `--expect 3` as the value).
3165
+ *
3166
+ * @module @lmzhen/dsh-evolution-commands/parse
3167
+ */
3168
+ /** The flags whose declared form takes a value, authored in the command table. */
3169
+ /**
2928
3170
  * Narrow a parse result: true when it is the syntax failure rather than a command.
2929
3171
  * @param result - what {@link parseSubcommand} answered.
2930
3172
  * @returns whether the line was refused.
@@ -2961,25 +3203,6 @@ function tokenize(input) {
2961
3203
  return tokens;
2962
3204
  }
2963
3205
  /**
2964
- * Read one SUB-FORM line: `maintain status`, `maintain report`, … — the shape the regexes used to own.
2965
- *
2966
- * A sub-form matches only when: the line parses, the name matches, the first positional is the sub-form,
2967
- * and every flag the line carries is DECLARED by the table (an undeclared flag keeps the old
2968
- * "unknown arguments" answer instead of silently becoming a bare flag).
2969
- * @param input - the text after `/evolution`.
2970
- * @param name - the subcommand name the table declares (e.g. `maintain`).
2971
- * @param sub - the sub-form word (e.g. `status`).
2972
- * @param declaredFlags - the flags the table declares for `name` (`flagsOf(name)`).
2973
- * @returns the parsed command, or null when this line is not that sub-form.
2974
- */
2975
- function subcommandOf(input, name, sub, declaredFlags) {
2976
- const parsed = parseSubcommand(input);
2977
- if (isParseFailure(parsed) || parsed.name !== name) return null;
2978
- if (parsed.positionals[0] !== sub) return null;
2979
- for (const flag of parsed.flags.keys()) if (!declaredFlags.includes("--" + flag)) return null;
2980
- return parsed;
2981
- }
2982
- /**
2983
3206
  * Parse one command line into its name, flags and positionals.
2984
3207
  * @param input - the text after `/evolution`.
2985
3208
  * @returns the parsed command, or the syntax failure that refused it.
@@ -3057,23 +3280,26 @@ function buildSurface(defs, prefix) {
3057
3280
  };
3058
3281
  }
3059
3282
  function parseCommand(defs, argv) {
3060
- const [verb, ...rest] = argv;
3283
+ const verb = argv[0];
3061
3284
  if (verb === void 0 || verb === "help" || verb === "--help" || verb === "-h") return {
3062
3285
  ok: true,
3063
3286
  id: "help",
3064
3287
  values: {},
3065
3288
  help: true
3066
3289
  };
3067
- const candidates = defs.filter((item) => item.words.includes(verb));
3068
- const def = candidates.find((item) => rest.filter((token) => token.startsWith("--")).every((token) => {
3290
+ const candidates = defs.filter((item) => item.words.length > 0 && item.words.every((word, index) => argv[index] === word));
3291
+ const restOf = (item) => argv.slice(item.words.length);
3292
+ const ordered = [...candidates].sort((left, right) => right.words.length - left.words.length);
3293
+ const def = ordered.find((item) => restOf(item).filter((token) => token.startsWith("--")).every((token) => {
3069
3294
  const name = token.slice(2).split("=")[0] ?? "";
3070
3295
  return item.flags.some((flag) => flag.name === name);
3071
- })) ?? candidates[0];
3296
+ })) ?? ordered[0];
3072
3297
  if (def === void 0) return {
3073
3298
  ok: false,
3074
3299
  code: "usage",
3075
3300
  message: "unknown command: " + verb
3076
3301
  };
3302
+ const rest = restOf(def);
3077
3303
  const values = {};
3078
3304
  const positional = [];
3079
3305
  for (let index = 0; index < rest.length; index += 1) {
@@ -3389,15 +3615,15 @@ function apply(ctx, rawConfig = {}) {
3389
3615
  return err(hostError("e-306-this-deployment-stages-foreground", { a1: what }));
3390
3616
  };
3391
3617
  const approval = ctx.get("evolutionApproval");
3392
- const pendingParsed = parseSubcommand(input);
3393
- if (!isParseFailure(pendingParsed) && pendingParsed.name === "pending" && pendingParsed.positionals.length === 0 && [...pendingParsed.flags.keys()].every((flag) => flag === "detail")) {
3618
+ const command = parseSubcommand(input);
3619
+ if (!isParseFailure(command) && command.name === "pending" && command.positionals.length === 0 && [...command.flags.keys()].every((flag) => flag === "detail")) {
3394
3620
  if (!approval) return err(hostError("e-301-approval-service-not-mounted"));
3395
3621
  const listed = [...await approval.list("pending"), ...await approval.list("executing")];
3396
3622
  const pending = [...new Map(listed.map((row) => [row.id, row])).values()];
3397
3623
  const ttlMs = typeof approval.ttlMs === "number" && Number.isFinite(approval.ttlMs) ? approval.ttlMs : 0;
3398
3624
  const ttlNote = ttlMs > 0 ? hostCommandText(hostLocale, "command.pending.ttl", { ttl: ttlMs }) : hostCommandText(hostLocale, "command.pending.neverExpires");
3399
3625
  if (pending.length === 0) return ok(hostCommandText(hostLocale, "command.pending.empty") + ttlNote);
3400
- const detailed = pendingParsed.flags.get("detail") === true;
3626
+ const detailed = command.flags.get("detail") === true;
3401
3627
  const nowMs = Date.now();
3402
3628
  const attribution = (p) => {
3403
3629
  const age = elapsedSince(p.createdAt, nowMs);
@@ -3663,8 +3889,7 @@ function apply(ctx, rawConfig = {}) {
3663
3889
  });
3664
3890
  return woke ? ok("已向本会话发送学习请求,请现在执行。") : ok("学习请求已排入本会话队列:本宿主没有唤醒通道,会在你下一条消息时读取。");
3665
3891
  }
3666
- const factsParsed = parseSubcommand(input);
3667
- if (!isParseFailure(factsParsed) && factsParsed.name === "maintain" && factsParsed.flags.get("facts") === true && factsParsed.positionals.length === 0) {
3892
+ if (!isParseFailure(command) && command.name === "maintain" && command.flags.get("facts") === true && command.positionals.length === 0) {
3668
3893
  const ioRegistry = ctx.get("evolutionIo");
3669
3894
  if (!ioRegistry) return err("未挂载 evolution-io 注册表:维护事实不可用。");
3670
3895
  const library = newSkillLibrary({
@@ -3688,10 +3913,9 @@ function apply(ctx, rawConfig = {}) {
3688
3913
  const { facts } = buildMaintainFacts(snapshots, enrichment.usageObservedValue, void 0);
3689
3914
  return ok(`维护事实(零 token 预览):\n${facts}`);
3690
3915
  }
3691
- const maintainParsed = parseSubcommand(input);
3692
- const maintainFlagsDeclared = [...isParseFailure(maintainParsed) ? [] : maintainParsed.flags.keys()].every((flag) => flagsOf("maintain").includes("--" + flag));
3693
- if (!isParseFailure(maintainParsed) && maintainParsed.name === "maintain" && maintainParsed.positionals.length === 0 && maintainFlagsDeclared) {
3694
- const timeoutFlag = maintainParsed.flags.get("timeout");
3916
+ const maintainFlagsDeclared = [...isParseFailure(command) ? [] : command.flags.keys()].every((flag) => flagsOf("maintain").includes("--" + flag));
3917
+ if (!isParseFailure(command) && command.name === "maintain" && command.positionals.length === 0 && maintainFlagsDeclared) {
3918
+ const timeoutFlag = command.flags.get("timeout");
3695
3919
  const runTimeoutMs = typeof timeoutFlag === "string" ? Number(timeoutFlag) : config.maintainTimeoutMs ?? 6e5;
3696
3920
  if (!Number.isSafeInteger(runTimeoutMs) || runTimeoutMs <= 0 || runTimeoutMs > MAX_TIMER_DELAY_MS) return err(timeoutFlag !== void 0 ? `--timeout 值不合法:应为不超过 ${MAX_TIMER_DELAY_MS} 的正整数毫秒(例如 /evolution maintain --timeout 600000)。` : `maintainTimeoutMs 配置不合法:应为不超过 ${MAX_TIMER_DELAY_MS} 的正整数毫秒。请修正 evolution-commands 行的配置(maintainTimeoutMs)后重试。`);
3697
3921
  const registry = runs;
@@ -3833,7 +4057,11 @@ function apply(ctx, rawConfig = {}) {
3833
4057
  `- stop: /evolution maintain cancel ${handle.id}`
3834
4058
  ].join("\n"));
3835
4059
  }
3836
- const maintainStatus = subcommandOf(input, "maintain", "status", flagsOf("maintain"));
4060
+ const maintainSub = (sub) => {
4061
+ if (isParseFailure(command) || command.name !== "maintain" || command.positionals[0] !== sub) return null;
4062
+ return [...command.flags.keys()].every((flag) => flagsOf("maintain").includes("--" + flag)) ? command : null;
4063
+ };
4064
+ const maintainStatus = maintainSub("status");
3837
4065
  if (maintainStatus !== null) {
3838
4066
  const registry = runs;
3839
4067
  if (!registry) return err("未挂载 evolution-io 注册表:无法查看运行状态。");
@@ -3854,7 +4082,7 @@ function apply(ctx, rawConfig = {}) {
3854
4082
  const recent = all.filter((record) => record.state !== "running").slice(0, 5);
3855
4083
  return ok([live.length === 0 ? "No maintenance run in flight." : `In flight:\n${live.map(renderRunRecord).join("\n")}`, recent.length === 0 ? "" : `Recent:\n${recent.map(renderRunRecord).join("\n")}`].filter((part) => part !== "").join("\n"));
3856
4084
  }
3857
- const maintainReport = subcommandOf(input, "maintain", "report", flagsOf("maintain"));
4085
+ const maintainReport = maintainSub("report");
3858
4086
  if (maintainReport !== null) {
3859
4087
  const registry = runs;
3860
4088
  if (!registry) return err("未挂载 evolution-io 注册表:无法查看运行结果。");
@@ -3877,7 +4105,7 @@ function apply(ctx, rawConfig = {}) {
3877
4105
  if (probed.kind === "unknown") return err(`运行 ${record.id} 有报告但读不出来(${probed.reason}):这「不是」没有结果。`);
3878
4106
  return ok(probed.text);
3879
4107
  }
3880
- const maintainCancel = subcommandOf(input, "maintain", "cancel", flagsOf("maintain"));
4108
+ const maintainCancel = maintainSub("cancel");
3881
4109
  if (maintainCancel !== null) {
3882
4110
  const registry = runs;
3883
4111
  if (!registry) return err("未挂载 evolution-io 注册表:无法取消运行。");
@@ -3899,7 +4127,7 @@ function apply(ctx, rawConfig = {}) {
3899
4127
  }
3900
4128
  return ok(`维护运行 ${record.id} 已取消:扫描会在下一个检查点停止。用 /evolution maintain status ${record.id} 查看终态。`);
3901
4129
  }
3902
- const maintainHandoff = subcommandOf(input, "maintain", "handoff", flagsOf("maintain"));
4130
+ const maintainHandoff = maintainSub("handoff");
3903
4131
  if (maintainHandoff !== null) {
3904
4132
  const registry = runs;
3905
4133
  if (!registry) return err("未挂载 evolution-io 注册表:无法交付报告。");
@@ -3944,14 +4172,13 @@ function apply(ctx, rawConfig = {}) {
3944
4172
  }
3945
4173
  if (/^maintain\b/.test(input)) return err("未知的 maintain 参数:应为 `maintain`、`maintain --timeout <ms>` / `maintain --timeout=<ms>`、`maintain status [<id>]`、`maintain report [<id>]`、`maintain handoff [<id>]` 或 `maintain cancel [<id>]`。实际收到:" + input);
3946
4174
  if (input.startsWith("extract ")) {
3947
- const extractParsed = parseSubcommand(rawInputTrimmed);
3948
- if (isParseFailure(extractParsed) || extractParsed.name !== "extract") return err("用法:/evolution extract <source> <target> \"<heading>\" [--start <line>] [--end <line>] [--owner-covers] 或 --proposal <id>");
3949
- const source = extractParsed.positionals[0] ?? "";
3950
- const proposalFlag = extractParsed.flags.get("proposal");
4175
+ if (isParseFailure(command) || command.name !== "extract") return err("用法:/evolution extract <source> <target> \"<heading>\" [--start <line>] [--end <line>] [--owner-covers] 或 --proposal <id>");
4176
+ const source = command.positionals[0] ?? "";
4177
+ const proposalFlag = command.flags.get("proposal");
3951
4178
  const ioRegistry = ctx.get("evolutionIo");
3952
4179
  if (!ioRegistry) return err("未挂载 evolution-io 注册表:无法执行 extract。");
3953
- let target = extractParsed.positionals[1] ?? "";
3954
- let heading = extractParsed.positionals[2] ?? "";
4180
+ let target = command.positionals[1] ?? "";
4181
+ let heading = command.positionals[2] ?? "";
3955
4182
  let start;
3956
4183
  let end;
3957
4184
  let extractItems = [];
@@ -3973,8 +4200,8 @@ function apply(ctx, rawConfig = {}) {
3973
4200
  }));
3974
4201
  } else {
3975
4202
  if (source === "" || target === "" || heading === "") return err("用法:/evolution extract <source> <target> \"<heading>\" [--start <line>] [--end <line>]");
3976
- const startFlag = extractParsed.flags.get("start");
3977
- const endFlag = extractParsed.flags.get("end");
4203
+ const startFlag = command.flags.get("start");
4204
+ const endFlag = command.flags.get("end");
3978
4205
  start = typeof startFlag === "string" ? startFlag : void 0;
3979
4206
  end = typeof endFlag === "string" ? endFlag : void 0;
3980
4207
  extractItems = [{
@@ -3984,8 +4211,8 @@ function apply(ctx, rawConfig = {}) {
3984
4211
  to_skill: target
3985
4212
  }];
3986
4213
  }
3987
- const ownerCovers = extractParsed.flags.has("owner-covers");
3988
- const outcomeFlag = extractParsed.flags.get("outcome");
4214
+ const ownerCovers = command.flags.has("owner-covers");
4215
+ const outcomeFlag = command.flags.get("outcome");
3989
4216
  if (outcomeFlag !== void 0 && outcomeFlag !== "extract" && outcomeFlag !== "mixed") return err("--outcome 只能是 extract 或 mixed。");
3990
4217
  const library = newSkillLibrary({
3991
4218
  authority: authorityFrom({ origin: "foreground" }),
@@ -4007,7 +4234,7 @@ function apply(ctx, rawConfig = {}) {
4007
4234
  if (!built.ok) return err(built.message);
4008
4235
  const plan = built.plan;
4009
4236
  const warnings = built.warnings === void 0 || built.warnings.length === 0 ? "" : "\n" + built.warnings.join("\n");
4010
- if (!extractParsed.flags.has("apply")) {
4237
+ if (!command.flags.has("apply")) {
4011
4238
  const proposal = proposalFromPlan(plan, { runId: "cli-" + Date.now().toString(36) });
4012
4239
  const proposalPath = await writeProposalReport(ioRegistry.provider(), proposal).catch(() => {});
4013
4240
  return ok("提取计划(未写入;默认 plan,--apply 才写):" + plan.parts.map((part) => "## " + part.heading).join(", ") + " -> " + target + "\n提取判定:outcome=" + plan.outcome + ";target=" + target + ";owner=" + ownerDecisionText(plan.owner) + warnings + "\nproposal_id: " + proposal.id + (proposalPath === void 0 ? "" : "(已写入 reports)"));
@@ -4044,13 +4271,12 @@ function apply(ctx, rawConfig = {}) {
4044
4271
  return ok(result.message + "\n提取判定:outcome=" + plan.outcome + ";target=" + target + warnings);
4045
4272
  }
4046
4273
  if (input.startsWith("restructure ")) {
4047
- const restParsed = parseSubcommand(rawInputTrimmed);
4048
- if (isParseFailure(restParsed) || restParsed.name !== "restructure") return err("用法:/evolution restructure <name> \"<heading>\" <to_file>");
4049
- const name = restParsed.positionals[0] ?? "";
4050
- const heading = restParsed.positionals[1] ?? "";
4051
- const toFile = restParsed.positionals[2] ?? "";
4274
+ if (isParseFailure(command) || command.name !== "restructure") return err("用法:/evolution restructure <name> \"<heading>\" <to_file>");
4275
+ const name = command.positionals[0] ?? "";
4276
+ const heading = command.positionals[1] ?? "";
4277
+ const toFile = command.positionals[2] ?? "";
4052
4278
  if (name === "" || heading === "" || toFile === "") return err("用法:/evolution restructure <name> \"<heading>\" <to_file>");
4053
- const planFlag = restParsed.flags.get("plan");
4279
+ const planFlag = command.flags.get("plan");
4054
4280
  const planRunId = typeof planFlag === "string" ? planFlag : void 0;
4055
4281
  if (!toFile.startsWith("references/")) return err("to_file 必须位于 references/ 之下(日志或明细的落地位置)。");
4056
4282
  const ioRegistry = ctx.get("evolutionIo");
@@ -4108,8 +4334,7 @@ function apply(ctx, rawConfig = {}) {
4108
4334
  if (!replay) return err(hostError("e-303-replay-service-not-mounted"));
4109
4335
  return ok(replay.compare().report);
4110
4336
  }
4111
- const paramsParsed = parseSubcommand(input);
4112
- if (!isParseFailure(paramsParsed) && paramsParsed.name === "params" && paramsParsed.positionals.length === 0 && [...paramsParsed.flags.keys()].every((flag) => flag === "group" || flag === "json")) {
4337
+ if (!isParseFailure(command) && command.name === "params" && command.positionals.length === 0 && [...command.flags.keys()].every((flag) => flag === "group" || flag === "json")) {
4113
4338
  const provider = ctx.get("settings");
4114
4339
  const sections = /* @__PURE__ */ new Map();
4115
4340
  if (provider?.describe !== void 0) try {
@@ -4124,14 +4349,14 @@ function apply(ctx, rawConfig = {}) {
4124
4349
  return err(hostError("e-307-the-settings-service-could", { a1: error instanceof Error ? error.message : String(error) }));
4125
4350
  }
4126
4351
  const rows = paramSurfaceRows(sections, PARAM_EXPOSURE);
4127
- const groupFlag = paramsParsed.flags.get("group");
4352
+ const groupFlag = command.flags.get("group");
4128
4353
  const group = typeof groupFlag === "string" ? groupFlag : void 0;
4129
4354
  const selected = group === void 0 ? rows : rows.filter((row) => row.group === group);
4130
4355
  if (group !== void 0 && selected.length === 0) return err(hostError("e-308-unknown-parameter-group-group", {
4131
4356
  a1: group,
4132
4357
  a2: paramGroups(PARAM_EXPOSURE).join(", ")
4133
4358
  }));
4134
- if (paramsParsed.flags.get("json") === true) return ok(renderParamJson(selected));
4359
+ if (command.flags.get("json") === true) return ok(renderParamJson(selected));
4135
4360
  return ok(renderParamRows(selected, { providerMounted: provider !== void 0 }));
4136
4361
  }
4137
4362
  if (input === "doctor" || input === "doctor --json") {
@@ -12,6 +12,15 @@ import type { Context } from '@deepseek-ai/cordis';
12
12
  import { type ChannelState, type DiagnosticsView } from '@lmzhen/dsh-evolution-core';
13
13
  /** The install form the running profile was classified as (the seven values DoctorReport uses). */
14
14
  export type InstallFormId = 'full' | 'human-gated' | 'preset' | 'host' | 'layered' | 'preset-only' | 'none';
15
+ /** The ONE install-form decision; callers only supply the facts their detection read. */
16
+ export declare function classifyInstallForm(input: {
17
+ readonly full: boolean;
18
+ readonly preset: boolean;
19
+ readonly host: boolean;
20
+ readonly humanGated: boolean;
21
+ readonly layeredPreset: boolean;
22
+ readonly presetDirInstalled: boolean;
23
+ }): InstallFormId;
15
24
  /** One preset's probe result (reviewer/maintainer). */
16
25
  export interface PresetFacts {
17
26
  readonly registered: boolean;
@@ -1,6 +1,7 @@
1
1
  import type { HostLocale } from '@lmzhen/dsh-evolution-core';
2
2
  import { type PlatformServiceProbe, type ScopedProbeReport } from '@lmzhen/dsh-evolution-core';
3
3
  import type { DiagnosticsView } from '@lmzhen/dsh-evolution-core';
4
+ import { type InstallFormId } from './doctor-view.ts';
4
5
  import type { MountedProfile } from './profiles.ts';
5
6
  /** P2-20 (audit): the TS-side copy of the install-target tails. The script
6
7
  * side (install-layered.mjs, verify-profile-bundles.mjs) imports the list
@@ -74,7 +75,7 @@ export interface DoctorReport {
74
75
  * per-session install reported `none` and the action ladder advised
75
76
  * installing `all` — which double-mounts the preset's model rows (the
76
77
  * exact conflict this report flags). */
77
- installForm: 'full' | 'human-gated' | 'host' | 'preset' | 'layered' | 'preset-only' | 'none';
78
+ installForm: InstallFormId;
78
79
  /** Aggregated across ALL profiles under `home` (N13, v12): doctor answers
79
80
  * "is any profile carrying an evolution bundle / which install forms exist"
80
81
  * — not "what this runtime mounted". `services.review` is the runtime-side
@@ -463,14 +463,14 @@ export declare const HOST_COMMANDS: {
463
463
  readonly pt: "atualizado — uma nova geração corresponde byte a byte a este arquivo";
464
464
  };
465
465
  readonly "doctor.presetDiffers": {
466
- readonly zh: "与最新生成不同 — 这是安装时快照;重新运行安装器(/evolution preset install)以重新生成";
467
- readonly en: "DIFFERS from a fresh generation — it is an install-time snapshot; re-run the installer (/evolution preset install) to regenerate";
468
- readonly ja: "最新の生成結果と異なります — インストール時のスナップショットです。インストーラー(/evolution preset install)を再実行して再生成してください";
469
- readonly es: "DIFIERE de una generación nueva — es una instantánea del momento de instalar; vuelve a ejecutar el instalador (/evolution preset install) para regenerarla";
470
- readonly fr: "DIFFÈRE d’une nouvelle génération — c’est un instantané de l’installation ; relancez l’installateur (/evolution preset install) pour la régénérer";
471
- readonly de: "WEICHT von einer neuen Erzeugung ab — es ist ein Installations-Snapshot; Installer erneut ausführen (/evolution preset install), um ihn neu zu erzeugen";
472
- readonly ru: "ОТЛИЧАЕТСЯ от новой генерации — это снимок на момент установки; запустите установщик повторно (/evolution preset install)";
473
- readonly pt: "DIFERE de uma nova geração — é um instantâneo do momento da instalação; execute o instalador novamente (/evolution preset install)";
466
+ readonly zh: "与最新生成不同 — 这是安装时快照;重新运行安装器(all/host)以重新生成";
467
+ readonly en: "DIFFERS from a fresh generation — it is an install-time snapshot; re-run the installer (all/host) to regenerate";
468
+ readonly ja: "最新の生成結果と異なります — インストール時のスナップショットです。インストーラー(all/host)を再実行して再生成してください";
469
+ readonly es: "DIFIERE de una generación nueva — es una instantánea del momento de instalar; vuelve a ejecutar el instalador (all/host) para regenerarla";
470
+ readonly fr: "DIFFÈRE d’une nouvelle génération — c’est un instantané de l’installation ; relancez l’installateur (all/host) pour la régénérer";
471
+ readonly de: "WEICHT von einer neuen Erzeugung ab — es ist ein Installations-Snapshot; Installer erneut ausführen (all/host), um ihn neu zu erzeugen";
472
+ readonly ru: "ОТЛИЧАЕТСЯ от новой генерации — это снимок на момент установки; запустите установщик повторно (all/host)";
473
+ readonly pt: "DIFERE de uma nova geração — é um instantâneo do momento da instalação; execute o instalador novamente (all/host)";
474
474
  };
475
475
  readonly "doctor.presetUnknown": {
476
476
  readonly zh: "未知 — 无法重新生成({detail})";
@@ -0,0 +1,7 @@
1
+ /** Typed host-command definitions: one source for help, surface and dispatch. */
2
+ import type { CommandDef } from './command-catalog.ts';
3
+ export interface HostCommandDef extends CommandDef {
4
+ readonly usageLine: string;
5
+ }
6
+ export declare const HOST_COMMAND_DEFS: readonly HostCommandDef[];
7
+ //# sourceMappingURL=host-command-defs.d.ts.map
@@ -55,31 +55,6 @@ export declare function paramGroups(entries?: readonly ParamExposure[]): string[
55
55
  export declare function renderParamRows(rows: readonly ParamSurfaceRow[], options: {
56
56
  providerMounted: boolean;
57
57
  }): string;
58
- /**
59
- * Parse one command-line value into what the settings document stores: JSON
60
- * when it parses (numbers, booleans, quoted strings, arrays, objects), the raw
61
- * text otherwise, so a bare word like `enforce` stays a word.
62
- * @param raw - the text typed after the parameter id.
63
- * @returns the value to write.
64
- */
65
- export declare function parseParamValue(raw: string): unknown;
66
- /** One accepted write, as the command echoes it back. */
67
- export interface ParamWriteEcho {
68
- id: string;
69
- namespace: string;
70
- applies: ParamExposure['applies'];
71
- before: unknown;
72
- after: unknown;
73
- /** Whether the user section already carried this key. */
74
- wasOverridden: boolean;
75
- }
76
- /**
77
- * Render the write result: the value move, then where it landed and when it
78
- * takes effect (the two things a caller cannot infer from the command line).
79
- * @param write - the accepted write.
80
- * @returns the command text.
81
- */
82
- export declare function renderPolicySet(write: ParamWriteEcho): string;
83
58
  /**
84
59
  * Render the rows as JSON for scripts (same fields, no formatting).
85
60
  * @param rows - rows from {@link paramSurfaceRows}.
@@ -13,8 +13,6 @@
13
13
  *
14
14
  * @module @lmzhen/dsh-evolution-commands/parse
15
15
  */
16
- /** The flags whose declared form takes a value, derived from the command table's usage lines. */
17
- export { VALUE_FLAGS } from './registry.ts';
18
16
  /** One parsed command line. */
19
17
  export interface ParsedCommand {
20
18
  /** The subcommand name, lower-cased (the table stores it lower-case too). */
@@ -39,19 +37,6 @@ export interface ParseFailure {
39
37
  * @returns whether the line was refused.
40
38
  */
41
39
  export declare function isParseFailure(result: ParsedCommand | ParseFailure): result is ParseFailure;
42
- /**
43
- * Read one SUB-FORM line: `maintain status`, `maintain report`, … — the shape the regexes used to own.
44
- *
45
- * A sub-form matches only when: the line parses, the name matches, the first positional is the sub-form,
46
- * and every flag the line carries is DECLARED by the table (an undeclared flag keeps the old
47
- * "unknown arguments" answer instead of silently becoming a bare flag).
48
- * @param input - the text after `/evolution`.
49
- * @param name - the subcommand name the table declares (e.g. `maintain`).
50
- * @param sub - the sub-form word (e.g. `status`).
51
- * @param declaredFlags - the flags the table declares for `name` (`flagsOf(name)`).
52
- * @returns the parsed command, or null when this line is not that sub-form.
53
- */
54
- export declare function subcommandOf(input: string, name: string, sub: string, declaredFlags: readonly string[]): ParsedCommand | null;
55
40
  /**
56
41
  * Parse one command line into its name, flags and positionals.
57
42
  * @param input - the text after `/evolution`.
@@ -1,13 +1,7 @@
1
1
  import type { HostLocale } from '@lmzhen/dsh-evolution-core';
2
- export interface CommandEntry {
3
- /** The subcommand as typed after `/evolution`. Variants use `|` (curator run|pause). */
4
- usage: string;
5
- /** C7: true when the subcommand only READS (no skill/param write). Stored: not derivable. */
6
- readonly: boolean;
7
- /** One-line purpose rendered in the help output. */
8
- summary: string;
9
- }
10
- /** The flags the TABLE declares for one subcommand (name → `--flag`), DERIVED from its usage. */
2
+ import { type HostCommandDef } from './host-command-defs.ts';
3
+ export { HOST_COMMAND_DEFS } from './host-command-defs.ts';
4
+ /** The flags the TABLE declares for one subcommand (name → `--flag`). */
11
5
  export declare function flagsOf(name: string): string[];
12
6
  /**
13
7
  * C7 shape, DERIVED: the entry IDENTITY key, and it is HIERARCHICAL (E-08).
@@ -19,10 +13,9 @@ export declare function flagsOf(name: string): string[];
19
13
  * still resolve: the one call site that named an entry by a name the key no longer produced was the preset
20
14
  * dispatch branch, and it now asks for the entry own key (`preset install`).
21
15
  */
22
- export declare function entryName(entry: CommandEntry): string;
23
- /** C7 shape, DERIVED: the flags a `usage` declares, in the form `--flag` (value flags keep their name). */
24
- export declare function entryFlags(entry: CommandEntry): string[];
25
- export declare const COMMAND_ENTRIES: CommandEntry[];
16
+ export declare function entryName(entry: HostCommandDef): string;
17
+ /** The one summary source: the generated command i18n catalog. */
18
+ export declare function summaryOf(entry: HostCommandDef, locale?: HostLocale): string;
26
19
  /** The input-declaration hint (single line, ` | `-separated). */
27
20
  export declare function renderHint(): string;
28
21
  /** The bare `/evolution` help body (one line per subcommand). */
@@ -30,12 +23,6 @@ export declare function renderHelpText(locale?: HostLocale): string;
30
23
  /** Markdown command table fragment for README surfaces (T-WD2 pins it).
31
24
  * `|` inside a usage (curator run|pause|…) is escaped for the table cell. */
32
25
  export declare function renderCommandTable(): string;
33
- /**
34
- * The flags whose declared form takes a value, DERIVED from the usage text: a flag followed by
35
- * `=` or by a placeholder token (not another flag/bracket) is a value flag. Boolean flags stay
36
- * out. The parser imports this, so `--proposal p1` cannot be read as a bare boolean again.
37
- */
38
- export declare function entryValueFlags(entry: CommandEntry): string[];
39
- /** Union of every usage's value flags (the parse table's ONE source). */
26
+ /** Union of every entry's authored value flags. */
40
27
  export declare const VALUE_FLAGS: readonly string[];
41
28
  //# sourceMappingURL=registry.d.ts.map
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.47.0",
4
+ "version": "0.48.0",
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.47.0",
33
- "@lmzhen/dsh-evolution-core": "^0.47.0",
34
- "@lmzhen/dsh-evolution-maintenance": "^0.47.0",
35
- "@lmzhen/dsh-evolution-state": "^0.47.0"
32
+ "@lmzhen/dsh-evolution-approval": "^0.48.0",
33
+ "@lmzhen/dsh-evolution-core": "^0.48.0",
34
+ "@lmzhen/dsh-evolution-maintenance": "^0.48.0",
35
+ "@lmzhen/dsh-evolution-state": "^0.48.0"
36
36
  },
37
37
  "optionalDependencies": {
38
- "@lmzhen/dsh-evolution-agent-preset": "^0.47.0"
38
+ "@lmzhen/dsh-evolution-agent-preset": "^0.48.0"
39
39
  },
40
40
  "peerDependencies": {
41
41
  "@deepseek-ai/cordis": "^4.0.5",