@lmzhen/dsh-evolution-commands 0.47.0 → 0.49.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
@@ -7,10 +7,10 @@ import { fileURLToPath } from "node:url";
7
7
  import z from "@deepseek-ai/schemastery";
8
8
  import { effectiveSessionPolicy } from "@lmzhen/dsh-evolution-approval";
9
9
  import { createUserMessage } from "@lmzhen/dsh-evolution-core/platform";
10
- import { assertSkillsRootAliasRetired, elapsedSince, newSkillLibrary, partitionVersions, resolveRootConfig } from "@lmzhen/dsh-evolution-core/skills";
11
10
  import { buildEnrichment, buildMaintainFacts, enrichmentSnapshotOptions, runMaintain, snapshotFromLibrary } from "@lmzhen/dsh-evolution-maintenance";
12
11
  import { composePresetEntry, presetRowBlock, presetRowBody, presetRowId, resolveBasePresetPatch } from "@lmzhen/dsh-evolution-core/composition";
13
12
  import { processScopeViolations } from "@lmzhen/dsh-evolution-state";
13
+ import { assertSkillsRootAliasRetired, elapsedSince, newSkillLibrary, partitionVersions, resolveRootConfig } from "@lmzhen/dsh-evolution-core/skills";
14
14
  //#region lib/types/command-fallback.js
15
15
  /**
16
16
  * G6/W8: the command-face fallback for every Host data-plane surface.
@@ -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"
@@ -630,6 +644,177 @@ async function withBudget(pending, timeoutMs, fallback) {
630
644
  }
631
645
  }
632
646
  //#endregion
647
+ //#region lib/types/migration.js
648
+ /**
649
+ * G3 (caller half): find the legacy settings document and run the namespace migration.
650
+ *
651
+ * The platform's own one-time import knows only its private table of entries, so a family
652
+ * section left in the document only produces a warn there — the values stay in the file the
653
+ * import renamed. This module reads that file (the renamed one first, a not-yet-imported
654
+ * `settings.yaml` second), plans with core's pure planner, and merges through the platform's
655
+ * own write. Everything it touches is injected, so a spec drives it without a host.
656
+ * @module @lmzhen/dsh-evolution-commands/migration
657
+ */
658
+ /**
659
+ * The legacy document names the platform leaves behind, in read order.
660
+ * @param home - the profile home the document sits in.
661
+ * @returns both candidate paths, the renamed import first.
662
+ */
663
+ function legacySettingsPaths(home) {
664
+ return [join(home, "settings.yaml.imported"), join(home, "settings.yaml")];
665
+ }
666
+ /** Nothing to do: no document, or no settings seat to write through. */
667
+ const NOTHING = {
668
+ source: void 0,
669
+ plan: void 0,
670
+ report: void 0
671
+ };
672
+ /**
673
+ * Read the first legacy document that exists and merge what it holds.
674
+ *
675
+ * The write goes through the platform's own `settings.update`, so the merge semantics, the
676
+ * revision fence and the row's schema validation are the platform's — a row whose schema
677
+ * refuses a key refuses the whole patch, which is why the planner refuses unknown keys
678
+ * before this runs.
679
+ * @param run - the home, the reader, the settings seat and the warning sink.
680
+ * @returns the source file, its plan, and what the run did (all undefined when there was
681
+ * nothing to read or nowhere to write).
682
+ */
683
+ async function runNamespaceMigration(run) {
684
+ const settings = run.settings;
685
+ if (settings === void 0) return NOTHING;
686
+ const read = (rowId) => settings.describe?.({ redactSecrets: false }).find((entry) => entry.ns === rowId);
687
+ const update = async (rowId, patch) => {
688
+ if (settings.update === void 0) return;
689
+ await settings.update(rowId, patch);
690
+ };
691
+ if (settings.describe === void 0 || settings.update === void 0) return NOTHING;
692
+ let seen;
693
+ for (const source of legacySettingsPaths(run.home)) {
694
+ const text = await run.io.readText(source);
695
+ if (text === null) continue;
696
+ const plan = planNamespaceMigration(text);
697
+ if (plan.entries.length === 0) {
698
+ seen ??= {
699
+ source,
700
+ plan
701
+ };
702
+ continue;
703
+ }
704
+ return {
705
+ source,
706
+ plan,
707
+ report: await applyNamespaceMigration(plan, {
708
+ read,
709
+ update,
710
+ warn: run.warn
711
+ })
712
+ };
713
+ }
714
+ return seen === void 0 ? NOTHING : {
715
+ source: seen.source,
716
+ plan: seen.plan,
717
+ report: void 0
718
+ };
719
+ }
720
+ /**
721
+ * Read the legacy document and report what is still unmigrated.
722
+ *
723
+ * Read-only by construction: the answer comes from the pure classifier, never from the
724
+ * applier, so a doctor run cannot write. `runNamespaceMigration` and this read the SAME
725
+ * decision, which is what keeps the report and the next run's outcome from disagreeing.
726
+ * @param run - the home, the reader, the settings seat.
727
+ * @returns the state, or undefined when there is no legacy document or no settings seat.
728
+ */
729
+ async function readLegacyDocumentState(run) {
730
+ const settings = run.settings;
731
+ if (settings?.describe === void 0) return void 0;
732
+ let seen;
733
+ for (const source of legacySettingsPaths(run.home)) {
734
+ const text = await run.io.readText(source);
735
+ if (text === null) continue;
736
+ const plan = planNamespaceMigration(text);
737
+ if (plan.entries.length === 0) {
738
+ seen ??= {
739
+ source,
740
+ plan
741
+ };
742
+ continue;
743
+ }
744
+ return stateOf(source, plan);
745
+ }
746
+ return seen === void 0 ? void 0 : stateOf(seen.source, seen.plan);
747
+ /** The doctor-facing state of ONE document, judged against the seat. */
748
+ function stateOf(source, plan) {
749
+ const read = (rowId) => settings?.describe?.({ redactSecrets: false }).find((entry) => entry.ns === rowId);
750
+ const decided = classifyNamespaceMigration(plan, read);
751
+ return {
752
+ source,
753
+ sections: plan.entries.length,
754
+ pending: decided.write.flatMap((row) => Object.keys(row.patch).map((key) => row.rowId + "." + key)),
755
+ settled: [...decided.unchanged.map((entry) => entry.rowId + "." + entry.key), ...decided.conflicts.map((entry) => entry.rowId + "." + entry.key)]
756
+ };
757
+ }
758
+ }
759
+ /**
760
+ * Run the migration from a plugin context: probe the settings seat, the profile home and the
761
+ * IO seam, then delegate to {@link runNamespaceMigration}.
762
+ *
763
+ * The command reports `problem` as its own error text; a boot-time caller skips instead — the
764
+ * point of naming the missing prerequisite rather than throwing is that both readers can act.
765
+ * @param host - the context (services + logger).
766
+ * @returns the outcome, or the prerequisite that is absent.
767
+ */
768
+ async function migrateFromContext(host) {
769
+ const settings = host.get("settings");
770
+ if (settings?.update === void 0 || settings.describe === void 0) return {
771
+ ok: false,
772
+ problem: "settings"
773
+ };
774
+ const profile = host.get("profileContext");
775
+ const home = typeof profile?.home === "string" ? profile.home : "";
776
+ if (home === "") return {
777
+ ok: false,
778
+ problem: "home"
779
+ };
780
+ const io = host.get("evolutionIo")?.provider?.();
781
+ if (io === void 0) return {
782
+ ok: false,
783
+ problem: "io"
784
+ };
785
+ return {
786
+ ok: true,
787
+ outcome: await runNamespaceMigration({
788
+ home,
789
+ io,
790
+ settings,
791
+ warn: (message) => {
792
+ host.logger.warn(message);
793
+ }
794
+ })
795
+ };
796
+ }
797
+ /**
798
+ * Render one outcome for the command surface.
799
+ * @param outcome - the run's result.
800
+ * @returns the report text (Chinese copy, the family's user-facing language).
801
+ */
802
+ function renderNamespaceMigration(outcome) {
803
+ if (outcome.source === void 0) return "迁移:没有找到旧设置文档(settings.yaml.imported / settings.yaml),无需迁移。";
804
+ const report = outcome.report;
805
+ if (report === void 0) return "迁移:" + outcome.source + " 里没有家族的旧分区,无需迁移。";
806
+ const rows = report.written.map((row) => `${row.rowId}:${row.keys.join("/")}`).join(";");
807
+ const kept = report.conflicts.map((conflict) => `${conflict.rowId}.${conflict.key}`).join("、");
808
+ const skipped = report.skipped.map((skip) => `${skip.namespace}.${skip.key}`).join("、");
809
+ return [
810
+ `迁移源:${outcome.source}`,
811
+ `写入:${report.written.length} 行${rows === "" ? "" : `(${rows})`}`,
812
+ `已一致:${report.unchanged.length} 个键(值相同,未写入)`,
813
+ `保留现值:${report.conflicts.length} 个键${kept === "" ? "" : `(${kept})`}`,
814
+ `未迁移:${report.skipped.length} 个键${skipped === "" ? "" : `(${skipped})`}`
815
+ ].join("\n");
816
+ }
817
+ //#endregion
633
818
  //#region lib/types/generated/host-commands.js
634
819
  /**
635
820
  * GENERATED by packages/scripts/gen-host-commands.mjs — do not edit.
@@ -1096,14 +1281,14 @@ const HOST_COMMANDS = {
1096
1281
  "pt": "atualizado — uma nova geração corresponde byte a byte a este arquivo"
1097
1282
  },
1098
1283
  "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)"
1284
+ "zh": "与最新生成不同 — 这是安装时快照;重新运行安装器(all/host)以重新生成",
1285
+ "en": "DIFFERS from a fresh generation — it is an install-time snapshot; re-run the installer (all/host) to regenerate",
1286
+ "ja": "最新の生成結果と異なります — インストール時のスナップショットです。インストーラー(all/host)を再実行して再生成してください",
1287
+ "es": "DIFIERE de una generación nueva — es una instantánea del momento de instalar; vuelve a ejecutar el instalador (all/host) para regenerarla",
1288
+ "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",
1289
+ "de": "WEICHT von einer neuen Erzeugung ab — es ist ein Installations-Snapshot; Installer erneut ausführen (all/host), um ihn neu zu erzeugen",
1290
+ "ru": "ОТЛИЧАЕТСЯ от новой генерации — это снимок на момент установки; запустите установщик повторно (all/host)",
1291
+ "pt": "DIFERE de uma nova geração — é um instantâneo do momento da instalação; execute o instalador novamente (all/host)"
1107
1292
  },
1108
1293
  "doctor.presetUnknown": {
1109
1294
  "zh": "未知 — 无法重新生成({detail})",
@@ -1344,176 +1529,833 @@ function hostErrorText(locale, id, args = {}) {
1344
1529
  return errorTextIn(locale, id, args);
1345
1530
  }
1346
1531
  //#endregion
1347
- //#region lib/types/migration.js
1532
+ //#region lib/types/host-command-defs.js
1533
+ const HOST_COMMAND_DEFS = [
1534
+ {
1535
+ id: "merge",
1536
+ words: ["merge"],
1537
+ summaryKey: "summary.merge",
1538
+ helpKey: "help.merge",
1539
+ flags: [],
1540
+ positional: [],
1541
+ readOnly: false,
1542
+ needsRun: false,
1543
+ fallback: "merge <subcommand> [<args>]",
1544
+ usageLine: "merge <subcommand> [<args>]"
1545
+ },
1546
+ {
1547
+ id: "pending",
1548
+ words: ["pending"],
1549
+ summaryKey: "summary.pending",
1550
+ helpKey: "help.pending",
1551
+ flags: [{
1552
+ name: "detail",
1553
+ kind: "boolean"
1554
+ }],
1555
+ positional: [],
1556
+ readOnly: true,
1557
+ needsRun: false,
1558
+ fallback: "pending [--detail]",
1559
+ usageLine: "pending [--detail]"
1560
+ },
1561
+ {
1562
+ id: "approve",
1563
+ words: ["approve"],
1564
+ summaryKey: "summary.approve",
1565
+ helpKey: "help.approve",
1566
+ flags: [],
1567
+ positional: [],
1568
+ readOnly: false,
1569
+ needsRun: false,
1570
+ fallback: "approve <id>",
1571
+ usageLine: "approve <id>"
1572
+ },
1573
+ {
1574
+ id: "reject",
1575
+ words: ["reject"],
1576
+ summaryKey: "summary.reject",
1577
+ helpKey: "help.reject",
1578
+ flags: [],
1579
+ positional: [],
1580
+ readOnly: false,
1581
+ needsRun: false,
1582
+ fallback: "reject <id>",
1583
+ usageLine: "reject <id>"
1584
+ },
1585
+ {
1586
+ id: "release",
1587
+ words: ["release"],
1588
+ summaryKey: "summary.release",
1589
+ helpKey: "help.release",
1590
+ flags: [],
1591
+ positional: [],
1592
+ readOnly: false,
1593
+ needsRun: false,
1594
+ fallback: "release <id>",
1595
+ usageLine: "release <id>"
1596
+ },
1597
+ {
1598
+ id: "doctor",
1599
+ words: ["doctor"],
1600
+ summaryKey: "summary.doctor",
1601
+ helpKey: "help.doctor",
1602
+ flags: [{
1603
+ name: "json",
1604
+ kind: "boolean"
1605
+ }],
1606
+ positional: [],
1607
+ readOnly: true,
1608
+ needsRun: false,
1609
+ fallback: "doctor [--json]",
1610
+ usageLine: "doctor [--json]"
1611
+ },
1612
+ {
1613
+ id: "curator",
1614
+ words: ["curator"],
1615
+ summaryKey: "summary.curator",
1616
+ helpKey: "help.curator",
1617
+ flags: [],
1618
+ positional: [],
1619
+ readOnly: false,
1620
+ needsRun: false,
1621
+ fallback: "curator run|pause|resume|status|report|scope",
1622
+ usageLine: "curator run|pause|resume|status|report|scope"
1623
+ },
1624
+ {
1625
+ id: "mutations",
1626
+ words: ["mutations"],
1627
+ summaryKey: "summary.mutations",
1628
+ helpKey: "help.mutations",
1629
+ flags: [],
1630
+ positional: [],
1631
+ readOnly: true,
1632
+ needsRun: false,
1633
+ fallback: "mutations",
1634
+ usageLine: "mutations"
1635
+ },
1636
+ {
1637
+ id: "restore",
1638
+ words: ["restore"],
1639
+ summaryKey: "summary.restore",
1640
+ helpKey: "help.restore",
1641
+ flags: [],
1642
+ positional: [],
1643
+ readOnly: false,
1644
+ needsRun: false,
1645
+ fallback: "restore",
1646
+ usageLine: "restore"
1647
+ },
1648
+ {
1649
+ id: "skill.restore",
1650
+ words: ["skill", "restore"],
1651
+ summaryKey: "summary.skill restore",
1652
+ helpKey: "help.skill restore",
1653
+ flags: [],
1654
+ positional: [],
1655
+ readOnly: false,
1656
+ needsRun: false,
1657
+ fallback: "skill restore <name>",
1658
+ usageLine: "skill restore <name>"
1659
+ },
1660
+ {
1661
+ id: "skill.history",
1662
+ words: ["skill", "history"],
1663
+ summaryKey: "summary.skill history",
1664
+ helpKey: "help.skill history",
1665
+ flags: [],
1666
+ positional: [],
1667
+ readOnly: true,
1668
+ needsRun: false,
1669
+ fallback: "skill history <name>",
1670
+ usageLine: "skill history <name>"
1671
+ },
1672
+ {
1673
+ id: "skill.undo",
1674
+ words: ["skill", "undo"],
1675
+ summaryKey: "summary.skill undo",
1676
+ helpKey: "help.skill undo",
1677
+ flags: [{
1678
+ name: "to",
1679
+ kind: "value"
1680
+ }],
1681
+ positional: [],
1682
+ readOnly: false,
1683
+ needsRun: false,
1684
+ fallback: "skill undo <name> [--to v<N>]",
1685
+ usageLine: "skill undo <name> [--to v<N>]"
1686
+ },
1687
+ {
1688
+ id: "skill.pin",
1689
+ words: ["skill", "pin"],
1690
+ summaryKey: "summary.skill pin",
1691
+ helpKey: "help.skill pin",
1692
+ flags: [],
1693
+ positional: [],
1694
+ readOnly: false,
1695
+ needsRun: false,
1696
+ fallback: "skill pin <name>",
1697
+ usageLine: "skill pin <name>"
1698
+ },
1699
+ {
1700
+ id: "skill.unpin",
1701
+ words: ["skill", "unpin"],
1702
+ summaryKey: "summary.skill unpin",
1703
+ helpKey: "help.skill unpin",
1704
+ flags: [],
1705
+ positional: [],
1706
+ readOnly: false,
1707
+ needsRun: false,
1708
+ fallback: "skill unpin <name>",
1709
+ usageLine: "skill unpin <name>"
1710
+ },
1711
+ {
1712
+ id: "propose",
1713
+ words: ["propose"],
1714
+ summaryKey: "summary.propose",
1715
+ helpKey: "help.propose",
1716
+ flags: [],
1717
+ positional: [],
1718
+ readOnly: false,
1719
+ needsRun: false,
1720
+ fallback: "propose",
1721
+ usageLine: "propose"
1722
+ },
1723
+ {
1724
+ id: "skills.health",
1725
+ words: ["skills", "health"],
1726
+ summaryKey: "summary.skills health",
1727
+ helpKey: "help.skills health",
1728
+ flags: [],
1729
+ positional: [],
1730
+ readOnly: true,
1731
+ needsRun: false,
1732
+ fallback: "skills health",
1733
+ usageLine: "skills health"
1734
+ },
1735
+ {
1736
+ id: "skills.refresh",
1737
+ words: ["skills", "refresh"],
1738
+ summaryKey: "summary.skills refresh",
1739
+ helpKey: "help.skills refresh",
1740
+ flags: [],
1741
+ positional: [],
1742
+ readOnly: false,
1743
+ needsRun: false,
1744
+ fallback: "skills refresh",
1745
+ usageLine: "skills refresh"
1746
+ },
1747
+ {
1748
+ id: "learn",
1749
+ words: ["learn"],
1750
+ summaryKey: "summary.learn",
1751
+ helpKey: "help.learn",
1752
+ flags: [],
1753
+ positional: [],
1754
+ readOnly: false,
1755
+ needsRun: false,
1756
+ fallback: "learn [request]",
1757
+ usageLine: "learn [request]"
1758
+ },
1759
+ {
1760
+ id: "maintain",
1761
+ words: ["maintain"],
1762
+ summaryKey: "summary.maintain",
1763
+ helpKey: "help.maintain",
1764
+ flags: [{
1765
+ name: "timeout",
1766
+ kind: "value"
1767
+ }, {
1768
+ name: "facts",
1769
+ kind: "boolean"
1770
+ }],
1771
+ positional: [],
1772
+ readOnly: false,
1773
+ needsRun: false,
1774
+ fallback: "maintain [--timeout=<ms> | --facts]",
1775
+ usageLine: "maintain [--timeout=<ms> | --facts]"
1776
+ },
1777
+ {
1778
+ id: "maintain.status",
1779
+ words: ["maintain", "status"],
1780
+ summaryKey: "summary.maintain status",
1781
+ helpKey: "help.maintain status",
1782
+ flags: [],
1783
+ positional: [],
1784
+ readOnly: true,
1785
+ needsRun: false,
1786
+ fallback: "maintain status [<id>]",
1787
+ usageLine: "maintain status [<id>]"
1788
+ },
1789
+ {
1790
+ id: "maintain.report",
1791
+ words: ["maintain", "report"],
1792
+ summaryKey: "summary.maintain report",
1793
+ helpKey: "help.maintain report",
1794
+ flags: [],
1795
+ positional: [],
1796
+ readOnly: true,
1797
+ needsRun: false,
1798
+ fallback: "maintain report [<id>]",
1799
+ usageLine: "maintain report [<id>]"
1800
+ },
1801
+ {
1802
+ id: "maintain.handoff",
1803
+ words: ["maintain", "handoff"],
1804
+ summaryKey: "summary.maintain handoff",
1805
+ helpKey: "help.maintain handoff",
1806
+ flags: [],
1807
+ positional: [],
1808
+ readOnly: false,
1809
+ needsRun: false,
1810
+ fallback: "maintain handoff [<id>]",
1811
+ usageLine: "maintain handoff [<id>]"
1812
+ },
1813
+ {
1814
+ id: "maintain.cancel",
1815
+ words: ["maintain", "cancel"],
1816
+ summaryKey: "summary.maintain cancel",
1817
+ helpKey: "help.maintain cancel",
1818
+ flags: [],
1819
+ positional: [],
1820
+ readOnly: false,
1821
+ needsRun: false,
1822
+ fallback: "maintain cancel [<id>]",
1823
+ usageLine: "maintain cancel [<id>]"
1824
+ },
1825
+ {
1826
+ id: "params",
1827
+ words: ["params"],
1828
+ summaryKey: "summary.params",
1829
+ helpKey: "help.params",
1830
+ flags: [{
1831
+ name: "group",
1832
+ kind: "value"
1833
+ }, {
1834
+ name: "json",
1835
+ kind: "boolean"
1836
+ }],
1837
+ positional: [],
1838
+ readOnly: true,
1839
+ needsRun: false,
1840
+ fallback: "params [--group <name>] [--json]",
1841
+ usageLine: "params [--group <name>] [--json]"
1842
+ },
1843
+ {
1844
+ id: "restructure",
1845
+ words: ["restructure"],
1846
+ summaryKey: "summary.restructure",
1847
+ helpKey: "help.restructure",
1848
+ flags: [{
1849
+ name: "plan",
1850
+ kind: "value"
1851
+ }],
1852
+ positional: [],
1853
+ readOnly: false,
1854
+ needsRun: false,
1855
+ fallback: "restructure <name> \"<heading>\" <to_file> [--plan <runId>]",
1856
+ usageLine: "restructure <name> \"<heading>\" <to_file> [--plan <runId>]"
1857
+ },
1858
+ {
1859
+ id: "extract",
1860
+ words: ["extract"],
1861
+ summaryKey: "summary.extract",
1862
+ helpKey: "help.extract",
1863
+ flags: [
1864
+ {
1865
+ name: "start",
1866
+ kind: "value"
1867
+ },
1868
+ {
1869
+ name: "end",
1870
+ kind: "value"
1871
+ },
1872
+ {
1873
+ name: "outcome",
1874
+ kind: "value"
1875
+ },
1876
+ {
1877
+ name: "proposal",
1878
+ kind: "value"
1879
+ },
1880
+ {
1881
+ name: "owner-covers",
1882
+ kind: "boolean"
1883
+ },
1884
+ {
1885
+ name: "apply",
1886
+ kind: "boolean"
1887
+ }
1888
+ ],
1889
+ positional: [],
1890
+ readOnly: false,
1891
+ needsRun: false,
1892
+ fallback: "extract <source> <target> \"<heading>\" [--start <line>] [--end <line>] [--outcome extract|mixed] [--proposal <id>] [--owner-covers] [--apply]",
1893
+ usageLine: "extract <source> <target> \"<heading>\" [--start <line>] [--end <line>] [--outcome extract|mixed] [--proposal <id>] [--owner-covers] [--apply]"
1894
+ },
1895
+ {
1896
+ id: "replay",
1897
+ words: ["replay"],
1898
+ summaryKey: "summary.replay",
1899
+ helpKey: "help.replay",
1900
+ flags: [],
1901
+ positional: [],
1902
+ readOnly: true,
1903
+ needsRun: false,
1904
+ fallback: "replay",
1905
+ usageLine: "replay"
1906
+ }
1907
+ ];
1908
+ /** Resolve a parsed command to its declaration: the longest `words` prefix wins. */
1909
+ function hostCommandDefForCommand(command) {
1910
+ let found;
1911
+ for (const def of HOST_COMMAND_DEFS) if (def.words.every((word, index) => (index === 0 ? command.name : command.positionals[index - 1]) === word) && (found === void 0 || def.words.length > found.words.length)) found = def;
1912
+ return found;
1913
+ }
1914
+ //#endregion
1915
+ //#region lib/types/registry.js
1348
1916
  /**
1349
- * G3 (caller half): find the legacy settings document and run the namespace migration.
1350
- *
1351
- * The platform's own one-time import knows only its private table of entries, so a family
1352
- * section left in the document only produces a warn there — the values stay in the file the
1353
- * import renamed. This module reads that file (the renamed one first, a not-yet-imported
1354
- * `settings.yaml` second), plans with core's pure planner, and merges through the platform's
1355
- * own write. Everything it touches is injected, so a spec drives it without a host.
1356
- * @module @lmzhen/dsh-evolution-commands/migration
1917
+ * Command surface rendering. HOST_COMMAND_DEFS is the one table; every renderer here reads it.
1918
+ * Keep `usageLine` in the exact shape a user can type after `/evolution`.
1357
1919
  */
1920
+ /** The flags the TABLE declares for one subcommand (name → `--flag`). */
1921
+ function flagsOf(name) {
1922
+ return HOST_COMMAND_DEFS.find((candidate) => entryName(candidate) === name)?.flags.map((flag) => "--" + flag.name) ?? [];
1923
+ }
1358
1924
  /**
1359
- * The legacy document names the platform leaves behind, in read order.
1360
- * @param home - the profile home the document sits in.
1361
- * @returns both candidate paths, the renamed import first.
1362
- */
1363
- function legacySettingsPaths(home) {
1364
- return [join(home, "settings.yaml.imported"), join(home, "settings.yaml")];
1925
+ * C7 shape, DERIVED: the entry IDENTITY key, and it is HIERARCHICAL (E-08).
1926
+ *
1927
+ * The key used to be the first token alone, and `flagsOf` finds an entry with `.find(...)` - the FIRST
1928
+ * match - so `maintain handoff` / `maintain cancel` and `skill restore` / `skill history` / `skill undo` /
1929
+ * `skill pin` all derived the SAME key as their parent and every flag lookup silently saw the parent entry
1930
+ * only (nine collisions). A bare parent (`maintain [--timeout]`) keeps its one-token key, so parent lookups
1931
+ * still resolve: the one call site that named an entry by a name the key no longer produced was the preset
1932
+ * dispatch branch, and it now asks for the entry own key (`preset install`).
1933
+ */
1934
+ function entryName(entry) {
1935
+ return entry.words.join(" ");
1365
1936
  }
1366
- /** Nothing to do: no document, or no settings seat to write through. */
1367
- const NOTHING = {
1368
- source: void 0,
1369
- plan: void 0,
1370
- report: void 0
1371
- };
1937
+ /** The one summary source: the generated command i18n catalog. */
1938
+ function summaryOf(entry, locale = "zh") {
1939
+ const text = HOST_COMMANDS["summary." + entryName(entry)]?.[locale];
1940
+ if (text === void 0) throw new Error("registry: no generated summary for " + entryName(entry) + " (" + locale + ")");
1941
+ return text;
1942
+ }
1943
+ /** The input-declaration hint (single line, ` | `-separated). */
1944
+ function renderHint() {
1945
+ return HOST_COMMAND_DEFS.map((entry) => entry.usageLine).join(" | ");
1946
+ }
1947
+ /** The bare `/evolution` help body (one line per subcommand). */
1948
+ function renderHelpText(locale = "zh") {
1949
+ return [
1950
+ (HOST_COMMANDS["help.subcommands"][locale] ?? HOST_COMMANDS["help.subcommands"].en).replace("{count}", String(HOST_COMMAND_DEFS.length)),
1951
+ "",
1952
+ ...HOST_COMMAND_DEFS.map((entry) => ` ${entry.usageLine.padEnd(44)} ${summaryOf(entry, locale)}`)
1953
+ ].join("\n");
1954
+ }
1955
+ /** Union of every entry's authored value flags. */
1956
+ const VALUE_FLAGS = (() => {
1957
+ const names = [];
1958
+ 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);
1959
+ return names;
1960
+ })();
1961
+ //#endregion
1962
+ //#region lib/types/parse.js
1372
1963
  /**
1373
- * Read the first legacy document that exists and merge what it holds.
1964
+ * F-4/G7.4 (C7): the ONE parser for the /evolution command surface.
1374
1965
  *
1375
- * The write goes through the platform's own `settings.update`, so the merge semantics, the
1376
- * revision fence and the row's schema validation are the platform's — a row whose schema
1377
- * refuses a key refuses the whole patch, which is why the planner refuses unknown keys
1378
- * before this runs.
1379
- * @param run - the home, the reader, the settings seat and the warning sink.
1380
- * @returns the source file, its plan, and what the run did (all undefined when there was
1381
- * nothing to read or nowhere to write).
1966
+ * The surface used to answer each subcommand with its own regex (`^params(?: --group ([a-z-]+))?(?: --json)?$`
1967
+ * and nine siblings), so `params --json --group review` and `params --group=review` were refused as
1968
+ * "not a subcommand", while a sibling regex accepted `=` — and a mistyped group name degraded into the
1969
+ * generic error instead of the one that lists the known groups.
1970
+ *
1971
+ * This parser is order- and `=`-tolerant, matches the subcommand name case-insensitively, keeps a flag
1972
+ * VALUE's case intact (the domain layer is the one that validates it), and answers a SYNTAX failure when a
1973
+ * declared value flag is left without its value (F-3: `extract --start 3` must not read
1974
+ * `--expect 3` as the value).
1975
+ *
1976
+ * @module @lmzhen/dsh-evolution-commands/parse
1382
1977
  */
1383
- async function runNamespaceMigration(run) {
1384
- const settings = run.settings;
1385
- if (settings === void 0) return NOTHING;
1386
- const read = (rowId) => settings.describe?.({ redactSecrets: false }).find((entry) => entry.ns === rowId);
1387
- const update = async (rowId, patch) => {
1388
- if (settings.update === void 0) return;
1389
- await settings.update(rowId, patch);
1978
+ /** The flags whose declared form takes a value, authored in the command table. */
1979
+ /**
1980
+ * Narrow a parse result: true when it is the syntax failure rather than a command.
1981
+ * @param result - what {@link parseSubcommand} answered.
1982
+ * @returns whether the line was refused.
1983
+ */
1984
+ function isParseFailure(result) {
1985
+ return result.kind !== void 0;
1986
+ }
1987
+ /**
1988
+ * Split a command line into tokens: whitespace separates, and a double-quoted run is ONE token with its
1989
+ * quotes removed (the `restructure <name> "<heading>" <to_file>` form needs that; the old regexes each
1990
+ * carried their own quoting rule).
1991
+ * @param input - the text after `/evolution`.
1992
+ * @returns the tokens, in order.
1993
+ */
1994
+ function tokenize(input) {
1995
+ const tokens = [];
1996
+ let current = "";
1997
+ let quoted = false;
1998
+ for (const char of input.trim()) {
1999
+ if (char === String.fromCharCode(34)) {
2000
+ quoted = !quoted;
2001
+ continue;
2002
+ }
2003
+ if (!quoted && /\s/.test(char)) {
2004
+ if (current !== "") {
2005
+ tokens.push(current);
2006
+ current = "";
2007
+ }
2008
+ continue;
2009
+ }
2010
+ current += char;
2011
+ }
2012
+ if (current !== "") tokens.push(current);
2013
+ return tokens;
2014
+ }
2015
+ /**
2016
+ * Parse one command line into its name, flags and positionals.
2017
+ * @param input - the text after `/evolution`.
2018
+ * @returns the parsed command, or the syntax failure that refused it.
2019
+ */
2020
+ function parseSubcommand(input) {
2021
+ const [first, ...rest] = tokenize(input);
2022
+ if (first === void 0) return {
2023
+ kind: "unknown-subcommand",
2024
+ name: ""
1390
2025
  };
1391
- if (settings.describe === void 0 || settings.update === void 0) return NOTHING;
1392
- let seen;
1393
- for (const source of legacySettingsPaths(run.home)) {
1394
- const text = await run.io.readText(source);
1395
- if (text === null) continue;
1396
- const plan = planNamespaceMigration(text);
1397
- if (plan.entries.length === 0) {
1398
- seen ??= {
1399
- source,
1400
- plan
1401
- };
2026
+ const name = first.toLowerCase();
2027
+ const flags = /* @__PURE__ */ new Map();
2028
+ const positionals = [];
2029
+ for (let index = 0; index < rest.length; index += 1) {
2030
+ const token = rest[index];
2031
+ if (token === void 0) continue;
2032
+ if (!token.startsWith("--")) {
2033
+ positionals.push(token);
1402
2034
  continue;
1403
2035
  }
1404
- return {
1405
- source,
1406
- plan,
1407
- report: await applyNamespaceMigration(plan, {
1408
- read,
1409
- update,
1410
- warn: run.warn
1411
- })
2036
+ const equals = token.indexOf("=");
2037
+ const flag = (equals < 0 ? token : token.slice(0, equals)).slice(2);
2038
+ if (equals >= 0) {
2039
+ flags.set(flag, token.slice(equals + 1));
2040
+ continue;
2041
+ }
2042
+ if (!VALUE_FLAGS.includes(flag)) {
2043
+ flags.set(flag, true);
2044
+ continue;
2045
+ }
2046
+ const next = rest[index + 1];
2047
+ if (next === void 0 || next.startsWith("--")) return {
2048
+ kind: "missing-value",
2049
+ name,
2050
+ flag
1412
2051
  };
2052
+ flags.set(flag, next);
2053
+ index += 1;
1413
2054
  }
1414
- return seen === void 0 ? NOTHING : {
1415
- source: seen.source,
1416
- plan: seen.plan,
1417
- report: void 0
2055
+ return {
2056
+ name,
2057
+ flags,
2058
+ positionals
1418
2059
  };
1419
2060
  }
2061
+ //#endregion
2062
+ //#region lib/types/params.js
1420
2063
  /**
1421
- * Read the legacy document and report what is still unmigrated.
2064
+ * `/evolution params` view (G4/S4.1): the registry joined with the settings
2065
+ * surface, so one text answers "which parameters exist, who may write them, and
2066
+ * did I already override this one".
1422
2067
  *
1423
- * Read-only by construction: the answer comes from the pure classifier, never from the
1424
- * applier, so a doctor run cannot write. `runNamespaceMigration` and this read the SAME
1425
- * decision, which is what keeps the report and the next run's outcome from disagreeing.
1426
- * @param run - the home, the reader, the settings seat.
1427
- * @returns the state, or undefined when there is no legacy document or no settings seat.
2068
+ * The join key is the OWNER PACKAGE: `settings.describe()` keys a section by the Loader
2069
+ * entry id, which is the row id (core's `paramSettingsId` names that mapping), and reports
2070
+ * that section's raw user section (a key's PRESENCE is the override) plus the resolved
2071
+ * value. Everything here is pure; the command handler supplies the data.
2072
+ * @module @lmzhen/dsh-evolution-commands/params
1428
2073
  */
1429
- async function readLegacyDocumentState(run) {
1430
- const settings = run.settings;
1431
- if (settings?.describe === void 0) return void 0;
1432
- let seen;
1433
- for (const source of legacySettingsPaths(run.home)) {
1434
- const text = await run.io.readText(source);
1435
- if (text === null) continue;
1436
- const plan = planNamespaceMigration(text);
1437
- if (plan.entries.length === 0) {
1438
- seen ??= {
1439
- source,
1440
- plan
1441
- };
1442
- continue;
1443
- }
1444
- return stateOf(source, plan);
1445
- }
1446
- return seen === void 0 ? void 0 : stateOf(seen.source, seen.plan);
1447
- /** The doctor-facing state of ONE document, judged against the seat. */
1448
- function stateOf(source, plan) {
1449
- const read = (rowId) => settings?.describe?.({ redactSecrets: false }).find((entry) => entry.ns === rowId);
1450
- const decided = classifyNamespaceMigration(plan, read);
2074
+ /**
2075
+ * Join the registry with the settings surface.
2076
+ *
2077
+ * `user` means the raw user section carries this key; `deployment` means the
2078
+ * owner's namespace is registered but the key is unset (so the row/policy value
2079
+ * applies); `unregistered` means the owner package publishes no namespace at all
2080
+ * (or is not mounted), which is the honest answer for a deployment-only face.
2081
+ * The distinction matters: 'no user section' must never read as 'not overridden'
2082
+ * for a namespace that failed to register.
2083
+ * @param sections - namespace to surface view, from `settings.describe()`.
2084
+ * @param entries - registry entries (defaults to the family registry).
2085
+ * @returns one row per registry entry, in registry order.
2086
+ */
2087
+ function paramSurfaceRows(sections, entries = PARAM_EXPOSURE) {
2088
+ return entries.map((entry) => {
2089
+ const base = {
2090
+ id: entry.id,
2091
+ group: entry.group,
2092
+ tier: entry.tier,
2093
+ applies: entry.applies,
2094
+ owner: entry.owner
2095
+ };
2096
+ const namespace = paramSettingsId(entry.owner);
2097
+ const section = namespace === void 0 ? void 0 : sections.get(namespace);
2098
+ if (section === void 0) return {
2099
+ ...base,
2100
+ source: "unregistered",
2101
+ value: void 0
2102
+ };
2103
+ const user = section.user;
2104
+ if (user !== void 0 && Object.hasOwn(user, entry.id)) return {
2105
+ ...base,
2106
+ source: "user",
2107
+ value: user[entry.id]
2108
+ };
1451
2109
  return {
1452
- source,
1453
- sections: plan.entries.length,
1454
- pending: decided.write.flatMap((row) => Object.keys(row.patch).map((key) => row.rowId + "." + key)),
1455
- settled: [...decided.unchanged.map((entry) => entry.rowId + "." + entry.key), ...decided.conflicts.map((entry) => entry.rowId + "." + entry.key)]
2110
+ ...base,
2111
+ source: "deployment",
2112
+ value: section.value?.[entry.id]
1456
2113
  };
1457
- }
2114
+ });
1458
2115
  }
1459
2116
  /**
1460
- * Run the migration from a plugin context: probe the settings seat, the profile home and the
1461
- * IO seam, then delegate to {@link runNamespaceMigration}.
1462
- *
1463
- * The command reports `problem` as its own error text; a boot-time caller skips instead — the
1464
- * point of naming the missing prerequisite rather than throwing is that both readers can act.
1465
- * @param host - the context (services + logger).
1466
- * @returns the outcome, or the prerequisite that is absent.
2117
+ * The groups the registry actually carries, in registry order — the list an
2118
+ * unknown `--group` value is answered with.
2119
+ * @param entries - registry entries (defaults to the family registry).
2120
+ * @returns distinct group names.
1467
2121
  */
1468
- async function migrateFromContext(host) {
1469
- const settings = host.get("settings");
1470
- if (settings?.update === void 0 || settings.describe === void 0) return {
1471
- ok: false,
1472
- problem: "settings"
1473
- };
1474
- const profile = host.get("profileContext");
1475
- const home = typeof profile?.home === "string" ? profile.home : "";
1476
- if (home === "") return {
1477
- ok: false,
1478
- problem: "home"
1479
- };
1480
- const io = host.get("evolutionIo")?.provider?.();
1481
- if (io === void 0) return {
1482
- ok: false,
1483
- problem: "io"
1484
- };
1485
- return {
1486
- ok: true,
1487
- outcome: await runNamespaceMigration({
1488
- home,
1489
- io,
1490
- settings,
1491
- warn: (message) => {
1492
- host.logger.warn(message);
1493
- }
1494
- })
1495
- };
2122
+ function paramGroups(entries = PARAM_EXPOSURE) {
2123
+ return [...new Set(entries.map((entry) => entry.group))];
2124
+ }
2125
+ /** One cell: `—` when no face reports a value, JSON for arrays/objects. */
2126
+ function renderValue(value) {
2127
+ if (value === void 0) return "—";
2128
+ if (typeof value === "string") return value;
2129
+ return JSON.stringify(value);
1496
2130
  }
2131
+ const WIDE_CHAR = new RegExp("[" + [
2132
+ "ᄀ-ᅟ",
2133
+ "⺀-〾",
2134
+ "ぁ-㏿",
2135
+ "㐀-䶿",
2136
+ "一-鿿",
2137
+ "가-힣",
2138
+ "豈-﫿",
2139
+ "︰-﹯",
2140
+ "＀-⦆",
2141
+ "¢-₩"
2142
+ ].join("") + "]");
1497
2143
  /**
1498
- * Render one outcome for the command surface.
1499
- * @param outcome - the run's result.
1500
- * @returns the report text (Chinese copy, the family's user-facing language).
2144
+ * Pad one cell to a display width, counting CJK characters as two columns.
2145
+ * @param text - the cell text.
2146
+ * @param columns - the target width in terminal columns.
2147
+ * @returns the text plus at least one space, so columns never touch.
1501
2148
  */
1502
- function renderNamespaceMigration(outcome) {
1503
- if (outcome.source === void 0) return "迁移:没有找到旧设置文档(settings.yaml.imported / settings.yaml),无需迁移。";
1504
- const report = outcome.report;
1505
- if (report === void 0) return "迁移:" + outcome.source + " 里没有家族的旧分区,无需迁移。";
1506
- const rows = report.written.map((row) => `${row.rowId}:${row.keys.join("/")}`).join(";");
1507
- const kept = report.conflicts.map((conflict) => `${conflict.rowId}.${conflict.key}`).join("、");
1508
- const skipped = report.skipped.map((skip) => `${skip.namespace}.${skip.key}`).join("、");
2149
+ function pad(text, columns) {
2150
+ let used = 0;
2151
+ for (const char of text) used += WIDE_CHAR.test(char) ? 2 : 1;
2152
+ return text + " ".repeat(Math.max(1, columns - used));
2153
+ }
2154
+ /** Settings timing, in the operator's words. */
2155
+ const APPLIES_LABELS = Object.freeze({
2156
+ live: "立即",
2157
+ restart: "重启后",
2158
+ none: "不生效"
2159
+ });
2160
+ /** Where a row's effective value comes from, in the operator's words. */
2161
+ const SOURCE_LABELS = Object.freeze({
2162
+ user: "我改过",
2163
+ deployment: "默认",
2164
+ unregistered: "不可改"
2165
+ });
2166
+ /** What the E-tiers mean, so the count line reads without the docs. */
2167
+ const TIER_LEGEND = "档位:E0 固定/E1 只读/E2 安装时定/E3 你可改/E4 装完固化。";
2168
+ /**
2169
+ * The source column's word for one row (F-1).
2170
+ *
2171
+ * `unregistered` covers TWO different facts: the owner publishes no settings namespace (the value
2172
+ * really cannot be written — E-315/E-316) and the settings service itself is missing (then whether
2173
+ * the value could be written is UNKNOWN). Without a provider the column must not claim "不可改", or it
2174
+ * contradicts the legend and the footer of the very same output.
2175
+ * @param row - the row's surface facts.
2176
+ * @param providerMounted - whether a settings provider answered.
2177
+ * @returns the label for the source column.
2178
+ */
2179
+ function sourceLabel(row, providerMounted) {
2180
+ const label = SOURCE_LABELS[row.source] ?? row.source;
2181
+ return providerMounted || row.source !== "unregistered" ? label : "未知";
2182
+ }
2183
+ function renderParamRows(rows, options) {
2184
+ const header = pad("参数", 36) + pad("分组", 12) + pad("档位", 6) + pad("生效", 8) + pad("来源", 10) + "当前值";
2185
+ const body = rows.map((row) => pad(row.id, 36) + pad(PARAM_GROUP_LABELS[row.group], 12) + pad(row.tier, 6) + pad(APPLIES_LABELS[row.applies] ?? row.applies, 8) + pad(sourceLabel(row, options.providerMounted), 10) + renderValue(row.value));
2186
+ const tiers = [
2187
+ "E0",
2188
+ "E1",
2189
+ "E2",
2190
+ "E3",
2191
+ "E4"
2192
+ ].map((tier) => `${tier} ${rows.filter((row) => row.tier === tier).length}`).join(" / ");
2193
+ const userRows = rows.filter((row) => row.source === "user").length;
2194
+ const counts = options.providerMounted ? `共 ${rows.length} 个参数:${tiers};你改过的:${userRows} 项。` : `共 ${rows.length} 个参数:${tiers};是否改过:未知(没有设置服务)。`;
2195
+ const note = options.providerMounted ? "来源:我改过=你在设置里改的;默认=安装时的配置;不可改=该功能不提供用户可改项。" : "设置服务未挂载——读不到你改过的值,所以每行显示的都是安装时的配置(这不等于「你没改过」)。";
1509
2196
  return [
1510
- `迁移源:${outcome.source}`,
1511
- `写入:${report.written.length} 行${rows === "" ? "" : `(${rows})`}`,
1512
- `已一致:${report.unchanged.length} 个键(值相同,未写入)`,
1513
- `保留现值:${report.conflicts.length} 个键${kept === "" ? "" : `(${kept})`}`,
1514
- `未迁移:${report.skipped.length} 个键${skipped === "" ? "" : `(${skipped})`}`
2197
+ counts,
2198
+ "",
2199
+ header,
2200
+ ...body,
2201
+ "",
2202
+ TIER_LEGEND,
2203
+ note
1515
2204
  ].join("\n");
1516
2205
  }
2206
+ /**
2207
+ * Render the rows as JSON for scripts (same fields, no formatting).
2208
+ * @param rows - rows from {@link paramSurfaceRows}.
2209
+ * @returns a JSON document with a `params` array.
2210
+ */
2211
+ function renderParamJson(rows) {
2212
+ return JSON.stringify({ params: rows }, null, 2);
2213
+ }
2214
+ //#endregion
2215
+ //#region lib/types/host-commands/params-command.js
2216
+ const ok$5 = (text) => ({
2217
+ kind: "success",
2218
+ text
2219
+ });
2220
+ const err$4 = (text) => ({
2221
+ kind: "error",
2222
+ text
2223
+ });
2224
+ /**
2225
+ * Render the parameter registry. Unreadable provider is a refusal, not an empty override set.
2226
+ * @param context - command, settings provider and locale.
2227
+ * @returns the rows/JSON, or the settings/group error.
2228
+ */
2229
+ function runParamsCommand(context) {
2230
+ const { command, provider, locale } = context;
2231
+ const sections = /* @__PURE__ */ new Map();
2232
+ if (provider?.describe !== void 0) try {
2233
+ for (const descriptor of provider.describe({ redactSecrets: false })) {
2234
+ const section = {};
2235
+ if (descriptor.user !== void 0) section.user = descriptor.user;
2236
+ const resolved = descriptor.value;
2237
+ if (typeof resolved === "object" && resolved !== null) section.value = resolved;
2238
+ sections.set(descriptor.ns, section);
2239
+ }
2240
+ } catch (error) {
2241
+ return err$4(hostErrorText(locale, "e-307-the-settings-service-could", { a1: error instanceof Error ? error.message : String(error) }));
2242
+ }
2243
+ const rows = paramSurfaceRows(sections, PARAM_EXPOSURE);
2244
+ const groupFlag = command.flags.get("group");
2245
+ const group = typeof groupFlag === "string" ? groupFlag : void 0;
2246
+ const selected = group === void 0 ? rows : rows.filter((row) => row.group === group);
2247
+ if (group !== void 0 && selected.length === 0) return err$4(hostErrorText(locale, "e-308-unknown-parameter-group-group", {
2248
+ a1: group,
2249
+ a2: paramGroups(PARAM_EXPOSURE).join(", ")
2250
+ }));
2251
+ if (command.flags.get("json") === true) return ok$5(renderParamJson(selected));
2252
+ return ok$5(renderParamRows(selected, { providerMounted: provider !== void 0 }));
2253
+ }
2254
+ //#endregion
2255
+ //#region lib/types/host-commands/curator-command.js
2256
+ const ok$4 = (text) => ({
2257
+ kind: "success",
2258
+ text
2259
+ });
2260
+ const err$3 = (text) => ({
2261
+ kind: "error",
2262
+ text
2263
+ });
2264
+ /**
2265
+ * Run one curator subcommand. Returns undefined when the input is not a curator command,
2266
+ * so the legacy chain can answer.
2267
+ * @param context - raw input, service context and locale.
2268
+ * @returns the command result or undefined.
2269
+ */
2270
+ async function runCuratorCommand(context) {
2271
+ const { input, ctx, locale } = context;
2272
+ const hostError = (id, args = {}) => hostErrorText(locale, id, args);
2273
+ if (input === "curator run") {
2274
+ const curator = ctx.get("evolutionCurator");
2275
+ if (!curator) return err$3(hostError("e-302-curator-service-not-mounted"));
2276
+ const result = await curator.run({ ignoreGates: true });
2277
+ if (result.skipped !== void 0) return ok$4(hostCommandText(locale, "command.curator.skipped", {
2278
+ reason: result.skipped,
2279
+ runId: result.report.runId
2280
+ }));
2281
+ return ok$4(hostCommandText(locale, "command.curator.done", {
2282
+ stale: result.stale.length,
2283
+ archived: result.archived.length,
2284
+ errors: result.errors.length,
2285
+ runId: result.report.runId,
2286
+ snapshot: result.report.snapshotPath ? `\nsnapshot=${result.report.snapshotPath}` : ""
2287
+ }));
2288
+ }
2289
+ if (input === "curator pause" || input === "curator resume") {
2290
+ const curator = ctx.get("evolutionCurator");
2291
+ if (!curator) return err$3(hostError("e-302-curator-service-not-mounted"));
2292
+ const paused = input === "curator pause";
2293
+ await curator.setPaused(paused);
2294
+ const notPersisted = ctx.get("evolutionState") !== void 0 ? "" : hostCommandText(locale, "command.curator.notPersisted");
2295
+ return ok$4((paused ? hostCommandText(locale, "command.curator.paused") : hostCommandText(locale, "command.curator.resumed")) + notPersisted);
2296
+ }
2297
+ if (input === "curator status") {
2298
+ const curator = ctx.get("evolutionCurator");
2299
+ if (!curator) return err$3(hostError("e-302-curator-service-not-mounted"));
2300
+ const state = await curator.status();
2301
+ if (!state) return ok$4(hostCommandText(locale, "command.curator.noState"));
2302
+ const lastRun = typeof state.lastRunAt === "number" && Number.isFinite(state.lastRunAt) && state.lastRunAt > 0 ? new Date(state.lastRunAt).toISOString() : "unknown";
2303
+ return ok$4([
2304
+ `paused=${state.paused}`,
2305
+ `runs=${state.runCount}`,
2306
+ `lastRun=${lastRun}`,
2307
+ `summary=${state.lastSummary}`
2308
+ ].join("\n"));
2309
+ }
2310
+ if (input === "curator scope") {
2311
+ const curator = ctx.get("evolutionCurator");
2312
+ if (!curator) return err$3(hostError("e-302-curator-service-not-mounted"));
2313
+ const view = await curator.scopeView();
2314
+ const line = (label, names) => `${label}: ${names.length}${names.length === 0 ? "" : `\n ${names.join(", ")}`}`;
2315
+ return ok$4([
2316
+ `Lifecycle scope at ${(/* @__PURE__ */ new Date()).toISOString().slice(0, 10)}`,
2317
+ line("Managed (may transition)", view.managed),
2318
+ line("Watched (stale / quality-warned)", view.watched),
2319
+ line("Quality-warned", view.qualityWarned),
2320
+ line("Exempted (exclude / referenced)", view.exempted),
2321
+ line("Protected (pinned / bundled / hub / builtin)", view.protected)
2322
+ ].join("\n"));
2323
+ }
2324
+ if (input === "curator report") {
2325
+ const curator = ctx.get("evolutionCurator");
2326
+ if (!curator) return err$3(hostError("e-302-curator-service-not-mounted"));
2327
+ const report = await curator.latestReport();
2328
+ if (!report) return ok$4(hostCommandText(locale, "command.curator.noReport"));
2329
+ if (typeof report !== "object" || typeof report.runId !== "string" || typeof report.startedAt !== "string" || !Array.isArray(report.archived) || !Array.isArray(report.failed)) return err$3(hostCommandText(locale, "command.curator.reportReadFailed"));
2330
+ const reportAny = report;
2331
+ const nameOf = (item) => typeof item === "object" && item !== null && typeof item.name === "string" ? item.name : "?";
2332
+ const reasonOf = (item) => typeof item === "object" && item !== null && typeof item.reason === "string" ? item.reason : "?";
2333
+ const aborted = typeof reportAny.aborted === "string" ? reportAny.aborted : void 0;
2334
+ const unattributed = Array.isArray(reportAny.unattributed) ? reportAny.unattributed.length : 0;
2335
+ return ok$4([
2336
+ `runId=${reportAny.runId}`,
2337
+ `startedAt=${reportAny.startedAt}`,
2338
+ `archived=${reportAny.archived.map(nameOf).join(", ") || "(none)"}`,
2339
+ `failed=${reportAny.failed.map((item) => `${nameOf(item)}: ${reasonOf(item)}`).join(", ") || "(none)"}`,
2340
+ ...aborted === void 0 ? [] : [`aborted=${aborted}`],
2341
+ ...unattributed === 0 ? [] : [`unattributed=${unattributed}`]
2342
+ ].join("\n"));
2343
+ }
2344
+ }
2345
+ /** The read-only mutations log (separate command id, same curator service). */
2346
+ async function runMutationsCommand(context) {
2347
+ const { input, ctx, locale } = context;
2348
+ const hostError = (id, args = {}) => hostErrorText(locale, id, args);
2349
+ if (input === "mutations") {
2350
+ const curator = ctx.get("evolutionCurator");
2351
+ if (!curator) return err$3(hostError("e-302-curator-service-not-mounted"));
2352
+ const records = await curator.skills.listMutations();
2353
+ const usable = Array.isArray(records) ? records.filter((row) => typeof row === "object" && row !== null && typeof row.at === "string" && typeof row.skillName === "string" && typeof row.action === "string" && typeof row.summary === "string") : [];
2354
+ if (usable.length === 0) return ok$4("还没有写入记录。");
2355
+ const recent = usable.slice(-5).reverse().map((record) => `${record.at.slice(0, 19)} ${record.skillName} ${record.action} ${record.summary}`);
2356
+ return ok$4(`写入记录:已记录 ${usable.length} 条(最近 5 条):\n${recent.join("\n")}`);
2357
+ }
2358
+ }
1517
2359
  //#endregion
1518
2360
  //#region lib/types/platform-view.js
1519
2361
  /**
@@ -1680,9 +2522,8 @@ function moduleGraphPath(specifier) {
1680
2522
  * at THIS plane — a leftover profile from the other plane's home used to make the exclusion refuse a
1681
2523
  * legitimate install (the two-plane split made that reachable: `~/.dsh/profiles/web` sat next
1682
2524
  * to `profiles/desktop`). The directory is therefore read here and nowhere else:
1683
- * `scanProfiles` is the single `readdirSync` of it, `homeProfiles` answers the diagnostic
1684
- * question, and `installExclusionTarget` answers the write-path one — fail-closed, because an
1685
- * unreadable home must never read as "nothing is installed".
2525
+ * `scanProfiles` is the single `readdirSync` of it and `homeProfiles` answers the diagnostic
2526
+ * question — an unreadable home must never read as "nothing is installed".
1686
2527
  *
1687
2528
  * @module evolution-commands/src/profiles
1688
2529
  */
@@ -1727,7 +2568,7 @@ function scanProfiles(home) {
1727
2568
  }
1728
2569
  /** Every profile directory under one home, by name — the DIAGNOSTIC question (doctor's cross-profile
1729
2570
  * summary). An unreadable home answers the empty list here because doctor reports the failure on its
1730
- * own DEGRADED row; a write path must ask {@link installExclusionTarget} instead.
2571
+ * own DEGRADED row.
1731
2572
  * @param home - the resolved DSH home.
1732
2573
  * @returns one entry per profile directory carrying a manifest.
1733
2574
  */
@@ -2250,7 +3091,7 @@ async function diagnose(ctx, options = {}) {
2250
3091
  let pendingTtlMs = null;
2251
3092
  const approvalService = ctx.get("evolutionApproval");
2252
3093
  if (typeof approvalService?.ttlMs === "number" && Number.isFinite(approvalService.ttlMs)) pendingTtlMs = approvalService.ttlMs;
2253
- const approvalList = approvalService?.list?.bind(approvalService);
3094
+ const approvalList = (approvalService?.listReadonly ?? approvalService?.list)?.bind(approvalService);
2254
3095
  if (approvalList !== void 0) try {
2255
3096
  const pendingProbe = await probeBounded(() => approvalList("pending"), "approval pending listing");
2256
3097
  const rows = pendingProbe.ok ? pendingProbe.value : void 0;
@@ -2262,8 +3103,14 @@ async function diagnose(ctx, options = {}) {
2262
3103
  pendingCount = null;
2263
3104
  executingCount = null;
2264
3105
  }
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";
3106
+ const installForm = classifyInstallForm({
3107
+ full,
3108
+ preset,
3109
+ host,
3110
+ humanGated: ctx.get("evolutionApproval")?.isEnabled === true,
3111
+ layeredPreset: layered,
3112
+ presetDirInstalled
3113
+ });
2267
3114
  const mountConflicts = conflicts.filter((row) => !row.includes("DEGRADED"));
2268
3115
  const undecidable = mountConflicts.length !== conflicts.length;
2269
3116
  const scopedProbe = {
@@ -2290,7 +3137,7 @@ async function diagnose(ctx, options = {}) {
2290
3137
  const queryIssues = await sessionQueryIssues(ctx);
2291
3138
  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
3139
  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)");
3140
+ 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
3141
  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
3142
  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
3143
  for (const row of presetFreshness) {
@@ -2362,7 +3209,7 @@ async function mergeDoctorLine(ctx) {
2362
3209
  }
2363
3210
  /**
2364
3211
  * S2-12③ (FLOW5-4): the memory budget is configured in TWO places —
2365
- * `memory-files`' `memoryCharLimit`/`userCharLimit` (what the STORE enforces)
3212
+ * `memory-files`' `memoryChars`/`userChars` (what the STORE enforces)
2366
3213
  * and `evolution-policy`'s `memoryChars`/`userChars` (what the review PLANS
2367
3214
  * against; `memory-files` follows the policy only for an UNSET limit). A
2368
3215
  * disagreement therefore means an explicit contradiction, or a `memory-files`
@@ -2445,8 +3292,8 @@ function memoryBudgetIssues(ctx) {
2445
3292
  const policy = ctx.get("evolutionPolicy")?.get?.();
2446
3293
  if (budget === void 0 || policy === void 0) return [];
2447
3294
  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`);
3295
+ 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`);
3296
+ 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
3297
  return issues;
2451
3298
  }
2452
3299
  /** S0-4 (v43 G-1 / J-1): the scoped-row reconciliation line. The verdict is the
@@ -2544,488 +3391,253 @@ function renderDiagnosticsText(view, locale = "zh") {
2544
3391
  for (const fact of view.facts) lines.push(" - " + fact.label + ":" + fact.value + hostCommandText(locale, "doctor.source", { home: fact.home }));
2545
3392
  lines.push(hostCommandText(locale, "doctor.runtime"));
2546
3393
  for (const row of view.runtime) {
2547
- const status = hostCommandText(locale, "doctor.status." + row.status);
2548
- const detail = row.detail === void 0 ? "" : ":" + row.detail;
2549
- const remedy = row.remedy === void 0 ? "" : hostCommandText(locale, "doctor.nextStep") + row.remedy;
2550
- lines.push(" - [" + status + "] " + row.label + detail + remedy);
2551
- }
2552
- return lines.join("\n") + "\n";
2553
- }
2554
- //#endregion
2555
- //#region lib/types/params.js
2556
- /**
2557
- * `/evolution params` view (G4/S4.1): the registry joined with the settings
2558
- * surface, so one text answers "which parameters exist, who may write them, and
2559
- * did I already override this one".
2560
- *
2561
- * The join key is the OWNER PACKAGE: `settings.describe()` keys a section by the Loader
2562
- * entry id, which is the row id (core's `paramSettingsId` names that mapping), and reports
2563
- * that section's raw user section (a key's PRESENCE is the override) plus the resolved
2564
- * value. Everything here is pure; the command handler supplies the data.
2565
- * @module @lmzhen/dsh-evolution-commands/params
2566
- */
2567
- /**
2568
- * Join the registry with the settings surface.
2569
- *
2570
- * `user` means the raw user section carries this key; `deployment` means the
2571
- * owner's namespace is registered but the key is unset (so the row/policy value
2572
- * applies); `unregistered` means the owner package publishes no namespace at all
2573
- * (or is not mounted), which is the honest answer for a deployment-only face.
2574
- * The distinction matters: 'no user section' must never read as 'not overridden'
2575
- * for a namespace that failed to register.
2576
- * @param sections - namespace to surface view, from `settings.describe()`.
2577
- * @param entries - registry entries (defaults to the family registry).
2578
- * @returns one row per registry entry, in registry order.
2579
- */
2580
- function paramSurfaceRows(sections, entries = PARAM_EXPOSURE) {
2581
- return entries.map((entry) => {
2582
- const base = {
2583
- id: entry.id,
2584
- group: entry.group,
2585
- tier: entry.tier,
2586
- applies: entry.applies,
2587
- owner: entry.owner
2588
- };
2589
- const namespace = paramSettingsId(entry.owner);
2590
- const section = namespace === void 0 ? void 0 : sections.get(namespace);
2591
- if (section === void 0) return {
2592
- ...base,
2593
- source: "unregistered",
2594
- value: void 0
2595
- };
2596
- const user = section.user;
2597
- if (user !== void 0 && Object.hasOwn(user, entry.id)) return {
2598
- ...base,
2599
- source: "user",
2600
- value: user[entry.id]
2601
- };
2602
- return {
2603
- ...base,
2604
- source: "deployment",
2605
- value: section.value?.[entry.id]
2606
- };
2607
- });
2608
- }
2609
- /**
2610
- * The groups the registry actually carries, in registry order — the list an
2611
- * unknown `--group` value is answered with.
2612
- * @param entries - registry entries (defaults to the family registry).
2613
- * @returns distinct group names.
2614
- */
2615
- function paramGroups(entries = PARAM_EXPOSURE) {
2616
- return [...new Set(entries.map((entry) => entry.group))];
2617
- }
2618
- /** One cell: `—` when no face reports a value, JSON for arrays/objects. */
2619
- function renderValue(value) {
2620
- if (value === void 0) return "—";
2621
- if (typeof value === "string") return value;
2622
- return JSON.stringify(value);
2623
- }
2624
- const WIDE_CHAR = new RegExp("[" + [
2625
- "ᄀ-ᅟ",
2626
- "⺀-〾",
2627
- "ぁ-㏿",
2628
- "㐀-䶿",
2629
- "一-鿿",
2630
- "가-힣",
2631
- "豈-﫿",
2632
- "︰-﹯",
2633
- "＀-⦆",
2634
- "¢-₩"
2635
- ].join("") + "]");
2636
- /**
2637
- * Pad one cell to a display width, counting CJK characters as two columns.
2638
- * @param text - the cell text.
2639
- * @param columns - the target width in terminal columns.
2640
- * @returns the text plus at least one space, so columns never touch.
2641
- */
2642
- function pad(text, columns) {
2643
- let used = 0;
2644
- for (const char of text) used += WIDE_CHAR.test(char) ? 2 : 1;
2645
- return text + " ".repeat(Math.max(1, columns - used));
2646
- }
2647
- /** Settings timing, in the operator's words. */
2648
- const APPLIES_LABELS = Object.freeze({
2649
- live: "立即",
2650
- restart: "重启后",
2651
- none: "不生效"
2652
- });
2653
- /** Where a row's effective value comes from, in the operator's words. */
2654
- const SOURCE_LABELS = Object.freeze({
2655
- user: "我改过",
2656
- deployment: "默认",
2657
- unregistered: "不可改"
2658
- });
2659
- /** What the E-tiers mean, so the count line reads without the docs. */
2660
- const TIER_LEGEND = "档位:E0 固定/E1 只读/E2 安装时定/E3 你可改/E4 装完固化。";
2661
- /**
2662
- * The source column's word for one row (F-1).
2663
- *
2664
- * `unregistered` covers TWO different facts: the owner publishes no settings namespace (the value
2665
- * really cannot be written — E-315/E-316) and the settings service itself is missing (then whether
2666
- * the value could be written is UNKNOWN). Without a provider the column must not claim "不可改", or it
2667
- * contradicts the legend and the footer of the very same output.
2668
- * @param row - the row's surface facts.
2669
- * @param providerMounted - whether a settings provider answered.
2670
- * @returns the label for the source column.
2671
- */
2672
- function sourceLabel(row, providerMounted) {
2673
- const label = SOURCE_LABELS[row.source] ?? row.source;
2674
- return providerMounted || row.source !== "unregistered" ? label : "未知";
2675
- }
2676
- function renderParamRows(rows, options) {
2677
- const header = pad("参数", 36) + pad("分组", 12) + pad("档位", 6) + pad("生效", 8) + pad("来源", 10) + "当前值";
2678
- const body = rows.map((row) => pad(row.id, 36) + pad(PARAM_GROUP_LABELS[row.group], 12) + pad(row.tier, 6) + pad(APPLIES_LABELS[row.applies] ?? row.applies, 8) + pad(sourceLabel(row, options.providerMounted), 10) + renderValue(row.value));
2679
- const tiers = [
2680
- "E0",
2681
- "E1",
2682
- "E2",
2683
- "E3",
2684
- "E4"
2685
- ].map((tier) => `${tier} ${rows.filter((row) => row.tier === tier).length}`).join(" / ");
2686
- const userRows = rows.filter((row) => row.source === "user").length;
2687
- const counts = options.providerMounted ? `共 ${rows.length} 个参数:${tiers};你改过的:${userRows} 项。` : `共 ${rows.length} 个参数:${tiers};是否改过:未知(没有设置服务)。`;
2688
- const note = options.providerMounted ? "来源:我改过=你在设置里改的;默认=安装时的配置;不可改=该功能不提供用户可改项。" : "设置服务未挂载——读不到你改过的值,所以每行显示的都是安装时的配置(这不等于「你没改过」)。";
2689
- return [
2690
- counts,
2691
- "",
2692
- header,
2693
- ...body,
2694
- "",
2695
- TIER_LEGEND,
2696
- note
2697
- ].join("\n");
2698
- }
2699
- /**
2700
- * Render the rows as JSON for scripts (same fields, no formatting).
2701
- * @param rows - rows from {@link paramSurfaceRows}.
2702
- * @returns a JSON document with a `params` array.
2703
- */
2704
- function renderParamJson(rows) {
2705
- return JSON.stringify({ params: rows }, null, 2);
2706
- }
2707
- //#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 = [
2747
- {
2748
- readonly: false,
2749
- usage: "merge <subcommand> [<args>]",
2750
- summary: "技能自动合并(扫描/待批准/重跑/报告/撤销)"
2751
- },
2752
- {
2753
- readonly: true,
2754
- usage: "pending [--detail]",
2755
- summary: "列出暂存的写入(--detail 显示参数)"
2756
- },
2757
- {
2758
- readonly: false,
2759
- usage: "approve <id>",
2760
- summary: "执行一条已批准的写入"
2761
- },
2762
- {
2763
- readonly: false,
2764
- usage: "reject <id>",
2765
- summary: "丢弃一条暂存写入,不执行"
2766
- },
2767
- {
2768
- readonly: false,
2769
- usage: "release <id>",
2770
- summary: "把卡在执行中的写入放回待批窗口(先确认效果再批准或驳回)"
2771
- },
2772
- {
2773
- readonly: true,
2774
- usage: "doctor [--json]",
2775
- summary: "只读自检:安装形态、冲突、环境、服务(--json 供脚本用)"
2776
- },
2777
- {
2778
- readonly: false,
2779
- usage: "curator run|pause|resume|status|report|scope",
2780
- summary: "立即运行一次自动整理,或暂停/恢复/查看状态"
2781
- },
2782
- {
2783
- readonly: true,
2784
- usage: "mutations",
2785
- summary: "列出技能改动记录"
2786
- },
2787
- {
2788
- readonly: false,
2789
- usage: "restore",
2790
- summary: "从最近的快照恢复技能"
2791
- },
2792
- {
2793
- readonly: false,
2794
- usage: "skill restore <name>",
2795
- summary: "按名字恢复一个已归档的技能"
2796
- },
2797
- {
2798
- readonly: true,
2799
- usage: "skill history <name>",
2800
- summary: "列出某个技能的内容版本(含时间、动作、字符数、哈希前缀)"
2801
- },
2802
- {
2803
- readonly: false,
2804
- usage: "skill undo <name> [--to v<N>]",
2805
- summary: "把某个技能的内容回退到某一版(默认上一版;只动内容,撤销本身也记为一版)"
2806
- },
2807
- {
2808
- readonly: false,
2809
- usage: "skill pin <name>",
2810
- summary: "钉住一个技能:免于删除、后台审查与生命周期整理(立即生效、随时可解钉;与 skill_manage 的 pin 动作同一语义,不走审批)"
2811
- },
2812
- {
2813
- readonly: false,
2814
- usage: "skill unpin <name>",
2815
- summary: "解钉一个技能:撤销上面的冻结(立即生效、不走审批)"
2816
- },
2817
- {
2818
- readonly: false,
2819
- usage: "propose",
2820
- summary: "为 body-oversize 技能写 keep 提议(不自动拆分;同一 reports store)"
2821
- },
2822
- {
2823
- readonly: true,
2824
- usage: "skills health",
2825
- summary: "技能库结构体检"
2826
- },
2827
- {
2828
- readonly: false,
2829
- usage: "skills refresh",
2830
- summary: "丢弃目录缓存并重新读取技能树"
2831
- },
2832
- {
2833
- readonly: false,
2834
- usage: "learn [request]",
2835
- summary: "向本会话发一条学习请求"
2836
- },
2837
- {
2838
- readonly: false,
2839
- usage: "maintain [--timeout=<ms> | --facts]",
2840
- summary: "起一次维护扫描并立即回 run id(后台跑;--facts 为 0 token 预览)"
2841
- },
2842
- {
2843
- readonly: true,
2844
- usage: "maintain status [<id>]",
2845
- summary: "看维护扫描:在飞的那次(含已跑多久)或某个 run 的终态"
2846
- },
2847
- {
2848
- readonly: true,
2849
- usage: "maintain report [<id>]",
2850
- summary: "读某个 run 的结果正文(省略 id 取本 home 最新一条;没有结果就明说,不装成空结果)"
2851
- },
2852
- {
2853
- readonly: false,
2854
- usage: "maintain handoff [<id>]",
2855
- summary: "把某次维护报告交给模型:注入指针与汇报协议,模型只汇报、等你确认后再动手"
2856
- },
2857
- {
2858
- readonly: false,
2859
- usage: "maintain cancel [<id>]",
2860
- summary: "停掉在飞的那次维护扫描(省略 id 仅当最新一条是本进程在跑的那次)"
2861
- },
2862
- {
2863
- readonly: true,
2864
- usage: "params [--group <name>] [--json]",
2865
- summary: "列出全部参数:分组、档位、生效时机、来源与当前值(--json 便于脚本处理)"
2866
- },
2867
- {
2868
- readonly: false,
2869
- usage: "restructure <name> \"<heading>\" <to_file> [--plan <runId>]",
2870
- summary: "把技能正文的一节移到 references 文件"
2871
- },
2872
- {
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 才写(多根一次事务)"
2876
- },
2877
- {
2878
- readonly: true,
2879
- usage: "replay",
2880
- summary: "比较不同会话与重启之间的计划结果(从活动记录回填)"
2881
- }
2882
- ];
2883
- /** The input-declaration hint (single line, ` | `-separated). */
2884
- function renderHint() {
2885
- return COMMAND_ENTRIES.map((entry) => entry.usage).join(" | ");
2886
- }
2887
- /** The bare `/evolution` help body (one line per subcommand). */
2888
- function renderHelpText(locale = "zh") {
2889
- return [
2890
- (HOST_COMMANDS["help.subcommands"][locale] ?? HOST_COMMANDS["help.subcommands"].en).replace("{count}", String(COMMAND_ENTRIES.length)),
2891
- "",
2892
- ...COMMAND_ENTRIES.map((entry) => ` ${entry.usage.padEnd(44)} ${HOST_COMMANDS["summary." + entryName(entry)]?.[locale] ?? entry.summary}`)
2893
- ].join("\n");
2894
- }
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
- }
3394
+ const status = hostCommandText(locale, "doctor.status." + row.status);
3395
+ const detail = row.detail === void 0 ? "" : ":" + row.detail;
3396
+ const remedy = row.remedy === void 0 ? "" : hostCommandText(locale, "doctor.nextStep") + row.remedy;
3397
+ lines.push(" - [" + status + "] " + row.label + detail + remedy);
2916
3398
  }
2917
- return found;
3399
+ return lines.join("\n") + "\n";
2918
3400
  }
2919
- /** Union of every usage's value flags (the parse table's ONE source). */
2920
- const VALUE_FLAGS = (() => {
2921
- const names = [];
2922
- for (const entry of COMMAND_ENTRIES) for (const name of entryValueFlags(entry)) if (!names.includes(name)) names.push(name);
2923
- return names;
2924
- })();
2925
3401
  //#endregion
2926
- //#region lib/types/parse.js
3402
+ //#region lib/types/host-commands/doctor-command.js
3403
+ const ok$3 = (text) => ({
3404
+ kind: "success",
3405
+ text
3406
+ });
2927
3407
  /**
2928
- * Narrow a parse result: true when it is the syntax failure rather than a command.
2929
- * @param result - what {@link parseSubcommand} answered.
2930
- * @returns whether the line was refused.
3408
+ * Render the doctor report for the bare and --json forms.
3409
+ * @param context - raw input, plugin context, run counts and locale.
3410
+ * @returns the report, or undefined for a different command.
2931
3411
  */
2932
- function isParseFailure(result) {
2933
- return result.kind !== void 0;
3412
+ async function runDoctorCommand(context) {
3413
+ const { input, ctx, runs, locale } = context;
3414
+ if (input !== "doctor" && input !== "doctor --json") return void 0;
3415
+ const mountedForDoctor = presetProfileTarget(ctx);
3416
+ const mounted = mountedForDoctor === void 0 ? {} : { mounted: {
3417
+ profile: mountedForDoctor.profile,
3418
+ dir: mountedForDoctor.profileDir,
3419
+ bundles: mountedForDoctor.bundles
3420
+ } };
3421
+ const report = await diagnose(ctx, {
3422
+ home: evolutionRoot(),
3423
+ ...mounted,
3424
+ runs: runs()
3425
+ });
3426
+ if (input === "doctor --json") return ok$3(JSON.stringify(report, null, 2));
3427
+ return ok$3(renderDoctorText(report, locale));
2934
3428
  }
2935
- /**
2936
- * Split a command line into tokens: whitespace separates, and a double-quoted run is ONE token with its
2937
- * quotes removed (the `restructure <name> "<heading>" <to_file>` form needs that; the old regexes each
2938
- * carried their own quoting rule).
2939
- * @param input - the text after `/evolution`.
2940
- * @returns the tokens, in order.
2941
- */
2942
- function tokenize(input) {
2943
- const tokens = [];
2944
- let current = "";
2945
- let quoted = false;
2946
- for (const char of input.trim()) {
2947
- if (char === String.fromCharCode(34)) {
2948
- quoted = !quoted;
2949
- continue;
2950
- }
2951
- if (!quoted && /\s/.test(char)) {
2952
- if (current !== "") {
2953
- tokens.push(current);
2954
- current = "";
2955
- }
2956
- continue;
2957
- }
2958
- current += char;
3429
+ //#endregion
3430
+ //#region lib/types/host-commands/restore-commands.js
3431
+ const ok$2 = (text) => ({
3432
+ kind: "success",
3433
+ text
3434
+ });
3435
+ const err$2 = (text) => ({
3436
+ kind: "error",
3437
+ text
3438
+ });
3439
+ const hostError$2 = (locale, id, args = {}) => hostErrorText(locale, id, args);
3440
+ /** The whole-tree restore. A tail is refused so a missing `skill ` prefix cannot roll back everything. */
3441
+ async function runRestoreCommand(context) {
3442
+ const { input, ctx, locale, refusal } = context;
3443
+ if (input !== "restore" && !input.startsWith("restore ")) return void 0;
3444
+ const tail = input.slice(7).trim();
3445
+ if (tail !== "") return err$2(`\`restore\` 不接受参数(收到 "${tail}")。\`restore\` 做整树回滚,\`skill restore <name>\` 恢复单个技能。`);
3446
+ const blocked = refusal("restore");
3447
+ if (blocked !== void 0) return blocked;
3448
+ const curator = ctx.get("evolutionCurator");
3449
+ if (curator === void 0) return err$2(hostError$2(locale, "e-302-curator-service-not-mounted"));
3450
+ const outcome = await curator.restoreSnapshot();
3451
+ return outcome.ok ? ok$2(outcome.message) : err$2(outcome.message);
3452
+ }
3453
+ /** One skill restore. */
3454
+ async function runSkillRestoreCommand(context) {
3455
+ const { input, ctx, locale, refusal } = context;
3456
+ if (!input.startsWith("skill restore ")) return void 0;
3457
+ const name = input.slice(14).trim();
3458
+ if (!name) return err$2("用法:/evolution skill restore <name>");
3459
+ const blocked = refusal("skill restore");
3460
+ if (blocked !== void 0) return blocked;
3461
+ const curator = ctx.get("evolutionCurator");
3462
+ if (curator === void 0) return err$2(hostError$2(locale, "e-302-curator-service-not-mounted"));
3463
+ const result = await curator.restore(name);
3464
+ return result.ok ? ok$2(result.message) : err$2(result.message);
3465
+ }
3466
+ //#endregion
3467
+ //#region lib/types/host-commands/skill-history-commands.js
3468
+ const ok$1 = (text) => ({
3469
+ kind: "success",
3470
+ text
3471
+ });
3472
+ const err$1 = (text) => ({
3473
+ kind: "error",
3474
+ text
3475
+ });
3476
+ const hostError$1 = (locale, id) => hostErrorText(locale, id);
3477
+ /** `skill history <name>`: content versions and support-file versions, kept apart. */
3478
+ async function runSkillHistoryCommand(context) {
3479
+ const { input, ctx, locale } = context;
3480
+ if (!input.startsWith("skill history ")) return void 0;
3481
+ const name = input.slice(14).trim();
3482
+ if (!name) return err$1("用法:/evolution skill history <name>");
3483
+ const curator = ctx.get("evolutionCurator");
3484
+ if (!curator) return err$1(hostError$1(locale, "e-302-curator-service-not-mounted"));
3485
+ const versions = await curator.history(name);
3486
+ if (versions.length === 0) return ok$1(`技能 "${name}" 还没有内容版本:下一次经 skill_manage 写入后才会出现。`);
3487
+ 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}`}`;
3489
+ const lines = [`技能 "${name}" 的内容版本(由旧到新,${groups.content.length} 条,最多保留这么多):`, ...groups.content.map(row)];
3490
+ if (groups.support.length > 0) lines.push("支撑文件版本(仅在历史里 —— 撤销恢复的是 SKILL.md,不是这些字节):", ...groups.support.map(row));
3491
+ return ok$1(lines.join("\n"));
3492
+ }
3493
+ /** `skill undo <name> [--to vN | --unit <id>]`. */
3494
+ async function runSkillUndoCommand(context) {
3495
+ const { input, ctx, locale, refusal } = context;
3496
+ if (!input.startsWith("skill undo ")) return void 0;
3497
+ const rest = input.slice(11).trim();
3498
+ const toMatch = /--to\s+v?(\d+)/.exec(rest);
3499
+ const unitMatch = /--unit\s+(\S+)/.exec(rest);
3500
+ const marker = [toMatch?.index, unitMatch?.index].filter((index) => index !== void 0).sort((a, b) => a - b)[0];
3501
+ const name = (marker === void 0 ? rest : rest.slice(0, marker)).trim();
3502
+ if (!name) return err$1("用法:/evolution skill undo <name> [--to v<N> | --unit <id>]");
3503
+ if (toMatch !== null && unitMatch !== null) return err$1("--to 与 --unit 不能同时使用");
3504
+ const blocked = refusal("skill undo");
3505
+ if (blocked !== void 0) return blocked;
3506
+ const curator = ctx.get("evolutionCurator");
3507
+ const target = toMatch?.[1] === void 0 ? void 0 : Number(toMatch[1]);
3508
+ const unitId = unitMatch?.[1];
3509
+ const result = curator === void 0 ? {
3510
+ ok: false,
3511
+ message: hostError$1(locale, "e-302-curator-service-not-mounted")
3512
+ } : unitId !== void 0 ? await curator.undoUnit(name, unitId) : target === void 0 ? await curator.undo(name) : await curator.undo(name, target);
3513
+ return result.ok ? ok$1(result.message) : err$1(result.message);
3514
+ }
3515
+ //#endregion
3516
+ //#region lib/types/host-commands/approval-commands.js
3517
+ const ok = (text) => ({
3518
+ kind: "success",
3519
+ text
3520
+ });
3521
+ const err = (text) => ({
3522
+ kind: "error",
3523
+ text
3524
+ });
3525
+ const hostError = (locale, id, args = {}) => hostErrorText(locale, id, args);
3526
+ /** Render a staged args payload without ever letting the pending surface crash. */
3527
+ function safeStagedArgs(args) {
3528
+ try {
3529
+ const json = JSON.stringify(args);
3530
+ if (typeof json !== "string") return "(unserializable)";
3531
+ if (json.length > 500) return `${json.slice(0, 500)}…(truncated ${json.length - 500} chars)`;
3532
+ return json;
3533
+ } catch {
3534
+ return "(unserializable)";
2959
3535
  }
2960
- if (current !== "") tokens.push(current);
2961
- return tokens;
2962
3536
  }
2963
3537
  /**
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.
3538
+ * The pending window, including the executing rows and the TTL note.
3539
+ * @param context - approval service, command shape and locale.
3540
+ * @returns the rendered window or the service error.
2974
3541
  */
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;
3542
+ async function runPendingCommand(context) {
3543
+ const { approval, command, locale } = context;
3544
+ if (!approval) return err(hostError(locale, "e-301-approval-service-not-mounted"));
3545
+ const listed = [...await approval.list("pending"), ...await approval.list("executing")];
3546
+ const pending = [...new Map(listed.map((row) => [row.id, row])).values()];
3547
+ const ttlMs = typeof approval.ttlMs === "number" && Number.isFinite(approval.ttlMs) ? approval.ttlMs : 0;
3548
+ const ttlNote = ttlMs > 0 ? hostCommandText(locale, "command.pending.ttl", { ttl: ttlMs }) : hostCommandText(locale, "command.pending.neverExpires");
3549
+ if (pending.length === 0) return ok(hostCommandText(locale, "command.pending.empty") + ttlNote);
3550
+ const detailed = command.flags.get("detail") === true;
3551
+ const nowMs = Date.now();
3552
+ const attribution = (p) => {
3553
+ const age = elapsedSince(p.createdAt, nowMs);
3554
+ const unit = age.n === 1 ? age.unit.replace(/s$/u, "") : age.unit;
3555
+ return ` · ${age.unit === "now" ? hostCommandText(locale, "command.pending.justNow") : hostCommandText(locale, "command.pending.ago", {
3556
+ n: age.n,
3557
+ unit
3558
+ })}${p.origin === void 0 ? "" : hostCommandText(locale, "command.pending.from", { origin: p.origin })}${p.sessionId === void 0 ? "" : hostCommandText(locale, "command.pending.session", { session: p.sessionId.slice(0, 8) })}`;
3559
+ };
3560
+ return ok(pending.map((p) => {
3561
+ if (!detailed) return `${p.id} ${p.kind} ${p.status === "executing" ? hostCommandText(locale, "command.pending.executing") + " " : ""}${p.summary}${attribution(p)}`;
3562
+ const status = p.status === "executing" ? hostCommandText(locale, "command.pending.executing") : p.status;
3563
+ const line = `${p.id} ${p.kind} ${status} ${p.summary}${attribution(p)}`;
3564
+ return p.args === void 0 ? line : `${line}\n` + hostCommandText(locale, "command.pending.stagedArgs", { args: safeStagedArgs(p.args) });
3565
+ }).join("\n") + (pending.some((p) => p.status === "executing") ? hostCommandText(locale, "command.pending.executingHint") : "") + ttlNote);
2981
3566
  }
2982
3567
  /**
2983
- * Parse one command line into its name, flags and positionals.
2984
- * @param input - the text after `/evolution`.
2985
- * @returns the parsed command, or the syntax failure that refused it.
3568
+ * One decision verb: approve, reject or release, with the service-unavailable posture of each.
3569
+ * @param verb - the decision.
3570
+ * @param id - the staged record id.
3571
+ * @param context - approval service and locale.
3572
+ * @returns the service message as success or error.
2986
3573
  */
2987
- function parseSubcommand(input) {
2988
- const [first, ...rest] = tokenize(input);
2989
- if (first === void 0) return {
2990
- kind: "unknown-subcommand",
2991
- name: ""
2992
- };
2993
- const name = first.toLowerCase();
2994
- const flags = /* @__PURE__ */ new Map();
2995
- const positionals = [];
2996
- for (let index = 0; index < rest.length; index += 1) {
2997
- const token = rest[index];
2998
- if (token === void 0) continue;
2999
- if (!token.startsWith("--")) {
3000
- positionals.push(token);
3001
- continue;
3002
- }
3003
- const equals = token.indexOf("=");
3004
- const flag = (equals < 0 ? token : token.slice(0, equals)).slice(2);
3005
- if (equals >= 0) {
3006
- flags.set(flag, token.slice(equals + 1));
3007
- continue;
3008
- }
3009
- if (!VALUE_FLAGS.includes(flag)) {
3010
- flags.set(flag, true);
3011
- continue;
3012
- }
3013
- const next = rest[index + 1];
3014
- if (next === void 0 || next.startsWith("--")) return {
3015
- kind: "missing-value",
3016
- name,
3017
- flag
3018
- };
3019
- flags.set(flag, next);
3020
- index += 1;
3574
+ async function runDecisionCommand(verb, id, context) {
3575
+ const { approval, locale } = context;
3576
+ if (!approval) return err(hostError(locale, "e-301-approval-service-not-mounted-2"));
3577
+ if (verb === "release") {
3578
+ if (!approval.release) return err(hostError(locale, "e-304-the-mounted-approval-service"));
3579
+ const result = await approval.release(id);
3580
+ return result.ok ? ok(result.message) : err(result.message);
3021
3581
  }
3022
- return {
3023
- name,
3024
- flags,
3025
- positionals
3026
- };
3582
+ const result = await approval[verb](id);
3583
+ return result.ok ? ok(result.message) : err(result.message);
3027
3584
  }
3028
3585
  //#endregion
3586
+ //#region lib/types/host-commands/handlers.js
3587
+ const isPendingShape = (command) => command.positionals.length === 0 && [...command.flags.keys()].every((flag) => flag === "detail");
3588
+ const isParamsShape = (command) => command.positionals.length === 0 && [...command.flags.keys()].every((flag) => flag === "group" || flag === "json");
3589
+ const HOST_COMMAND_HANDLERS = {
3590
+ pending: (context) => isPendingShape(context.command) ? runPendingCommand(context) : void 0,
3591
+ approve: (context) => context.input.startsWith("approve ") ? runDecisionCommand("approve", context.input.slice(8).trim(), context) : void 0,
3592
+ reject: (context) => context.input.startsWith("reject ") ? runDecisionCommand("reject", context.input.slice(7).trim(), context) : void 0,
3593
+ release: (context) => context.input.startsWith("release ") ? runDecisionCommand("release", context.input.slice(8).trim(), context) : void 0,
3594
+ params: (context) => isParamsShape(context.command) ? runParamsCommand({
3595
+ command: context.command,
3596
+ provider: context.provider,
3597
+ locale: context.locale
3598
+ }) : void 0,
3599
+ curator: (context) => context.ctx === void 0 ? void 0 : runCuratorCommand({
3600
+ input: context.input,
3601
+ ctx: context.ctx,
3602
+ locale: context.locale
3603
+ }),
3604
+ mutations: (context) => context.ctx === void 0 ? void 0 : runMutationsCommand({
3605
+ input: context.input,
3606
+ ctx: context.ctx,
3607
+ locale: context.locale
3608
+ }),
3609
+ doctor: (context) => context.ctx === void 0 || context.runs === void 0 ? void 0 : runDoctorCommand({
3610
+ input: context.input,
3611
+ ctx: context.ctx,
3612
+ runs: context.runs,
3613
+ locale: context.locale
3614
+ }),
3615
+ restore: (context) => context.ctx === void 0 || context.refusal === void 0 ? void 0 : runRestoreCommand({
3616
+ input: context.input,
3617
+ ctx: context.ctx,
3618
+ locale: context.locale,
3619
+ refusal: context.refusal
3620
+ }),
3621
+ "skill.restore": (context) => context.ctx === void 0 || context.refusal === void 0 ? void 0 : runSkillRestoreCommand({
3622
+ input: context.input,
3623
+ ctx: context.ctx,
3624
+ locale: context.locale,
3625
+ refusal: context.refusal
3626
+ }),
3627
+ "skill.history": (context) => context.ctx === void 0 || context.refusal === void 0 ? void 0 : runSkillHistoryCommand({
3628
+ input: context.input,
3629
+ ctx: context.ctx,
3630
+ locale: context.locale,
3631
+ refusal: context.refusal
3632
+ }),
3633
+ "skill.undo": (context) => context.ctx === void 0 || context.refusal === void 0 ? void 0 : runSkillUndoCommand({
3634
+ input: context.input,
3635
+ ctx: context.ctx,
3636
+ locale: context.locale,
3637
+ refusal: context.refusal
3638
+ })
3639
+ };
3640
+ //#endregion
3029
3641
  //#region lib/types/command-catalog.js
3030
3642
  function buildSurface(defs, prefix) {
3031
3643
  const defaults = (def) => Object.fromEntries(def.flags.flatMap((flag) => {
@@ -3057,23 +3669,26 @@ function buildSurface(defs, prefix) {
3057
3669
  };
3058
3670
  }
3059
3671
  function parseCommand(defs, argv) {
3060
- const [verb, ...rest] = argv;
3672
+ const verb = argv[0];
3061
3673
  if (verb === void 0 || verb === "help" || verb === "--help" || verb === "-h") return {
3062
3674
  ok: true,
3063
3675
  id: "help",
3064
3676
  values: {},
3065
3677
  help: true
3066
3678
  };
3067
- const candidates = defs.filter((item) => item.words.includes(verb));
3068
- const def = candidates.find((item) => rest.filter((token) => token.startsWith("--")).every((token) => {
3679
+ const candidates = defs.filter((item) => item.words.length > 0 && item.words.every((word, index) => argv[index] === word));
3680
+ const restOf = (item) => argv.slice(item.words.length);
3681
+ const ordered = [...candidates].sort((left, right) => right.words.length - left.words.length);
3682
+ const def = ordered.find((item) => restOf(item).filter((token) => token.startsWith("--")).every((token) => {
3069
3683
  const name = token.slice(2).split("=")[0] ?? "";
3070
3684
  return item.flags.some((flag) => flag.name === name);
3071
- })) ?? candidates[0];
3685
+ })) ?? ordered[0];
3072
3686
  if (def === void 0) return {
3073
3687
  ok: false,
3074
3688
  code: "usage",
3075
3689
  message: "unknown command: " + verb
3076
3690
  };
3691
+ const rest = restOf(def);
3077
3692
  const values = {};
3078
3693
  const positional = [];
3079
3694
  for (let index = 0; index < rest.length; index += 1) {
@@ -3373,12 +3988,6 @@ function apply(ctx, rawConfig = {}) {
3373
3988
  });
3374
3989
  const hostLocale = resolveHostLocale(ctx);
3375
3990
  const hostError = (id, args = {}) => hostErrorText(hostLocale, id, args);
3376
- if (input === "merge" || input.startsWith("merge ")) {
3377
- const merge = ctx.get("evolutionMerge");
3378
- if (merge === void 0) return err("merge 未挂载:当前安装形态没有 evolution-merge 行(安装形态与命令可用性见 INSTALL.md),或先运行 /evolution doctor。");
3379
- const result = await merge.run(rawInputTrimmed, { agent: invocation.agent });
3380
- return result.ok ? ok(result.text) : err(result.text);
3381
- }
3382
3991
  const invocationAgent = invocation.agent;
3383
3992
  const agentMissing = (need) => invocationAgent === void 0 ? err(hostError("e-305-this-invocation-carries-no", { a1: need })) : void 0;
3384
3993
  const unreplayableWriteRefusal = (what) => {
@@ -3389,766 +3998,595 @@ function apply(ctx, rawConfig = {}) {
3389
3998
  return err(hostError("e-306-this-deployment-stages-foreground", { a1: what }));
3390
3999
  };
3391
4000
  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")) {
3394
- if (!approval) return err(hostError("e-301-approval-service-not-mounted"));
3395
- const listed = [...await approval.list("pending"), ...await approval.list("executing")];
3396
- const pending = [...new Map(listed.map((row) => [row.id, row])).values()];
3397
- const ttlMs = typeof approval.ttlMs === "number" && Number.isFinite(approval.ttlMs) ? approval.ttlMs : 0;
3398
- const ttlNote = ttlMs > 0 ? hostCommandText(hostLocale, "command.pending.ttl", { ttl: ttlMs }) : hostCommandText(hostLocale, "command.pending.neverExpires");
3399
- if (pending.length === 0) return ok(hostCommandText(hostLocale, "command.pending.empty") + ttlNote);
3400
- const detailed = pendingParsed.flags.get("detail") === true;
3401
- const nowMs = Date.now();
3402
- const attribution = (p) => {
3403
- const age = elapsedSince(p.createdAt, nowMs);
3404
- const unit = age.n === 1 ? age.unit.replace(/s$/u, "") : age.unit;
3405
- return ` · ${age.unit === "now" ? hostCommandText(hostLocale, "command.pending.justNow") : hostCommandText(hostLocale, "command.pending.ago", {
3406
- n: age.n,
3407
- unit
3408
- })}${p.origin === void 0 ? "" : hostCommandText(hostLocale, "command.pending.from", { origin: p.origin })}${p.sessionId === void 0 ? "" : hostCommandText(hostLocale, "command.pending.session", { session: p.sessionId.slice(0, 8) })}`;
3409
- };
3410
- return ok(pending.map((p) => {
3411
- if (!detailed) return `${p.id} ${p.kind} ${p.status === "executing" ? hostCommandText(hostLocale, "command.pending.executing") + " " : ""}${p.summary}${attribution(p)}`;
3412
- const status = p.status === "executing" ? hostCommandText(hostLocale, "command.pending.executing") : p.status;
3413
- const line = `${p.id} ${p.kind} ${status} ${p.summary}${attribution(p)}`;
3414
- return p.args === void 0 ? line : `${line}\n` + hostCommandText(hostLocale, "command.pending.stagedArgs", { args: safeStagedArgs(p.args) });
3415
- }).join("\n") + (pending.some((p) => p.status === "executing") ? hostCommandText(hostLocale, "command.pending.executingHint") : "") + ttlNote);
3416
- }
3417
- if (input.startsWith("approve ")) {
3418
- const id = input.slice(8).trim();
3419
- const result = approval ? await approval.approve(id) : {
3420
- ok: false,
3421
- message: hostError("e-301-approval-service-not-mounted-2")
3422
- };
3423
- return result.ok ? ok(result.message) : err(result.message);
3424
- }
3425
- if (input.startsWith("reject ")) {
3426
- const id = input.slice(7).trim();
3427
- const result = approval ? await approval.reject(id) : {
3428
- ok: false,
3429
- message: hostError("e-301-approval-service-not-mounted-2")
3430
- };
3431
- return result.ok ? ok(result.message) : err(result.message);
3432
- }
3433
- if (input.startsWith("release ")) {
3434
- const id = input.slice(8).trim();
3435
- if (!approval) return err(hostError("e-301-approval-service-not-mounted-2"));
3436
- if (!approval.release) return err(hostError("e-304-the-mounted-approval-service"));
3437
- const result = await approval.release(id);
3438
- return result.ok ? ok(result.message) : err(result.message);
3439
- }
3440
- if (input === "curator run") {
3441
- const curator = ctx.get("evolutionCurator");
3442
- if (!curator) return err(hostError("e-302-curator-service-not-mounted"));
3443
- const result = await curator.run({ ignoreGates: true });
3444
- if (result.skipped !== void 0) return ok(hostCommandText(hostLocale, "command.curator.skipped", {
3445
- reason: result.skipped,
3446
- runId: result.report.runId
3447
- }));
3448
- return ok(hostCommandText(hostLocale, "command.curator.done", {
3449
- stale: result.stale.length,
3450
- archived: result.archived.length,
3451
- errors: result.errors.length,
3452
- runId: result.report.runId,
3453
- snapshot: result.report.snapshotPath ? `\nsnapshot=${result.report.snapshotPath}` : ""
3454
- }));
3455
- }
3456
- if (input === "curator pause" || input === "curator resume") {
3457
- const curator = ctx.get("evolutionCurator");
3458
- if (!curator) return err(hostError("e-302-curator-service-not-mounted"));
3459
- const paused = input === "curator pause";
3460
- await curator.setPaused(paused);
3461
- const notPersisted = ctx.get("evolutionState") !== void 0 ? "" : hostCommandText(hostLocale, "command.curator.notPersisted");
3462
- return ok((paused ? hostCommandText(hostLocale, "command.curator.paused") : hostCommandText(hostLocale, "command.curator.resumed")) + notPersisted);
3463
- }
3464
- if (input === "curator status") {
3465
- const curator = ctx.get("evolutionCurator");
3466
- if (!curator) return err(hostError("e-302-curator-service-not-mounted"));
3467
- const state = await curator.status();
3468
- if (!state) return ok(hostCommandText(hostLocale, "command.curator.noState"));
3469
- const lastRun = typeof state.lastRunAt === "number" && Number.isFinite(state.lastRunAt) && state.lastRunAt > 0 ? new Date(state.lastRunAt).toISOString() : "unknown";
3470
- return ok([
3471
- `paused=${state.paused}`,
3472
- `runs=${state.runCount}`,
3473
- `lastRun=${lastRun}`,
3474
- `summary=${state.lastSummary}`
3475
- ].join("\n"));
3476
- }
3477
- if (input === "mutations") {
3478
- const curator = ctx.get("evolutionCurator");
3479
- if (!curator) return err(hostError("e-302-curator-service-not-mounted"));
3480
- const records = await curator.skills.listMutations();
3481
- const usable = Array.isArray(records) ? records.filter((row) => typeof row === "object" && row !== null && typeof row.at === "string" && typeof row.skillName === "string" && typeof row.action === "string" && typeof row.summary === "string") : [];
3482
- if (usable.length === 0) return ok("还没有写入记录。");
3483
- const recent = usable.slice(-5).reverse().map((record) => `${record.at.slice(0, 19)} ${record.skillName} ${record.action} ${record.summary}`);
3484
- return ok(`写入记录:已记录 ${usable.length} 条(最近 5 条):\n${recent.join("\n")}`);
3485
- }
3486
- if (input === "curator scope") {
3487
- const curator = ctx.get("evolutionCurator");
3488
- if (!curator) return err(hostError("e-302-curator-service-not-mounted"));
3489
- const view = await curator.scopeView();
3490
- const line = (label, names) => `${label}: ${names.length}${names.length === 0 ? "" : `\n ${names.join(", ")}`}`;
3491
- return ok([
3492
- `Lifecycle scope at ${(/* @__PURE__ */ new Date()).toISOString().slice(0, 10)}`,
3493
- line("Managed (may transition)", view.managed),
3494
- line("Watched (stale / quality-warned)", view.watched),
3495
- line("Quality-warned", view.qualityWarned),
3496
- line("Exempted (exclude / referenced)", view.exempted),
3497
- line("Protected (pinned / bundled / hub / builtin)", view.protected)
3498
- ].join("\n"));
3499
- }
3500
- if (input === "curator report") {
3501
- const curator = ctx.get("evolutionCurator");
3502
- if (!curator) return err(hostError("e-302-curator-service-not-mounted"));
3503
- const report = await curator.latestReport();
3504
- if (!report) return ok(hostCommandText(hostLocale, "command.curator.noReport"));
3505
- if (typeof report !== "object" || typeof report.runId !== "string" || typeof report.startedAt !== "string" || !Array.isArray(report.archived) || !Array.isArray(report.failed)) return err(hostCommandText(hostLocale, "command.curator.reportReadFailed"));
3506
- const reportAny = report;
3507
- const nameOf = (item) => typeof item === "object" && item !== null && typeof item.name === "string" ? item.name : "?";
3508
- const reasonOf = (item) => typeof item === "object" && item !== null && typeof item.reason === "string" ? item.reason : "?";
3509
- const aborted = typeof reportAny.aborted === "string" ? reportAny.aborted : void 0;
3510
- const unattributed = Array.isArray(reportAny.unattributed) ? reportAny.unattributed.length : 0;
3511
- return ok([
3512
- `runId=${reportAny.runId}`,
3513
- `startedAt=${reportAny.startedAt}`,
3514
- `archived=${reportAny.archived.map(nameOf).join(", ") || "(none)"}`,
3515
- `failed=${reportAny.failed.map((item) => `${nameOf(item)}: ${reasonOf(item)}`).join(", ") || "(none)"}`,
3516
- ...aborted === void 0 ? [] : [`aborted=${aborted}`],
3517
- ...unattributed === 0 ? [] : [`unattributed=${unattributed}`]
3518
- ].join("\n"));
3519
- }
3520
- if (input === "restore" || input.startsWith("restore ")) {
3521
- const tail = input.slice(7).trim();
3522
- if (tail !== "") return err(`\`restore\` 不接受参数(收到 "${tail}")。\`restore\` 做整树回滚,\`skill restore <name>\` 恢复单个技能。`);
3523
- const restoreRefusal = unreplayableWriteRefusal("restore");
3524
- if (restoreRefusal) return restoreRefusal;
3525
- const curator = ctx.get("evolutionCurator");
3526
- const result = curator ? await curator.restoreSnapshot() : {
3527
- ok: false,
3528
- message: hostError("e-302-curator-service-not-mounted")
3529
- };
3530
- return result.ok ? ok(result.message) : err(result.message);
3531
- }
3532
- if (input === "consolidate" || input.startsWith("consolidate ")) {
3533
- const plan = /--plan\s+(\S+)/.exec(input)?.[1];
3534
- return err("`consolidate` 已退出用户面:机械追加由 curator 归档收尾,人类合成用 `/evolution merge pair <a> <b>`。" + (plan === void 0 ? "" : "\n旧 --plan 审计只读保留:" + plan));
3535
- }
3536
- if (input.startsWith("skill restore ")) {
3537
- const name = input.slice(14).trim();
3538
- if (!name) return err("用法:/evolution skill restore <name>");
3539
- const skillRestoreRefusal = unreplayableWriteRefusal("skill restore");
3540
- if (skillRestoreRefusal) return skillRestoreRefusal;
3541
- const curator = ctx.get("evolutionCurator");
3542
- const result = curator ? await curator.restore(name) : {
3543
- ok: false,
3544
- message: hostError("e-302-curator-service-not-mounted")
3545
- };
3546
- return result.ok ? ok(result.message) : err(result.message);
3547
- }
3548
- if (input.startsWith("skill history ")) {
3549
- const name = input.slice(14).trim();
3550
- if (!name) return err("用法:/evolution skill history <name>");
3551
- const curator = ctx.get("evolutionCurator");
3552
- if (!curator) return err(hostError("e-302-curator-service-not-mounted"));
3553
- const versions = await curator.history(name);
3554
- if (versions.length === 0) return ok(`技能 "${name}" 还没有内容版本:下一次经 skill_manage 写入后才会出现。`);
3555
- const groups = partitionVersions(versions);
3556
- 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}`}`;
3557
- const lines = [`技能 "${name}" 的内容版本(由旧到新,${groups.content.length} 条,最多保留这么多):`, ...groups.content.map(row)];
3558
- if (groups.support.length > 0) lines.push("支撑文件版本(仅在历史里 —— 撤销恢复的是 SKILL.md,不是这些字节):", ...groups.support.map(row));
3559
- return ok(lines.join("\n"));
3560
- }
3561
- if (input.startsWith("skill undo ")) {
3562
- const rest = input.slice(11).trim();
3563
- const toMatch = /--to\s+v?(\d+)/.exec(rest);
3564
- const unitMatch = /--unit\s+(\S+)/.exec(rest);
3565
- const marker = [toMatch?.index, unitMatch?.index].filter((index) => index !== void 0).sort((a, b) => a - b)[0];
3566
- const name = (marker === void 0 ? rest : rest.slice(0, marker)).trim();
3567
- if (!name) return err("用法:/evolution skill undo <name> [--to v<N> | --unit <id>]");
3568
- if (toMatch !== null && unitMatch !== null) return err("--to 与 --unit 不能同时使用");
3569
- const skillUndoRefusal = unreplayableWriteRefusal("skill undo");
3570
- if (skillUndoRefusal) return skillUndoRefusal;
3571
- const curator = ctx.get("evolutionCurator");
3572
- const target = toMatch?.[1] === void 0 ? void 0 : Number(toMatch[1]);
3573
- const unitId = unitMatch?.[1];
3574
- const result = curator ? unitId !== void 0 ? await curator.undoUnit(name, unitId) : target === void 0 ? await curator.undo(name) : await curator.undo(name, target) : {
3575
- ok: false,
3576
- message: hostError("e-302-curator-service-not-mounted")
3577
- };
3578
- return result.ok ? ok(result.message) : err(result.message);
3579
- }
3580
- if (input === "skill pin" || input.startsWith("skill pin ") || input === "skill unpin" || input.startsWith("skill unpin ")) {
3581
- const pinned = !input.startsWith("skill unpin");
3582
- const name = input.slice(pinned ? 10 : 12).trim();
3583
- if (!name) return err(`用法:/evolution skill ${pinned ? "pin" : "unpin"} <name>`);
3584
- const ioRegistry = ctx.get("evolutionIo");
3585
- if (!ioRegistry) return err("未挂载 evolution-io 注册表:无法固定或取消固定技能。");
3586
- const result = await newSkillLibrary({
3587
- authority: authorityFrom({ origin: "foreground" }),
3588
- config: { root: skillsRootValue },
3589
- io: ioRegistry.provider(),
3590
- ctx,
3591
- limits: {
3592
- ...DEFAULT_SKILL_LIMITS,
3593
- ...policyStageLimits(ctx.get("evolutionPolicy")?.get?.())
3594
- }
3595
- }).setPinned(name, pinned);
3596
- return result.ok ? ok(result.message) : err(result.message);
3597
- }
3598
- if (input === "propose") {
3599
- const curator = ctx.get("evolutionCurator");
3600
- if (!curator) return err(hostError("e-302-curator-service-not-mounted"));
3601
- const result = await curator.proposeKeeps();
3602
- return result.ok ? ok(result.message) : err(result.message);
3603
- }
3604
- if (input === "skills health") {
3605
- const curator = ctx.get("evolutionCurator");
3606
- if (!curator) return err(hostError("e-302-curator-service-not-mounted"));
3607
- const [rows, observed] = await Promise.all([curator.healthView(), curator.usageObserved()]);
3608
- const banner = observed ? "" : "使用观测尚未建立 —— 频繁变动(写入幽灵)行已被抑制。";
3609
- const line = (row) => {
3610
- const detail = (row.findings ?? []).map((f) => f.rule + " x" + String(f.count)).join(", ");
3611
- return row.verdict.padEnd(18) + " " + row.name + (detail === "" ? "" : " — " + detail);
3612
- };
3613
- const tally = /* @__PURE__ */ new Map();
3614
- for (const row of rows) for (const f of row.findings ?? []) {
3615
- const hit = tally.get(f.rule);
3616
- if (hit === void 0) tally.set(f.rule, {
3617
- count: 1,
3618
- severity: f.severity
4001
+ const command = parseSubcommand(input);
4002
+ const maintainSub = (sub) => {
4003
+ if (isParseFailure(command) || command.name !== "maintain" || command.positionals[0] !== sub) return null;
4004
+ return [...command.flags.keys()].every((flag) => flagsOf("maintain").includes("--" + flag)) ? command : null;
4005
+ };
4006
+ const def = !isParseFailure(command) ? hostCommandDefForCommand(command) : void 0;
4007
+ switch (def?.id) {
4008
+ case "pending":
4009
+ case "approve":
4010
+ case "reject":
4011
+ case "release":
4012
+ case "params":
4013
+ case "curator":
4014
+ case "mutations":
4015
+ case "doctor":
4016
+ case "restore":
4017
+ case "skill.restore":
4018
+ case "skill.history":
4019
+ case "skill.undo": {
4020
+ if (def === void 0 || isParseFailure(command)) break;
4021
+ const handler = HOST_COMMAND_HANDLERS[def.id];
4022
+ if (handler === void 0) break;
4023
+ const handled = await handler({
4024
+ input,
4025
+ command,
4026
+ approval,
4027
+ locale: hostLocale,
4028
+ provider: ctx.get("settings"),
4029
+ ctx,
4030
+ runs: doctorRuns,
4031
+ refusal: unreplayableWriteRefusal
3619
4032
  });
3620
- else hit.count += 1;
4033
+ if (handled !== void 0) return handled;
4034
+ break;
3621
4035
  }
3622
- const aggregate = tally.size === 0 ? [] : ["Main causes: " + [...tally.entries()].sort((a, b) => b[1].count - a[1].count).map(([rule, v]) => `${rule} (${v.severity}) x${v.count}`).join(", ")];
3623
- if (rows.length === 0) return ok(["Structure health: no degraded row was reported (this does NOT assert that every skill is readable).", banner].filter(Boolean).join(" "));
3624
- return ok([
3625
- banner ? `Structure health (${rows.length} degraded): ${banner}` : `Structure health (${rows.length} degraded):`,
3626
- ...aggregate,
3627
- ...rows.map(line)
3628
- ].join("\n"));
3629
- }
3630
- if (input === "skills refresh") {
3631
- ctx.emit("evolution/skills-refresh");
3632
- return ok("已请求重读技能目录:缓存已丢弃,下次查询时重新读取。");
3633
- }
3634
- if (input === "learn" || input.startsWith("learn ")) {
3635
- const request = rawInputTrimmed === "learn" ? "" : rawInputTrimmed.slice(6).trim();
3636
- const message = createUserMessage({
3637
- content: [{
3638
- type: "text",
3639
- text: buildLearnPrompt(request)
3640
- }],
3641
- source: {
3642
- kind: "evolution-commands",
3643
- form: "notice",
3644
- summary: "learn request"
3645
- }
3646
- });
3647
- const missingAgent = agentMissing("learn");
3648
- if (missingAgent) return missingAgent;
3649
- const agent = invocationAgent;
3650
- let woke = false;
3651
- if (typeof agent.followup === "function") {
3652
- agent.followup(message);
3653
- woke = true;
3654
- } else if (typeof agent.inject === "function") agent.inject(message);
3655
- else return err(hostError("e-305-the-invocation-agent-exposes", { a1: "this learn request" }));
3656
- const eventIo = ctx.get("evolutionIo")?.provider();
3657
- if (eventIo) appendEvolutionEvent(eventIo, eventsFile(evolutionRoot()), {
3658
- type: "learn",
3659
- source: "manual",
3660
- ...request ? { request } : {}
3661
- }).catch((error) => {
3662
- ctx.logger.warn(`evolution-commands: failed to record learn event: ${String(error)}`);
3663
- });
3664
- return woke ? ok("已向本会话发送学习请求,请现在执行。") : ok("学习请求已排入本会话队列:本宿主没有唤醒通道,会在你下一条消息时读取。");
3665
- }
3666
- const factsParsed = parseSubcommand(input);
3667
- if (!isParseFailure(factsParsed) && factsParsed.name === "maintain" && factsParsed.flags.get("facts") === true && factsParsed.positionals.length === 0) {
3668
- const ioRegistry = ctx.get("evolutionIo");
3669
- if (!ioRegistry) return err("未挂载 evolution-io 注册表:维护事实不可用。");
3670
- const library = newSkillLibrary({
3671
- authority: authorityFrom({ origin: "foreground" }),
3672
- config: { root: skillsRootValue },
3673
- io: ioRegistry.provider(),
3674
- ...mutationLockFrom(ctx) === void 0 ? {} : { mutationLock: mutationLockFrom(ctx) }
3675
- });
3676
- const enrichment = await buildEnrichment(ctx, library);
3677
- const readFailures = [];
3678
- const snapshots = await snapshotFromLibrary(library, {
3679
- ...enrichmentSnapshotOptions(enrichment),
3680
- onReadError: (name, error) => {
3681
- readFailures.push(name);
3682
- ctx.logger.warn(`evolution-maintenance: skipping unreadable skill "${name}": ${error instanceof Error ? error.message : String(error)}`);
4036
+ case "skill.pin":
4037
+ case "skill.unpin": {
4038
+ const pinned = !input.startsWith("skill unpin");
4039
+ const name = input.slice(pinned ? 10 : 12).trim();
4040
+ if (!name) return err(`用法:/evolution skill ${pinned ? "pin" : "unpin"} <name>`);
4041
+ const ioRegistry = ctx.get("evolutionIo");
4042
+ if (!ioRegistry) return err("未挂载 evolution-io 注册表:无法固定或取消固定技能。");
4043
+ const result = await newSkillLibrary({
4044
+ authority: authorityFrom({ origin: "foreground" }),
4045
+ config: { root: skillsRootValue },
4046
+ io: ioRegistry.provider(),
4047
+ ctx,
4048
+ limits: {
4049
+ ...DEFAULT_SKILL_LIMITS,
4050
+ ...policyStageLimits(ctx.get("evolutionPolicy")?.get?.())
4051
+ }
4052
+ }).setPinned(name, pinned);
4053
+ return result.ok ? ok(result.message) : err(result.message);
4054
+ }
4055
+ case "skills.health": {
4056
+ const curator = ctx.get("evolutionCurator");
4057
+ if (!curator) return err(hostError("e-302-curator-service-not-mounted"));
4058
+ const [rows, observed] = await Promise.all([curator.healthView(), curator.usageObserved()]);
4059
+ const banner = observed ? "" : "使用观测尚未建立 —— 频繁变动(写入幽灵)行已被抑制。";
4060
+ const line = (row) => {
4061
+ const detail = (row.findings ?? []).map((f) => f.rule + " x" + String(f.count)).join(", ");
4062
+ return row.verdict.padEnd(18) + " " + row.name + (detail === "" ? "" : " — " + detail);
4063
+ };
4064
+ const tally = /* @__PURE__ */ new Map();
4065
+ for (const row of rows) for (const f of row.findings ?? []) {
4066
+ const hit = tally.get(f.rule);
4067
+ if (hit === void 0) tally.set(f.rule, {
4068
+ count: 1,
4069
+ severity: f.severity
4070
+ });
4071
+ else hit.count += 1;
3683
4072
  }
3684
- });
3685
- if (snapshots.length === 0 && readFailures.length > 0) return err(`维护扫描读不出 ${readFailures.length} 个已登记技能(${readFailures.slice(0, 10).join(", ")}${readFailures.length > 10 ? ", …" : ""}),且一个技能都没读到:技能库未被审计。请修好读不出的技能(或它们的目录名)后重新扫描`);
3686
- if (snapshots.length === 0 && skillsRootValue !== "" && !await ioRegistry.provider().exists(skillsRootValue)) return err(`维护扫描发现技能库为空,但配置的技能根目录不存在(${skillsRootValue}):请把 skillsRoot 指向真实目录(字面量 \`~\` 不会被展开),然后重新扫描`);
3687
- if (snapshots.length === 0) return ok("维护扫描:技能库为空,无需处理。");
3688
- const { facts } = buildMaintainFacts(snapshots, enrichment.usageObservedValue, void 0);
3689
- return ok(`维护事实(零 token 预览):\n${facts}`);
3690
- }
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");
3695
- const runTimeoutMs = typeof timeoutFlag === "string" ? Number(timeoutFlag) : config.maintainTimeoutMs ?? 6e5;
3696
- 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
- const registry = runs;
3698
- if (!registry) return err("未挂载 evolution-io 注册表:维护扫描不可用。");
3699
- const synced = await syncRuns(registry);
3700
- if (!synced.ok) ctx.logger.warn(`evolution-commands: ${synced.note ?? "run index unreadable"} — the in-flight guard cannot see other processes' runs`);
3701
- else if (synced.note !== void 0) ctx.logger.warn(`evolution-commands: ${synced.note}`);
3702
- const ioRegistry = ctx.get("evolutionIo");
3703
- if (!ioRegistry) return err("未挂载 evolution-io 注册表:维护扫描不可用。");
3704
- const channel = createSubagentChannel(ctx);
3705
- const running = registry.inFlight();
3706
- if (running) {
3707
- const elapsed = Math.max(1, Math.round((Date.now() - running.startedAt) / 1e3));
3708
- return err(`维护运行 ${running.id} 已经在进行中(约 ${elapsed}s 前启动):现在重交会再开一次扫描。查看状态:/evolution maintain status ${running.id};停止它:/evolution maintain cancel ${running.id}。`);
4073
+ const aggregate = tally.size === 0 ? [] : ["Main causes: " + [...tally.entries()].sort((a, b) => b[1].count - a[1].count).map(([rule, v]) => `${rule} (${v.severity}) x${v.count}`).join(", ")];
4074
+ if (rows.length === 0) return ok(["Structure health: no degraded row was reported (this does NOT assert that every skill is readable).", banner].filter(Boolean).join(" "));
4075
+ return ok([
4076
+ banner ? `Structure health (${rows.length} degraded): ${banner}` : `Structure health (${rows.length} degraded):`,
4077
+ ...aggregate,
4078
+ ...rows.map(line)
4079
+ ].join("\n"));
3709
4080
  }
3710
- const cooldownMs = clampedNumber(config.maintainCooldownMs, 3e4, { min: 0 });
3711
- const lastSettled = registry.lastSettledAt();
3712
- const sinceLast = lastSettled === void 0 ? Number.POSITIVE_INFINITY : Date.now() - lastSettled;
3713
- if (cooldownMs > 0 && sinceLast < cooldownMs) {
3714
- const remaining = Math.ceil((cooldownMs - sinceLast) / 1e3);
3715
- const latest = registry.runs().find((record) => record.state !== "running");
3716
- return err(`维护冷却中(${remaining}s)${latest === void 0 ? "" : `,最近一次运行 ${latest.id}`}:现在重跑会再消耗一次模型调用。`);
4081
+ case "learn": {
4082
+ const request = rawInputTrimmed === "learn" ? "" : rawInputTrimmed.slice(6).trim();
4083
+ const message = createUserMessage({
4084
+ content: [{
4085
+ type: "text",
4086
+ text: buildLearnPrompt(request)
4087
+ }],
4088
+ source: {
4089
+ kind: "evolution-commands",
4090
+ form: "notice",
4091
+ summary: "learn request"
4092
+ }
4093
+ });
4094
+ const missingAgent = agentMissing("learn");
4095
+ if (missingAgent) return missingAgent;
4096
+ const agent = invocationAgent;
4097
+ let woke = false;
4098
+ if (typeof agent.followup === "function") {
4099
+ agent.followup(message);
4100
+ woke = true;
4101
+ } else if (typeof agent.inject === "function") agent.inject(message);
4102
+ else return err(hostError("e-305-the-invocation-agent-exposes", { a1: "this learn request" }));
4103
+ const eventIo = ctx.get("evolutionIo")?.provider();
4104
+ if (eventIo) appendEvolutionEvent(eventIo, eventsFile(evolutionRoot()), {
4105
+ type: "learn",
4106
+ source: "manual",
4107
+ ...request ? { request } : {}
4108
+ }).catch((error) => {
4109
+ ctx.logger.warn(`evolution-commands: failed to record learn event: ${String(error)}`);
4110
+ });
4111
+ return woke ? ok("已向本会话发送学习请求,请现在执行。") : ok("学习请求已排入本会话队列:本宿主没有唤醒通道,会在你下一条消息时读取。");
3717
4112
  }
3718
- const runHome = evolutionHome();
3719
- const runRoot = evolutionRoot();
3720
- const runAgent = invocationAgent;
3721
- const handle = await registry.begin("maintain");
3722
- (async () => {
3723
- try {
3724
- const library = newSkillLibrary({
3725
- authority: authorityFrom({ origin: "foreground" }),
3726
- config: { root: skillsRootValue },
3727
- io: ioRegistry.provider(),
3728
- ...mutationLockFrom(ctx) === void 0 ? {} : { mutationLock: mutationLockFrom(ctx) }
3729
- });
3730
- const enrichment = await buildEnrichment(ctx, library);
3731
- const outcome = await runMaintain({
3732
- library,
3733
- channel,
3734
- parent: invocation.agent,
3735
- evolutionPolicy: { get: () => ctx.get("evolutionPolicy")?.get() },
3736
- tools: { get: (name) => ctx.get("tools")?.get(name) },
3737
- logger: { warn: (message) => {
3738
- ctx.logger.warn(message);
3739
- } },
3740
- rootExists: skillsRootValue === "" ? void 0 : () => ioRegistry.provider().exists(skillsRootValue),
3741
- skillRoot: skillsRootValue
3742
- }, {
3743
- timeoutMs: runTimeoutMs,
3744
- signal: handle.signal,
3745
- runId: handle.id,
3746
- enrichment: () => enrichment
3747
- });
3748
- const endedAt = Date.now();
3749
- const resultRef = await writeMaintainReport(ioRegistry.provider(), {
3750
- runId: handle.id,
3751
- ...outcome.ok ? {
3752
- verdict: outcome.verdict,
3753
- recommendationCount: outcome.recommendationCount,
3754
- items: outcome.items,
3755
- notes: outcome.notes,
3756
- forcedHuman: outcome.forcedHuman,
3757
- needsHumanCount: outcome.needsHumanCount
3758
- } : {},
3759
- ...outcome.ok ? {} : { failure: handle.signal.aborted ? "cancelled: the scan was stopped before it settled" : outcome.error ?? "Maintenance scan failed." },
3760
- startedAt: handle.startedAt,
3761
- endedAt,
3762
- text: outcome.text ?? ""
3763
- }, (message) => {
3764
- ctx.logger.warn(message);
3765
- }, runHome, ctx.get("evolutionMutationAuthority")?.homeFence);
3766
- if (resultRef !== void 0) {
3767
- if (!isPresent(await probeMtime(ioRegistry.provider(), resultRef))) {
3768
- await registry.settle(handle.id, {
3769
- state: "failed",
3770
- failure: "the maintain report file is missing at settle time (write/io race) — the scan result was not persisted."
3771
- });
3772
- return;
3773
- }
4113
+ case "extract": {
4114
+ if (isParseFailure(command) || command.name !== "extract") return err("用法:/evolution extract <source> <target> \"<heading>\" [--start <line>] [--end <line>] [--owner-covers] 或 --proposal <id>");
4115
+ const source = command.positionals[0] ?? "";
4116
+ const proposalFlag = command.flags.get("proposal");
4117
+ const ioRegistry = ctx.get("evolutionIo");
4118
+ if (!ioRegistry) return err("未挂载 evolution-io 注册表:无法执行 extract。");
4119
+ let target = command.positionals[1] ?? "";
4120
+ let heading = command.positionals[2] ?? "";
4121
+ let start;
4122
+ let end;
4123
+ let extractItems = [];
4124
+ let proposalOutcome;
4125
+ if (typeof proposalFlag === "string") {
4126
+ if (source === "") return err("用法:/evolution extract <source> --proposal <id>");
4127
+ const proposal = await readProposalReport(ioRegistry.provider(), proposalFlag);
4128
+ if (proposal === null) return err("找不到 extract proposal:" + proposalFlag);
4129
+ if (proposal.outcome === "keep") return err("该 proposal 的结论是 keep,没有可应用提取。");
4130
+ if (proposal.owner.mode !== "covered" || proposal.owner.name === void 0) return err("该 proposal 未覆盖 owner(owner-gap),不能应用。");
4131
+ target = proposal.owner.name;
4132
+ heading = proposal.parts[0]?.heading ?? "";
4133
+ proposalOutcome = proposal.outcome === "extract" || proposal.outcome === "mixed" ? proposal.outcome : void 0;
4134
+ extractItems = proposal.parts.map((part) => ({
4135
+ heading: part.heading,
4136
+ ...part.anchor.start === void 0 ? {} : { start: part.anchor.start },
4137
+ ...part.anchor.end === void 0 ? {} : { end: part.anchor.end },
4138
+ to_skill: target
4139
+ }));
4140
+ } else {
4141
+ if (source === "" || target === "" || heading === "") return err("用法:/evolution extract <source> <target> \"<heading>\" [--start <line>] [--end <line>]");
4142
+ const startFlag = command.flags.get("start");
4143
+ const endFlag = command.flags.get("end");
4144
+ start = typeof startFlag === "string" ? startFlag : void 0;
4145
+ end = typeof endFlag === "string" ? endFlag : void 0;
4146
+ extractItems = [{
4147
+ heading,
4148
+ ...start === void 0 ? {} : { start },
4149
+ ...end === void 0 ? {} : { end },
4150
+ to_skill: target
4151
+ }];
4152
+ }
4153
+ const ownerCovers = command.flags.has("owner-covers");
4154
+ const outcomeFlag = command.flags.get("outcome");
4155
+ if (outcomeFlag !== void 0 && outcomeFlag !== "extract" && outcomeFlag !== "mixed") return err("--outcome 只能是 extract 或 mixed。");
4156
+ const library = newSkillLibrary({
4157
+ authority: authorityFrom({ origin: "foreground" }),
4158
+ config: { root: skillsRootValue },
4159
+ io: ioRegistry.provider(),
4160
+ ctx,
4161
+ threatExemptLabels: config.threatExemptLabels,
4162
+ limits: {
4163
+ ...DEFAULT_SKILL_LIMITS,
4164
+ ...policyStageLimits(ctx.get("evolutionPolicy")?.get?.())
3774
4165
  }
3775
- const state = outcome.ok ? "succeeded" : handle.signal.aborted ? "cancelled" : "failed";
3776
- await registry.settle(handle.id, {
3777
- state,
3778
- ...resultRef === void 0 ? {} : { resultRef },
3779
- ...outcome.ok ? {} : { failure: handle.signal.aborted ? "cancelled: the scan was stopped before it settled" : outcome.error ?? "Maintenance scan failed." }
3780
- });
3781
- if (outcome.ok) {
3782
- appendEvolutionEvent(ioRegistry.provider(), eventsFile(runRoot), {
3783
- type: "maintain",
3784
- source: "manual",
3785
- runId: handle.id,
3786
- verdict: outcome.verdict,
3787
- recommendations: outcome.recommendationCount
3788
- }).catch((error) => {
3789
- ctx.logger.warn(`evolution-commands: failed to record maintain event: ${String(error)}`);
3790
- });
3791
- if (liveBool(config.maintainHandoffOnSettle) && resultRef !== void 0 && runAgent !== void 0) try {
3792
- if (deliverHandoff(runAgent, createUserMessage({
3793
- content: [{
3794
- type: "text",
3795
- text: handoffPrompt({
3796
- runId: handle.id,
3797
- reportPath: reportDigestPath({
3798
- id: handle.id,
3799
- resultRef
3800
- }),
3801
- verdict: outcome.verdict,
3802
- recommendationCount: outcome.recommendationCount,
3803
- needsHumanCount: outcome.needsHumanCount
3804
- })
3805
- }],
3806
- source: {
3807
- kind: "evolution-commands",
3808
- form: "notice",
3809
- summary: "maintenance report handoff (auto)"
3810
- }
3811
- })) === void 0) ctx.logger.warn(`evolution-commands: the automatic report handoff for run ${handle.id} could not be delivered — this host exposes neither followup nor inject; the report is at ${reportDigestPath({
3812
- id: handle.id,
3813
- resultRef
3814
- })}`);
3815
- } catch (error) {
3816
- ctx.logger.warn(`evolution-commands: automatic report handoff failed (${String(error)})`);
3817
- }
3818
- } else ctx.logger.warn(`evolution-commands: maintenance run ${handle.id} produced no plan (${outcome.error ?? "原因未知"})`);
3819
- } catch (error) {
3820
- const aborted = handle.signal.aborted;
3821
- const failure = aborted ? "cancelled: the scan was stopped before it settled" : `Maintenance scan failed: ${error instanceof Error ? error.message : String(error)}`;
3822
- await registry.settle(handle.id, {
3823
- state: aborted ? "cancelled" : "failed",
3824
- failure
3825
- });
3826
- ctx.logger.warn(`evolution-commands: maintenance run ${handle.id} threw (${failure})`);
4166
+ });
4167
+ const built = await buildExtractPlanFromLibrary(library, {
4168
+ source,
4169
+ items: extractItems,
4170
+ ...outcomeFlag === void 0 ? proposalOutcome === void 0 ? {} : { outcome: proposalOutcome } : { outcome: outcomeFlag },
4171
+ ...ownerCovers ? { ownerCovers: true } : {}
4172
+ });
4173
+ if (!built.ok) return err(built.message);
4174
+ const plan = built.plan;
4175
+ const warnings = built.warnings === void 0 || built.warnings.length === 0 ? "" : "\n" + built.warnings.join("\n");
4176
+ if (!command.flags.has("apply")) {
4177
+ const proposal = proposalFromPlan(plan, { runId: "cli-" + Date.now().toString(36) });
4178
+ const proposalPath = await writeProposalReport(ioRegistry.provider(), proposal).catch(() => {});
4179
+ 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)"));
3827
4180
  }
3828
- })();
3829
- return ok([
3830
- `Maintenance run ${handle.id} started — the scan keeps running after this reply.`,
3831
- `- status: /evolution maintain status ${handle.id}`,
3832
- `- result: /evolution maintain report ${handle.id}`,
3833
- `- stop: /evolution maintain cancel ${handle.id}`
3834
- ].join("\n"));
3835
- }
3836
- const maintainStatus = subcommandOf(input, "maintain", "status", flagsOf("maintain"));
3837
- if (maintainStatus !== null) {
3838
- const registry = runs;
3839
- if (!registry) return err("未挂载 evolution-io 注册表:无法查看运行状态。");
3840
- const synced = await syncRuns(registry);
3841
- const wanted = maintainStatus.positionals[1];
3842
- if (wanted !== void 0) {
3843
- const record = registry.find(wanted);
3844
- if (!record) {
3845
- if (!synced.ok) return err(`运行 ${wanted} 不在本进程的历史里,且本 home 的运行索引读不出来(${synced.note ?? "原因未知"}):但这不能证明那次运行没发生过。`);
3846
- return err(`本 home 里没有 ${wanted} 这次运行:用 /evolution maintain status 查看最近的几次。`);
4181
+ if (approval) {
4182
+ const session = invocationAgent?.session;
4183
+ const sessionPolicy = effectiveSessionPolicy(ctx, session);
4184
+ const stagesForeground = approval.isEnabled !== false && sessionPolicy !== "never" && approval.stageForeground !== false;
4185
+ if (stagesForeground && session === void 0) return err(hostError("e-306-this-deployment-stages-foreground-2"));
4186
+ if (stagesForeground && !approval.hasRunner("skill")) return err("无法暂存提取:没有注册技能回放运行器:请挂载 tool-skill-manage 行,或禁用 evolution-approval。");
4187
+ const decision = await approval.request({
4188
+ kind: "skill",
4189
+ summary: "/evolution extract " + source + " -> " + target + " " + heading,
4190
+ args: {
4191
+ operation: {
4192
+ action: "extract",
4193
+ name: source,
4194
+ extract: extractItems
4195
+ },
4196
+ origin: "foreground",
4197
+ libraryOrigin: "foreground"
4198
+ },
4199
+ origin: "foreground",
4200
+ ...session !== void 0 ? {
4201
+ sessionId: session.id,
4202
+ session
4203
+ } : {},
4204
+ ...sessionPolicy !== void 0 ? { sessionPolicy } : {}
4205
+ });
4206
+ if (decision.action === "staged") return ok(decision.message);
3847
4207
  }
3848
- return ok(synced.ok ? renderRunRecord(record) : `${renderRunRecord(record)}\n(运行索引读不出来:${synced.note ?? "原因未知"} — only this process's view is shown)`);
4208
+ const result = await library.extract(plan, "foreground");
4209
+ if (!result.ok) return err(result.message);
4210
+ return ok(result.message + "\n提取判定:outcome=" + plan.outcome + ";target=" + target + warnings);
3849
4211
  }
3850
- if (!synced.ok) return err(`本 home 的运行历史读不出来(${synced.note ?? "原因未知"}):这「不是」没有运行。要开始干净的历史,请修好或删除 <evolutionHome>/runs.json。`);
3851
- const all = registry.runs();
3852
- if (all.length === 0) return ok("本 home 还没有维护运行记录:用 /evolution maintain 启动一次。");
3853
- const live = all.filter((record) => record.state === "running");
3854
- const recent = all.filter((record) => record.state !== "running").slice(0, 5);
3855
- 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
- }
3857
- const maintainReport = subcommandOf(input, "maintain", "report", flagsOf("maintain"));
3858
- if (maintainReport !== null) {
3859
- const registry = runs;
3860
- if (!registry) return err("未挂载 evolution-io 注册表:无法查看运行结果。");
3861
- const synced = await syncRuns(registry);
3862
- const wanted = maintainReport.positionals[1];
3863
- if (wanted === void 0 && !synced.ok) return err(unreadableIndex(synced.note));
3864
- const record = wanted === void 0 ? newestRun(registry) : registry.find(wanted);
3865
- if (!record) {
3866
- if (wanted !== void 0) {
3867
- if (!synced.ok) return err(unreadableForId(wanted, synced.note));
3868
- return err(`本 home 里没有 ${wanted} 这次运行:用 /evolution maintain status 查看最近的几次。`);
4212
+ case "restructure": {
4213
+ if (isParseFailure(command) || command.name !== "restructure") return err("用法:/evolution restructure <name> \"<heading>\" <to_file>");
4214
+ const name = command.positionals[0] ?? "";
4215
+ const heading = command.positionals[1] ?? "";
4216
+ const toFile = command.positionals[2] ?? "";
4217
+ if (name === "" || heading === "" || toFile === "") return err("用法:/evolution restructure <name> \"<heading>\" <to_file>");
4218
+ const planFlag = command.flags.get("plan");
4219
+ const planRunId = typeof planFlag === "string" ? planFlag : void 0;
4220
+ if (!toFile.startsWith("references/")) return err("to_file 必须位于 references/ 之下(日志或明细的落地位置)。");
4221
+ const ioRegistry = ctx.get("evolutionIo");
4222
+ if (!ioRegistry) return err("未挂载 evolution-io 注册表:无法重构。");
4223
+ if (approval) {
4224
+ const session = invocationAgent?.session;
4225
+ const sessionPolicy = effectiveSessionPolicy(ctx, session);
4226
+ const stagesForeground = approval.isEnabled !== false && sessionPolicy !== "never" && approval.stageForeground !== false;
4227
+ if (stagesForeground && session === void 0) return err(hostError("e-306-this-deployment-stages-foreground-2"));
4228
+ if (stagesForeground && !approval.hasRunner("skill")) return err("无法暂存重构:没有注册技能回放运行器:请挂载 tool-skill-manage 行(evolution-agent 预设或 evolution-all),或禁用 evolution-approval。");
4229
+ const decision = await approval.request({
4230
+ kind: "skill",
4231
+ summary: `/evolution restructure ${name}${planRunId ? ` (plan ${planRunId})` : ""}`,
4232
+ args: {
4233
+ operation: {
4234
+ action: "restructure",
4235
+ name,
4236
+ restructure: [{
4237
+ heading,
4238
+ to_file: toFile
4239
+ }]
4240
+ },
4241
+ origin: "foreground",
4242
+ libraryOrigin: "foreground"
4243
+ },
4244
+ origin: "foreground",
4245
+ ...session !== void 0 ? {
4246
+ sessionId: session.id,
4247
+ session
4248
+ } : {},
4249
+ ...sessionPolicy !== void 0 ? { sessionPolicy } : {}
4250
+ });
4251
+ if (decision.action === "staged") return ok(`${decision.message}${planRunId ? `\n[audit] plan=${planRunId}` : ""}`);
3869
4252
  }
3870
- return err("本 home 还没有维护运行记录:用 /evolution maintain 启动一次。");
4253
+ const result = await newSkillLibrary({
4254
+ authority: authorityFrom({ origin: "foreground" }),
4255
+ config: { root: skillsRootValue },
4256
+ io: ioRegistry.provider(),
4257
+ ctx,
4258
+ threatExemptLabels: config.threatExemptLabels,
4259
+ limits: {
4260
+ ...DEFAULT_SKILL_LIMITS,
4261
+ ...policyStageLimits(ctx.get("evolutionPolicy")?.get?.())
4262
+ }
4263
+ }).restructure(name, [{
4264
+ heading,
4265
+ toFile
4266
+ }], "foreground");
4267
+ if (!result.ok) return err(result.message);
4268
+ await ctx.get("skillUsage")?.record?.(name, "patch");
4269
+ return ok(planRunId ? `${result.message}\n[audit] plan=${planRunId}` : result.message);
3871
4270
  }
3872
- if (wanted === void 0 && record.state === "running") return err(`最新一次运行 ${record.id} 仍在进行:它结束后才会出报告;用 /evolution maintain status ${record.id} 查看进度。`);
3873
- const ioRegistry = ctx.get("evolutionIo");
3874
- if (!ioRegistry) return err("未挂载 evolution-io 注册表:无法查看运行结果。");
3875
- const probed = await readRunReport(ioRegistry.provider(), record);
3876
- if (probed.kind === "missing") return err(`运行 ${record.id}(${record.state})没有结果:没有写出报告${record.failure === void 0 ? "" : `(${record.failure})`}。`);
3877
- if (probed.kind === "unknown") return err(`运行 ${record.id} 有报告但读不出来(${probed.reason}):这「不是」没有结果。`);
3878
- return ok(probed.text);
3879
- }
3880
- const maintainCancel = subcommandOf(input, "maintain", "cancel", flagsOf("maintain"));
3881
- if (maintainCancel !== null) {
3882
- const registry = runs;
3883
- if (!registry) return err("未挂载 evolution-io 注册表:无法取消运行。");
3884
- const synced = await syncRuns(registry);
3885
- const wanted = maintainCancel.positionals[1];
3886
- if (wanted === void 0 && !synced.ok) return err(unreadableIndex(synced.note));
3887
- const record = wanted === void 0 ? newestRun(registry) : registry.find(wanted);
3888
- if (!record) {
3889
- if (wanted !== void 0) {
3890
- if (!synced.ok) return err(unreadableForId(wanted, synced.note));
3891
- return err(`本 home 里没有 ${wanted} 这次运行:用 /evolution maintain status 查看最近的几次。`);
3892
- }
3893
- return err("本 home 还没有维护运行记录:用 /evolution maintain 启动一次。");
4271
+ case "merge": {
4272
+ const merge = ctx.get("evolutionMerge");
4273
+ if (merge === void 0) return err("merge 未挂载:当前安装形态没有 evolution-merge 行(安装形态与命令可用性见 INSTALL.md),或先运行 /evolution doctor。");
4274
+ const result = await merge.run(rawInputTrimmed, { agent: invocation.agent });
4275
+ return result.ok ? ok(result.text) : err(result.text);
3894
4276
  }
3895
- const idlessHint = wanted === void 0 ? " 要取消某次运行请带上 id:/evolution maintain status 会列出它们。" : "";
3896
- if (!registry.cancel(record.id)) {
3897
- if (record.state === "running") return err(`运行 ${record.id} 正在共享本 home 的另一个进程里运行:只能在那里取消。`);
3898
- return err(`运行 ${record.id} 已经是 ${record.state}:没有可取消的东西。${idlessHint}`);
4277
+ case "maintain.status": {
4278
+ const maintainStatus = maintainSub("status");
4279
+ if (maintainStatus !== null) {
4280
+ const registry = runs;
4281
+ if (!registry) return err("未挂载 evolution-io 注册表:无法查看运行状态。");
4282
+ const synced = await syncRuns(registry);
4283
+ const wanted = maintainStatus.positionals[1];
4284
+ if (wanted !== void 0) {
4285
+ const record = registry.find(wanted);
4286
+ if (!record) {
4287
+ if (!synced.ok) return err(`运行 ${wanted} 不在本进程的历史里,且本 home 的运行索引读不出来(${synced.note ?? "原因未知"}):但这不能证明那次运行没发生过。`);
4288
+ return err(`本 home 里没有 ${wanted} 这次运行:用 /evolution maintain status 查看最近的几次。`);
4289
+ }
4290
+ return ok(synced.ok ? renderRunRecord(record) : `${renderRunRecord(record)}\n(运行索引读不出来:${synced.note ?? "原因未知"} — only this process's view is shown)`);
4291
+ }
4292
+ if (!synced.ok) return err(`本 home 的运行历史读不出来(${synced.note ?? "原因未知"}):这「不是」没有运行。要开始干净的历史,请修好或删除 <evolutionHome>/runs.json。`);
4293
+ const all = registry.runs();
4294
+ if (all.length === 0) return ok("本 home 还没有维护运行记录:用 /evolution maintain 启动一次。");
4295
+ const live = all.filter((record) => record.state === "running");
4296
+ const recent = all.filter((record) => record.state !== "running").slice(0, 5);
4297
+ 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"));
4298
+ }
4299
+ break;
3899
4300
  }
3900
- return ok(`维护运行 ${record.id} 已取消:扫描会在下一个检查点停止。用 /evolution maintain status ${record.id} 查看终态。`);
3901
- }
3902
- const maintainHandoff = subcommandOf(input, "maintain", "handoff", flagsOf("maintain"));
3903
- if (maintainHandoff !== null) {
3904
- const registry = runs;
3905
- if (!registry) return err("未挂载 evolution-io 注册表:无法交付报告。");
3906
- const synced = await syncRuns(registry);
3907
- const wanted = maintainHandoff.positionals[1];
3908
- if (wanted === void 0 && !synced.ok) return err(unreadableIndex(synced.note));
3909
- const record = wanted === void 0 ? newestRun(registry) : registry.find(wanted);
3910
- if (!record) {
3911
- if (wanted !== void 0) {
3912
- if (!synced.ok) return err(unreadableForId(wanted, synced.note));
3913
- return err(`本 home 里没有 ${wanted} 这次运行:用 /evolution maintain status 查看最近的几次。`);
4301
+ case "maintain.report": {
4302
+ const maintainReport = maintainSub("report");
4303
+ if (maintainReport !== null) {
4304
+ const registry = runs;
4305
+ if (!registry) return err("未挂载 evolution-io 注册表:无法查看运行结果。");
4306
+ const synced = await syncRuns(registry);
4307
+ const wanted = maintainReport.positionals[1];
4308
+ if (wanted === void 0 && !synced.ok) return err(unreadableIndex(synced.note));
4309
+ const record = wanted === void 0 ? newestRun(registry) : registry.find(wanted);
4310
+ if (!record) {
4311
+ if (wanted !== void 0) {
4312
+ if (!synced.ok) return err(unreadableForId(wanted, synced.note));
4313
+ return err(`本 home 里没有 ${wanted} 这次运行:用 /evolution maintain status 查看最近的几次。`);
4314
+ }
4315
+ return err("本 home 还没有维护运行记录:用 /evolution maintain 启动一次。");
4316
+ }
4317
+ if (wanted === void 0 && record.state === "running") return err(`最新一次运行 ${record.id} 仍在进行:它结束后才会出报告;用 /evolution maintain status ${record.id} 查看进度。`);
4318
+ const ioRegistry = ctx.get("evolutionIo");
4319
+ if (!ioRegistry) return err("未挂载 evolution-io 注册表:无法查看运行结果。");
4320
+ const probed = await readRunReport(ioRegistry.provider(), record);
4321
+ if (probed.kind === "missing") return err(`运行 ${record.id}(${record.state})没有结果:没有写出报告${record.failure === void 0 ? "" : `(${record.failure})`}。`);
4322
+ if (probed.kind === "unknown") return err(`运行 ${record.id} 有报告但读不出来(${probed.reason}):这「不是」没有结果。`);
4323
+ return ok(probed.text);
3914
4324
  }
3915
- return err("本 home 还没有维护运行记录:用 /evolution maintain 启动一次。");
4325
+ break;
3916
4326
  }
3917
- if (wanted === void 0 && record.state === "running") return err(`最新一次运行 ${record.id} 仍在进行:它结束后才会出报告;用 /evolution maintain status ${record.id} 查看进度。`);
3918
- const ioRegistry = ctx.get("evolutionIo");
3919
- if (!ioRegistry) return err("未挂载 evolution-io 注册表:无法交付报告。");
3920
- const probed = await readRunReport(ioRegistry.provider(), record);
3921
- if (probed.kind === "missing") return err(`运行 ${record.id}(${record.state})没有结果:没有写出报告${record.failure === void 0 ? "" : `(${record.failure})`}。`);
3922
- if (probed.kind === "unknown") return err(`运行 ${record.id} 有报告但读不出来(${probed.reason}):这「不是」没有结果。`);
3923
- const missingAgent = agentMissing("handoff");
3924
- if (missingAgent) return missingAgent;
3925
- const woke = deliverHandoff(invocationAgent, createUserMessage({
3926
- content: [{
3927
- type: "text",
3928
- text: handoffPrompt({
3929
- runId: record.id,
3930
- reportPath: reportDigestPath(record),
3931
- verdict: probed.report.verdict,
3932
- recommendationCount: probed.report.recommendationCount,
3933
- needsHumanCount: probed.report.needsHumanCount
3934
- })
3935
- }],
3936
- source: {
3937
- kind: "evolution-commands",
3938
- form: "notice",
3939
- summary: "maintenance report handoff"
4327
+ case "maintain.cancel": {
4328
+ const maintainCancel = maintainSub("cancel");
4329
+ if (maintainCancel !== null) {
4330
+ const registry = runs;
4331
+ if (!registry) return err("未挂载 evolution-io 注册表:无法取消运行。");
4332
+ const synced = await syncRuns(registry);
4333
+ const wanted = maintainCancel.positionals[1];
4334
+ if (wanted === void 0 && !synced.ok) return err(unreadableIndex(synced.note));
4335
+ const record = wanted === void 0 ? newestRun(registry) : registry.find(wanted);
4336
+ if (!record) {
4337
+ if (wanted !== void 0) {
4338
+ if (!synced.ok) return err(unreadableForId(wanted, synced.note));
4339
+ return err(`本 home 里没有 ${wanted} 这次运行:用 /evolution maintain status 查看最近的几次。`);
4340
+ }
4341
+ return err("本 home 还没有维护运行记录:用 /evolution maintain 启动一次。");
4342
+ }
4343
+ const idlessHint = wanted === void 0 ? " 要取消某次运行请带上 id:/evolution maintain status 会列出它们。" : "";
4344
+ if (!registry.cancel(record.id)) {
4345
+ if (record.state === "running") return err(`运行 ${record.id} 正在共享本 home 的另一个进程里运行:只能在那里取消。`);
4346
+ return err(`运行 ${record.id} 已经是 ${record.state}:没有可取消的东西。${idlessHint}`);
4347
+ }
4348
+ return ok(`维护运行 ${record.id} 已取消:扫描会在下一个检查点停止。用 /evolution maintain status ${record.id} 查看终态。`);
3940
4349
  }
3941
- }));
3942
- if (woke === void 0) return err(hostError("e-305-the-invocation-agent-exposes", { a1: "this maintenance handoff" }));
3943
- return ok(woke ? `已把运行 ${record.id} 交给模型 —— 报告:${reportDigestPath(record)}。它会读取该文件并执行其中的行动项。` : `已把运行 ${record.id} 交给模型并排队 —— 本宿主没有唤醒通道,因此会在你下一条消息时被读取。`);
3944
- }
3945
- 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
- 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");
3951
- const ioRegistry = ctx.get("evolutionIo");
3952
- if (!ioRegistry) return err("未挂载 evolution-io 注册表:无法执行 extract。");
3953
- let target = extractParsed.positionals[1] ?? "";
3954
- let heading = extractParsed.positionals[2] ?? "";
3955
- let start;
3956
- let end;
3957
- let extractItems = [];
3958
- let proposalOutcome;
3959
- if (typeof proposalFlag === "string") {
3960
- if (source === "") return err("用法:/evolution extract <source> --proposal <id>");
3961
- const proposal = await readProposalReport(ioRegistry.provider(), proposalFlag);
3962
- if (proposal === null) return err("找不到 extract proposal:" + proposalFlag);
3963
- if (proposal.outcome === "keep") return err("该 proposal 的结论是 keep,没有可应用提取。");
3964
- if (proposal.owner.mode !== "covered" || proposal.owner.name === void 0) return err("该 proposal 未覆盖 owner(owner-gap),不能应用。");
3965
- target = proposal.owner.name;
3966
- heading = proposal.parts[0]?.heading ?? "";
3967
- proposalOutcome = proposal.outcome === "extract" || proposal.outcome === "mixed" ? proposal.outcome : void 0;
3968
- extractItems = proposal.parts.map((part) => ({
3969
- heading: part.heading,
3970
- ...part.anchor.start === void 0 ? {} : { start: part.anchor.start },
3971
- ...part.anchor.end === void 0 ? {} : { end: part.anchor.end },
3972
- to_skill: target
3973
- }));
3974
- } else {
3975
- 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");
3978
- start = typeof startFlag === "string" ? startFlag : void 0;
3979
- end = typeof endFlag === "string" ? endFlag : void 0;
3980
- extractItems = [{
3981
- heading,
3982
- ...start === void 0 ? {} : { start },
3983
- ...end === void 0 ? {} : { end },
3984
- to_skill: target
3985
- }];
4350
+ break;
3986
4351
  }
3987
- const ownerCovers = extractParsed.flags.has("owner-covers");
3988
- const outcomeFlag = extractParsed.flags.get("outcome");
3989
- if (outcomeFlag !== void 0 && outcomeFlag !== "extract" && outcomeFlag !== "mixed") return err("--outcome 只能是 extract 或 mixed。");
3990
- const library = newSkillLibrary({
3991
- authority: authorityFrom({ origin: "foreground" }),
3992
- config: { root: skillsRootValue },
3993
- io: ioRegistry.provider(),
3994
- ctx,
3995
- threatExemptLabels: config.threatExemptLabels,
3996
- limits: {
3997
- ...DEFAULT_SKILL_LIMITS,
3998
- ...policyStageLimits(ctx.get("evolutionPolicy")?.get?.())
4352
+ case "maintain.handoff": {
4353
+ const maintainHandoff = maintainSub("handoff");
4354
+ if (maintainHandoff !== null) {
4355
+ const registry = runs;
4356
+ if (!registry) return err("未挂载 evolution-io 注册表:无法交付报告。");
4357
+ const synced = await syncRuns(registry);
4358
+ const wanted = maintainHandoff.positionals[1];
4359
+ if (wanted === void 0 && !synced.ok) return err(unreadableIndex(synced.note));
4360
+ const record = wanted === void 0 ? newestRun(registry) : registry.find(wanted);
4361
+ if (!record) {
4362
+ if (wanted !== void 0) {
4363
+ if (!synced.ok) return err(unreadableForId(wanted, synced.note));
4364
+ return err(`本 home 里没有 ${wanted} 这次运行:用 /evolution maintain status 查看最近的几次。`);
4365
+ }
4366
+ return err("本 home 还没有维护运行记录:用 /evolution maintain 启动一次。");
4367
+ }
4368
+ if (wanted === void 0 && record.state === "running") return err(`最新一次运行 ${record.id} 仍在进行:它结束后才会出报告;用 /evolution maintain status ${record.id} 查看进度。`);
4369
+ const ioRegistry = ctx.get("evolutionIo");
4370
+ if (!ioRegistry) return err("未挂载 evolution-io 注册表:无法交付报告。");
4371
+ const probed = await readRunReport(ioRegistry.provider(), record);
4372
+ if (probed.kind === "missing") return err(`运行 ${record.id}(${record.state})没有结果:没有写出报告${record.failure === void 0 ? "" : `(${record.failure})`}。`);
4373
+ if (probed.kind === "unknown") return err(`运行 ${record.id} 有报告但读不出来(${probed.reason}):这「不是」没有结果。`);
4374
+ const missingAgent = agentMissing("handoff");
4375
+ if (missingAgent) return missingAgent;
4376
+ const woke = deliverHandoff(invocationAgent, createUserMessage({
4377
+ content: [{
4378
+ type: "text",
4379
+ text: handoffPrompt({
4380
+ runId: record.id,
4381
+ reportPath: reportDigestPath(record),
4382
+ verdict: probed.report.verdict,
4383
+ recommendationCount: probed.report.recommendationCount,
4384
+ needsHumanCount: probed.report.needsHumanCount
4385
+ })
4386
+ }],
4387
+ source: {
4388
+ kind: "evolution-commands",
4389
+ form: "notice",
4390
+ summary: "maintenance report handoff"
4391
+ }
4392
+ }));
4393
+ if (woke === void 0) return err(hostError("e-305-the-invocation-agent-exposes", { a1: "this maintenance handoff" }));
4394
+ return ok(woke ? `已把运行 ${record.id} 交给模型 —— 报告:${reportDigestPath(record)}。它会读取该文件并执行其中的行动项。` : `已把运行 ${record.id} 交给模型并排队 —— 本宿主没有唤醒通道,因此会在你下一条消息时被读取。`);
3999
4395
  }
4000
- });
4001
- const built = await buildExtractPlanFromLibrary(library, {
4002
- source,
4003
- items: extractItems,
4004
- ...outcomeFlag === void 0 ? proposalOutcome === void 0 ? {} : { outcome: proposalOutcome } : { outcome: outcomeFlag },
4005
- ...ownerCovers ? { ownerCovers: true } : {}
4006
- });
4007
- if (!built.ok) return err(built.message);
4008
- const plan = built.plan;
4009
- const warnings = built.warnings === void 0 || built.warnings.length === 0 ? "" : "\n" + built.warnings.join("\n");
4010
- if (!extractParsed.flags.has("apply")) {
4011
- const proposal = proposalFromPlan(plan, { runId: "cli-" + Date.now().toString(36) });
4012
- const proposalPath = await writeProposalReport(ioRegistry.provider(), proposal).catch(() => {});
4013
- 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)"));
4396
+ break;
4014
4397
  }
4015
- if (approval) {
4016
- const session = invocationAgent?.session;
4017
- const sessionPolicy = effectiveSessionPolicy(ctx, session);
4018
- const stagesForeground = approval.isEnabled !== false && sessionPolicy !== "never" && approval.stageForeground !== false;
4019
- if (stagesForeground && session === void 0) return err(hostError("e-306-this-deployment-stages-foreground-2"));
4020
- if (stagesForeground && !approval.hasRunner("skill")) return err("无法暂存提取:没有注册技能回放运行器:请挂载 tool-skill-manage 行,或禁用 evolution-approval。");
4021
- const decision = await approval.request({
4022
- kind: "skill",
4023
- summary: "/evolution extract " + source + " -> " + target + " " + heading,
4024
- args: {
4025
- operation: {
4026
- action: "extract",
4027
- name: source,
4028
- extract: extractItems
4029
- },
4030
- origin: "foreground",
4031
- libraryOrigin: "foreground"
4032
- },
4033
- origin: "foreground",
4034
- ...session !== void 0 ? {
4035
- sessionId: session.id,
4036
- session
4037
- } : {},
4038
- ...sessionPolicy !== void 0 ? { sessionPolicy } : {}
4039
- });
4040
- if (decision.action === "staged") return ok(decision.message);
4398
+ case "propose": {
4399
+ const curator = ctx.get("evolutionCurator");
4400
+ if (!curator) return err(hostError("e-302-curator-service-not-mounted"));
4401
+ const result = await curator.proposeKeeps();
4402
+ return result.ok ? ok(result.message) : err(result.message);
4041
4403
  }
4042
- const result = await library.extract(plan, "foreground");
4043
- if (!result.ok) return err(result.message);
4044
- return ok(result.message + "\n提取判定:outcome=" + plan.outcome + ";target=" + target + warnings);
4045
- }
4046
- 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] ?? "";
4052
- if (name === "" || heading === "" || toFile === "") return err("用法:/evolution restructure <name> \"<heading>\" <to_file>");
4053
- const planFlag = restParsed.flags.get("plan");
4054
- const planRunId = typeof planFlag === "string" ? planFlag : void 0;
4055
- if (!toFile.startsWith("references/")) return err("to_file 必须位于 references/ 之下(日志或明细的落地位置)。");
4056
- const ioRegistry = ctx.get("evolutionIo");
4057
- if (!ioRegistry) return err("未挂载 evolution-io 注册表:无法重构。");
4058
- if (approval) {
4059
- const session = invocationAgent?.session;
4060
- const sessionPolicy = effectiveSessionPolicy(ctx, session);
4061
- const stagesForeground = approval.isEnabled !== false && sessionPolicy !== "never" && approval.stageForeground !== false;
4062
- if (stagesForeground && session === void 0) return err(hostError("e-306-this-deployment-stages-foreground-2"));
4063
- if (stagesForeground && !approval.hasRunner("skill")) return err("无法暂存重构:没有注册技能回放运行器:请挂载 tool-skill-manage 行(evolution-agent 预设或 evolution-all),或禁用 evolution-approval。");
4064
- const decision = await approval.request({
4065
- kind: "skill",
4066
- summary: `/evolution restructure ${name}${planRunId ? ` (plan ${planRunId})` : ""}`,
4067
- args: {
4068
- operation: {
4069
- action: "restructure",
4070
- name,
4071
- restructure: [{
4072
- heading,
4073
- to_file: toFile
4074
- }]
4075
- },
4076
- origin: "foreground",
4077
- libraryOrigin: "foreground"
4078
- },
4079
- origin: "foreground",
4080
- ...session !== void 0 ? {
4081
- sessionId: session.id,
4082
- session
4083
- } : {},
4084
- ...sessionPolicy !== void 0 ? { sessionPolicy } : {}
4085
- });
4086
- if (decision.action === "staged") return ok(`${decision.message}${planRunId ? `\n[audit] plan=${planRunId}` : ""}`);
4404
+ case "skills.refresh":
4405
+ ctx.emit("evolution/skills-refresh");
4406
+ return ok("已请求重读技能目录:缓存已丢弃,下次查询时重新读取。");
4407
+ case "replay": {
4408
+ const replay = ctx.get("evolutionReplay");
4409
+ if (!replay) return err(hostError("e-303-replay-service-not-mounted"));
4410
+ return ok(replay.compare().report);
4087
4411
  }
4088
- const result = await newSkillLibrary({
4089
- authority: authorityFrom({ origin: "foreground" }),
4090
- config: { root: skillsRootValue },
4091
- io: ioRegistry.provider(),
4092
- ctx,
4093
- threatExemptLabels: config.threatExemptLabels,
4094
- limits: {
4095
- ...DEFAULT_SKILL_LIMITS,
4096
- ...policyStageLimits(ctx.get("evolutionPolicy")?.get?.())
4412
+ case "maintain": {
4413
+ if (!isParseFailure(command) && command.name === "maintain" && command.flags.get("facts") === true && command.positionals.length === 0) {
4414
+ const ioRegistry = ctx.get("evolutionIo");
4415
+ if (!ioRegistry) return err("未挂载 evolution-io 注册表:维护事实不可用。");
4416
+ const library = newSkillLibrary({
4417
+ authority: authorityFrom({ origin: "foreground" }),
4418
+ config: { root: skillsRootValue },
4419
+ io: ioRegistry.provider(),
4420
+ ...mutationLockFrom(ctx) === void 0 ? {} : { mutationLock: mutationLockFrom(ctx) }
4421
+ });
4422
+ const enrichment = await buildEnrichment(ctx, library);
4423
+ const readFailures = [];
4424
+ const snapshots = await snapshotFromLibrary(library, {
4425
+ ...enrichmentSnapshotOptions(enrichment),
4426
+ onReadError: (name, error) => {
4427
+ readFailures.push(name);
4428
+ ctx.logger.warn(`evolution-maintenance: skipping unreadable skill "${name}": ${error instanceof Error ? error.message : String(error)}`);
4429
+ }
4430
+ });
4431
+ if (snapshots.length === 0 && readFailures.length > 0) return err(`维护扫描读不出 ${readFailures.length} 个已登记技能(${readFailures.slice(0, 10).join(", ")}${readFailures.length > 10 ? ", …" : ""}),且一个技能都没读到:技能库未被审计。请修好读不出的技能(或它们的目录名)后重新扫描`);
4432
+ if (snapshots.length === 0 && skillsRootValue !== "" && !await ioRegistry.provider().exists(skillsRootValue)) return err(`维护扫描发现技能库为空,但配置的技能根目录不存在(${skillsRootValue}):请把 skillsRoot 指向真实目录(字面量 \`~\` 不会被展开),然后重新扫描`);
4433
+ if (snapshots.length === 0) return ok("维护扫描:技能库为空,无需处理。");
4434
+ const { facts } = buildMaintainFacts(snapshots, enrichment.usageObservedValue, void 0);
4435
+ return ok(`维护事实(零 token 预览):\n${facts}`);
4097
4436
  }
4098
- }).restructure(name, [{
4099
- heading,
4100
- toFile
4101
- }], "foreground");
4102
- if (!result.ok) return err(result.message);
4103
- await ctx.get("skillUsage")?.record?.(name, "patch");
4104
- return ok(planRunId ? `${result.message}\n[audit] plan=${planRunId}` : result.message);
4105
- }
4106
- if (input === "replay") {
4107
- const replay = ctx.get("evolutionReplay");
4108
- if (!replay) return err(hostError("e-303-replay-service-not-mounted"));
4109
- return ok(replay.compare().report);
4110
- }
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")) {
4113
- const provider = ctx.get("settings");
4114
- const sections = /* @__PURE__ */ new Map();
4115
- if (provider?.describe !== void 0) try {
4116
- for (const descriptor of provider.describe({ redactSecrets: false })) {
4117
- const section = {};
4118
- if (descriptor.user !== void 0) section.user = descriptor.user;
4119
- const resolved = descriptor.value;
4120
- if (typeof resolved === "object" && resolved !== null) section.value = resolved;
4121
- sections.set(descriptor.ns, section);
4437
+ const maintainFlagsDeclared = [...isParseFailure(command) ? [] : command.flags.keys()].every((flag) => flagsOf("maintain").includes("--" + flag));
4438
+ if (!isParseFailure(command) && command.name === "maintain" && command.positionals.length === 0 && maintainFlagsDeclared) {
4439
+ const timeoutFlag = command.flags.get("timeout");
4440
+ const runTimeoutMs = typeof timeoutFlag === "string" ? Number(timeoutFlag) : config.maintainTimeoutMs ?? 6e5;
4441
+ 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)后重试。`);
4442
+ const registry = runs;
4443
+ if (!registry) return err("未挂载 evolution-io 注册表:维护扫描不可用。");
4444
+ const synced = await syncRuns(registry);
4445
+ if (!synced.ok) ctx.logger.warn(`evolution-commands: ${synced.note ?? "run index unreadable"} — the in-flight guard cannot see other processes' runs`);
4446
+ else if (synced.note !== void 0) ctx.logger.warn(`evolution-commands: ${synced.note}`);
4447
+ const ioRegistry = ctx.get("evolutionIo");
4448
+ if (!ioRegistry) return err("未挂载 evolution-io 注册表:维护扫描不可用。");
4449
+ const channel = createSubagentChannel(ctx);
4450
+ const running = registry.inFlight();
4451
+ if (running) {
4452
+ const elapsed = Math.max(1, Math.round((Date.now() - running.startedAt) / 1e3));
4453
+ return err(`维护运行 ${running.id} 已经在进行中(约 ${elapsed}s 前启动):现在重交会再开一次扫描。查看状态:/evolution maintain status ${running.id};停止它:/evolution maintain cancel ${running.id}。`);
4454
+ }
4455
+ const cooldownMs = clampedNumber(config.maintainCooldownMs, 3e4, { min: 0 });
4456
+ const lastSettled = registry.lastSettledAt();
4457
+ const sinceLast = lastSettled === void 0 ? Number.POSITIVE_INFINITY : Date.now() - lastSettled;
4458
+ if (cooldownMs > 0 && sinceLast < cooldownMs) {
4459
+ const remaining = Math.ceil((cooldownMs - sinceLast) / 1e3);
4460
+ const latest = registry.runs().find((record) => record.state !== "running");
4461
+ return err(`维护冷却中(${remaining}s)${latest === void 0 ? "" : `,最近一次运行 ${latest.id}`}:现在重跑会再消耗一次模型调用。`);
4462
+ }
4463
+ const runHome = evolutionHome();
4464
+ const runRoot = evolutionRoot();
4465
+ const runAgent = invocationAgent;
4466
+ const handle = await registry.begin("maintain");
4467
+ (async () => {
4468
+ try {
4469
+ const library = newSkillLibrary({
4470
+ authority: authorityFrom({ origin: "foreground" }),
4471
+ config: { root: skillsRootValue },
4472
+ io: ioRegistry.provider(),
4473
+ ...mutationLockFrom(ctx) === void 0 ? {} : { mutationLock: mutationLockFrom(ctx) }
4474
+ });
4475
+ const enrichment = await buildEnrichment(ctx, library);
4476
+ const outcome = await runMaintain({
4477
+ library,
4478
+ channel,
4479
+ parent: invocation.agent,
4480
+ evolutionPolicy: { get: () => ctx.get("evolutionPolicy")?.get() },
4481
+ tools: { get: (name) => ctx.get("tools")?.get(name) },
4482
+ logger: { warn: (message) => {
4483
+ ctx.logger.warn(message);
4484
+ } },
4485
+ rootExists: skillsRootValue === "" ? void 0 : () => ioRegistry.provider().exists(skillsRootValue),
4486
+ skillRoot: skillsRootValue
4487
+ }, {
4488
+ timeoutMs: runTimeoutMs,
4489
+ signal: handle.signal,
4490
+ runId: handle.id,
4491
+ enrichment: () => enrichment
4492
+ });
4493
+ const endedAt = Date.now();
4494
+ const resultRef = await writeMaintainReport(ioRegistry.provider(), {
4495
+ runId: handle.id,
4496
+ ...outcome.ok ? {
4497
+ verdict: outcome.verdict,
4498
+ recommendationCount: outcome.recommendationCount,
4499
+ items: outcome.items,
4500
+ notes: outcome.notes,
4501
+ forcedHuman: outcome.forcedHuman,
4502
+ needsHumanCount: outcome.needsHumanCount
4503
+ } : {},
4504
+ ...outcome.ok ? {} : { failure: handle.signal.aborted ? "cancelled: the scan was stopped before it settled" : outcome.error ?? "Maintenance scan failed." },
4505
+ startedAt: handle.startedAt,
4506
+ endedAt,
4507
+ text: outcome.text ?? ""
4508
+ }, (message) => {
4509
+ ctx.logger.warn(message);
4510
+ }, runHome, ctx.get("evolutionMutationAuthority")?.homeFence);
4511
+ if (resultRef !== void 0) {
4512
+ if (!isPresent(await probeMtime(ioRegistry.provider(), resultRef))) {
4513
+ await registry.settle(handle.id, {
4514
+ state: "failed",
4515
+ failure: "the maintain report file is missing at settle time (write/io race) — the scan result was not persisted."
4516
+ });
4517
+ return;
4518
+ }
4519
+ }
4520
+ const state = outcome.ok ? "succeeded" : handle.signal.aborted ? "cancelled" : "failed";
4521
+ await registry.settle(handle.id, {
4522
+ state,
4523
+ ...resultRef === void 0 ? {} : { resultRef },
4524
+ ...outcome.ok ? {} : { failure: handle.signal.aborted ? "cancelled: the scan was stopped before it settled" : outcome.error ?? "Maintenance scan failed." }
4525
+ });
4526
+ if (outcome.ok) {
4527
+ appendEvolutionEvent(ioRegistry.provider(), eventsFile(runRoot), {
4528
+ type: "maintain",
4529
+ source: "manual",
4530
+ runId: handle.id,
4531
+ verdict: outcome.verdict,
4532
+ recommendations: outcome.recommendationCount
4533
+ }).catch((error) => {
4534
+ ctx.logger.warn(`evolution-commands: failed to record maintain event: ${String(error)}`);
4535
+ });
4536
+ if (liveBool(config.maintainHandoffOnSettle) && resultRef !== void 0 && runAgent !== void 0) try {
4537
+ if (deliverHandoff(runAgent, createUserMessage({
4538
+ content: [{
4539
+ type: "text",
4540
+ text: handoffPrompt({
4541
+ runId: handle.id,
4542
+ reportPath: reportDigestPath({
4543
+ id: handle.id,
4544
+ resultRef
4545
+ }),
4546
+ verdict: outcome.verdict,
4547
+ recommendationCount: outcome.recommendationCount,
4548
+ needsHumanCount: outcome.needsHumanCount
4549
+ })
4550
+ }],
4551
+ source: {
4552
+ kind: "evolution-commands",
4553
+ form: "notice",
4554
+ summary: "maintenance report handoff (auto)"
4555
+ }
4556
+ })) === void 0) ctx.logger.warn(`evolution-commands: the automatic report handoff for run ${handle.id} could not be delivered — this host exposes neither followup nor inject; the report is at ${reportDigestPath({
4557
+ id: handle.id,
4558
+ resultRef
4559
+ })}`);
4560
+ } catch (error) {
4561
+ ctx.logger.warn(`evolution-commands: automatic report handoff failed (${String(error)})`);
4562
+ }
4563
+ } else ctx.logger.warn(`evolution-commands: maintenance run ${handle.id} produced no plan (${outcome.error ?? "原因未知"})`);
4564
+ } catch (error) {
4565
+ const aborted = handle.signal.aborted;
4566
+ const failure = aborted ? "cancelled: the scan was stopped before it settled" : `Maintenance scan failed: ${error instanceof Error ? error.message : String(error)}`;
4567
+ await registry.settle(handle.id, {
4568
+ state: aborted ? "cancelled" : "failed",
4569
+ failure
4570
+ });
4571
+ ctx.logger.warn(`evolution-commands: maintenance run ${handle.id} threw (${failure})`);
4572
+ }
4573
+ })();
4574
+ return ok([
4575
+ `Maintenance run ${handle.id} started — the scan keeps running after this reply.`,
4576
+ `- status: /evolution maintain status ${handle.id}`,
4577
+ `- result: /evolution maintain report ${handle.id}`,
4578
+ `- stop: /evolution maintain cancel ${handle.id}`
4579
+ ].join("\n"));
4122
4580
  }
4123
- } catch (error) {
4124
- return err(hostError("e-307-the-settings-service-could", { a1: error instanceof Error ? error.message : String(error) }));
4581
+ break;
4125
4582
  }
4126
- const rows = paramSurfaceRows(sections, PARAM_EXPOSURE);
4127
- const groupFlag = paramsParsed.flags.get("group");
4128
- const group = typeof groupFlag === "string" ? groupFlag : void 0;
4129
- const selected = group === void 0 ? rows : rows.filter((row) => row.group === group);
4130
- if (group !== void 0 && selected.length === 0) return err(hostError("e-308-unknown-parameter-group-group", {
4131
- a1: group,
4132
- a2: paramGroups(PARAM_EXPOSURE).join(", ")
4133
- }));
4134
- if (paramsParsed.flags.get("json") === true) return ok(renderParamJson(selected));
4135
- return ok(renderParamRows(selected, { providerMounted: provider !== void 0 }));
4583
+ default: break;
4136
4584
  }
4137
- if (input === "doctor" || input === "doctor --json") {
4138
- const mountedForDoctor = presetProfileTarget(ctx);
4139
- const mounted = mountedForDoctor === void 0 ? {} : { mounted: {
4140
- profile: mountedForDoctor.profile,
4141
- dir: mountedForDoctor.profileDir,
4142
- bundles: mountedForDoctor.bundles
4143
- } };
4144
- const report = await diagnose(ctx, {
4145
- home: evolutionRoot(),
4146
- ...mounted,
4147
- runs: doctorRuns()
4148
- });
4149
- if (input === "doctor --json") return ok(JSON.stringify(report, null, 2));
4150
- return ok(renderDoctorText(report, hostLocale));
4585
+ if (input === "consolidate" || input.startsWith("consolidate ")) {
4586
+ const plan = /--plan\s+(\S+)/.exec(input)?.[1];
4587
+ return err("`consolidate` 已退出用户面:机械追加由 curator 归档收尾,人类合成用 `/evolution merge pair <a> <b>`。" + (plan === void 0 ? "" : "\n旧 --plan 审计只读保留:" + plan));
4151
4588
  }
4589
+ 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);
4152
4590
  if (input === "" || input === "help") return ok(hostCommandText(hostLocale, "help.header") + "\n" + renderHelpText(hostLocale));
4153
4591
  return err("/evolution " + input + " " + hostCommandText(hostLocale, "help.unknown") + "\n" + renderHint());
4154
4592
  } };
@@ -4218,28 +4656,5 @@ function apply(ctx, rawConfig = {}) {
4218
4656
  runMigrationOnce();
4219
4657
  })();
4220
4658
  }
4221
- /**
4222
- * 0.3.14 (P1-1): locate the installed `dsh-evolution-agent-preset` package
4223
- * (the delivery container for agent.cordis.yml/bases.json). Resolution order:
4224
- * npm-name sibling (published profile layout), dev-tree sibling (source/test
4225
- * layout), then module resolution. The package dir name differs from the npm
4226
- * name (`evolution-agent` vs `@lmzhen/dsh-evolution-agent-preset` — the rc.44
4227
- * dir≠name trap), so BOTH sibling shapes are probed.
4228
- */
4229
- /** The agent-preset base table (evolution-agent/bases.json). The installer
4230
- * (install-layered.mjs) reads the SAME file — the literal that used to live in
4231
- * each of them is what kept this path on `standard` while the installer knew
4232
- * `ptc` too. Fails loud: a missing table is an incomplete install, never a
4233
- * silent fallback to the default base. */
4234
- function safeStagedArgs(args) {
4235
- try {
4236
- const json = JSON.stringify(args);
4237
- if (typeof json !== "string") return "(unserializable)";
4238
- if (json.length > 500) return `${json.slice(0, 500)}…(truncated ${json.length - 500} chars)`;
4239
- return json;
4240
- } catch {
4241
- return "(unserializable)";
4242
- }
4243
- }
4244
4659
  //#endregion
4245
4660
  export { Config, aliasRegistration, apply, atomicWriteFiles, buildSurface, name, parseCommand };