@lmzhen/dsh-evolution-core 0.44.0 → 0.46.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.
Files changed (62) hide show
  1. package/lib/authority-plugin.js +14 -0
  2. package/lib/composition/index.js +2 -2
  3. package/lib/{composition-CVafrlEw.js → composition-Da8NfRI7.js} +2 -2
  4. package/lib/contract.js +1 -0
  5. package/lib/index.js +54 -133
  6. package/lib/{mutations-jUuOPaCn.js → io-AmUf4lVY.js} +54 -84
  7. package/lib/io-node.js +24 -0
  8. package/lib/io-registry.js +96 -0
  9. package/lib/mutation-authority-DeJ_Wz14.js +537 -0
  10. package/lib/mutations-DwvbjRHF.js +75 -0
  11. package/lib/numeric-DLeLvvGb.js +324 -0
  12. package/lib/platform/index.js +1 -1
  13. package/lib/{platform-B06_h8t-.js → platform-CFA12Jam.js} +36 -19
  14. package/lib/policy.js +99 -0
  15. package/lib/runtime/plugin.js +8 -1
  16. package/lib/{skill-health-BLGZTIv8.js → skill-health-D1pZGk5V.js} +6 -835
  17. package/lib/{skill-history-_Cssts5o.js → skill-history-CjypdYqv.js} +2 -1
  18. package/lib/skills.js +6 -3
  19. package/lib/subagent/index.js +1 -1
  20. package/lib/types/authority-plugin.d.ts +12 -0
  21. package/lib/types/authority-plugin.js +10 -0
  22. package/lib/types/authority.d.ts +96 -0
  23. package/lib/types/authority.js +237 -0
  24. package/lib/types/contract.d.ts +116 -0
  25. package/lib/types/contract.js +10 -0
  26. package/lib/types/events.d.ts +2 -2
  27. package/lib/types/home-fence.d.ts +25 -17
  28. package/lib/types/home-fence.js +42 -92
  29. package/lib/types/index.d.ts +2 -2
  30. package/lib/types/index.js +2 -2
  31. package/lib/types/io-node.d.ts +15 -0
  32. package/lib/types/io-node.js +36 -0
  33. package/lib/types/io-registry.d.ts +71 -0
  34. package/lib/types/io-registry.js +126 -0
  35. package/lib/types/io.d.ts +29 -2
  36. package/lib/types/io.js +50 -9
  37. package/lib/types/journal-protocol.d.ts +35 -0
  38. package/lib/types/journal-protocol.js +29 -0
  39. package/lib/types/lease-store.d.ts +1 -1
  40. package/lib/types/mutation-unit.d.ts +1 -1
  41. package/lib/types/params.d.ts +2 -16
  42. package/lib/types/params.js +6 -44
  43. package/lib/types/platform/llm.js +4 -1
  44. package/lib/types/platform/projections.d.ts +10 -4
  45. package/lib/types/platform/projections.js +34 -17
  46. package/lib/types/platform-services.d.ts +2 -2
  47. package/lib/types/policy.d.ts +68 -0
  48. package/lib/types/policy.js +161 -0
  49. package/lib/types/run-registry.d.ts +2 -2
  50. package/lib/types/runtime/projections.js +12 -0
  51. package/lib/types/state-store.d.ts +1 -1
  52. package/lib/types/state-store.js +1 -1
  53. package/lib/types/store-ledger.js +2 -2
  54. package/lib/types/write-inventory.js +3 -1
  55. package/lib/write.js +2 -2
  56. package/package.json +25 -4
  57. package/persisted-write-inventory.json +10 -37
  58. package/lib/types/home-owner.d.ts +0 -4
  59. package/lib/types/home-owner.js +0 -37
  60. package/lib/types/tree-lock.d.ts +0 -54
  61. package/lib/types/tree-lock.js +0 -127
  62. package/lib/{ensure-BjToTMMj.js → ensure-C5Mo1dbB.js} +1 -1
@@ -0,0 +1,75 @@
1
+ import { a as nodeEvolutionIo, s as transactIo } from "./io-AmUf4lVY.js";
2
+ import { n as isRecord } from "./guards-3f02mnf2.js";
3
+ import { join } from "node:path";
4
+ import { createHash } from "node:crypto";
5
+ //#region lib/types/mutations.js
6
+ /**
7
+ * Curator/author audit trail: `.mutations.json` records every skill mutation
8
+ * with before/after content hashes so any automated edit is reviewable and
9
+ * replayable. Best-effort persistence, mirroring the usage sidecar posture.
10
+ * @module @lmzhen/dsh-evolution-core
11
+ */
12
+ const DEFAULT_MUTATION_CAP = 500;
13
+ /** Version of the `.mutations.json` file shape; writers always emit the current one. */
14
+ const MUTATIONS_FILE_VERSION = 1;
15
+ function mutationsFile(root) {
16
+ return join(root, ".mutations.json");
17
+ }
18
+ function contentHash(content) {
19
+ return createHash("sha256").update(content.replaceAll("\r\n", "\n")).digest("hex");
20
+ }
21
+ /**
22
+ * Parse a raw mutations sidecar; malformed content reads as empty (auditing is
23
+ * best-effort). Versioned shape ({ version, records }) with legacy
24
+ * plain-array compat, plus a field-level guard for records without the
25
+ * required identity/timestamp fields (rc.42 audit P2-3).
26
+ */
27
+ function parseMutationRecords(raw) {
28
+ if (raw === null) return [];
29
+ try {
30
+ return recordsFromParsed(JSON.parse(raw));
31
+ } catch {
32
+ return [];
33
+ }
34
+ }
35
+ /** Field-level shape guard shared by the parse and the recordMutation write
36
+ * path (P3/v15: the guard's JSON.parse and this parse used to run twice over
37
+ * the same bytes inside one transact). */
38
+ function recordsFromParsed(parsed) {
39
+ return (Array.isArray(parsed) ? parsed : typeof parsed === "object" && parsed !== null && Array.isArray(parsed.records) ? parsed.records : []).filter((entry) => typeof entry === "object" && entry !== null && typeof entry.skillName === "string" && typeof entry.action === "string" && typeof entry.at === "string");
40
+ }
41
+ async function loadMutations(root, io = nodeEvolutionIo()) {
42
+ return parseMutationRecords(await io.readText(mutationsFile(root)));
43
+ }
44
+ /** Append one record, trim to `cap`, and write atomically (versioned shape). */
45
+ async function recordMutation(root, io, record, cap = 500, fence) {
46
+ const write = async () => {
47
+ await transactIo(io, mutationsFile(root), (current) => {
48
+ let parsed = [];
49
+ if (current !== null) try {
50
+ parsed = JSON.parse(current);
51
+ } catch {
52
+ console.warn(`mutation audit record dropped: ${mutationsFile(root)} is malformed and was not overwritten`);
53
+ return current;
54
+ }
55
+ if (isRecord(parsed)) {
56
+ const version = parsed.version;
57
+ if (typeof version === "number" && version > 1) {
58
+ console.warn(`mutation audit record dropped: ${mutationsFile(root)} declares version ${version} (newer than 1); not overwritten`);
59
+ return current;
60
+ }
61
+ }
62
+ const existing = recordsFromParsed(parsed);
63
+ existing.push(record);
64
+ const trimmed = existing.length > cap ? existing.slice(existing.length - cap) : existing;
65
+ return JSON.stringify({
66
+ version: 1,
67
+ records: trimmed
68
+ }, null, 2);
69
+ });
70
+ };
71
+ if (fence !== void 0) await fence.run(write);
72
+ else await write();
73
+ }
74
+ //#endregion
75
+ export { mutationsFile as a, loadMutations as i, MUTATIONS_FILE_VERSION as n, recordMutation as o, contentHash as r, DEFAULT_MUTATION_CAP as t };
@@ -0,0 +1,324 @@
1
+ //#region lib/types/constants.js
2
+ /**
3
+ * Shared constants for the dsh-evolution plugin family.
4
+ *
5
+ * Two classes of value live here, deliberately separated by section so future
6
+ * edits do not blur the semantic boundary:
7
+ *
8
+ * 1. **Fixed protocol/format/security invariants** — changing these breaks an
9
+ * on-disk format, a naming/format contract, a path-security boundary, or a
10
+ * cross-component invariant. They are NOT exposed as deployment config.
11
+ *
12
+ * 2. **Cross-package shared tunable defaults** — the same semantic default is
13
+ * read (with a config override path) by more than one package (e.g.
14
+ * `evolution-policy` and `evolution-curator` both default `staleAfterDays`
15
+ * to 30). Centralizing them here means one authoritative default: a config
16
+ * override still applies per package, but the fallback is single-sourced.
17
+ *
18
+ * Package-private tunables (used by exactly one package) stay in that package,
19
+ * not here — see evolution-replay's `DEFAULT_WEIGHTS` and evolution-feedback's
20
+ * threshold, which are intentionally left where they are used.
21
+ * @module @lmzhen/dsh-evolution-core
22
+ */
23
+ /**
24
+ * Required argument names per `skill_manage` action — the SINGLE SOURCE read
25
+ * by the tool's argument gate (tool-skill-manage write-gates.ts) and the plan
26
+ * validator (evolution-plan-validator), so the two can never drift.
27
+ * OPT-05 (2026-09): the plan validator used to accept a `write_file`/
28
+ * `remove_file` op without `file_path` while the executor required it — the
29
+ * staged write then failed at EVERY approve until rejected.
30
+ * Rows here are the op-level requirements only: `delete` additionally
31
+ * requires `absorbed_into` at the PLAN layer (review passes may only delete
32
+ * into an umbrella) and `pin`/`unpin` are tool-only actions — each consumer
33
+ * adds its own extras on top of this table. An empty-string argument is NOT
34
+ * caught here (the tool's gate deliberately lets it reach the library for a
35
+ * more specific remedy message); the validator adds its own `.trim()`
36
+ * emptiness checks for payload fields.
37
+ */
38
+ const SKILL_ACTION_REQUIRED_FIELDS = {
39
+ create: ["name", "content"],
40
+ edit: ["name", "content"],
41
+ update: ["name", "content"],
42
+ patch: [
43
+ "name",
44
+ "old_string",
45
+ "new_string"
46
+ ],
47
+ delete: ["name"],
48
+ write_file: [
49
+ "name",
50
+ "file_path",
51
+ "file_content"
52
+ ],
53
+ remove_file: ["name", "file_path"],
54
+ restructure: ["name"],
55
+ pin: ["name"],
56
+ unpin: ["name"]
57
+ };
58
+ /** Skill frontmatter `name` validated for the file name (lowercase + hyphen).
59
+ * 计划 B-4 (v18): tightened to the UPSTREAM `SKILL_NAME` shape
60
+ * (`/^[a-z0-9]+(?:-[a-z0-9]+)*$/`, packages/skill/skill/src/index.ts:21). The
61
+ * old form admitted trailing/consecutive hyphens, which upstream
62
+ * `validateCandidate` throws on — and that throw aborts the WHOLE `ctx.skills`
63
+ * collection. The catalog provider still filters such legacy tree entries so
64
+ * an existing tree cannot break a session. */
65
+ const SKILL_NAME_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
66
+ /** Allowed skill support-file subdirectories (path-traversal boundary). */
67
+ const SUPPORT_DIRS = [
68
+ "references",
69
+ "templates",
70
+ "scripts",
71
+ "assets"
72
+ ];
73
+ /** Delimiter between durable memory entries (on-disk storage format). */
74
+ const ENTRY_DELIMITER = "\n§\n";
75
+ /** Built-in skill names the curator must never lifecycle-manage. */
76
+ const PROTECTED_BUILTIN_SKILLS = new Set(["plan"]);
77
+ const MAX_SKILL_NAME_LENGTH = 64;
78
+ const MAX_DESCRIPTION_LENGTH = 1024;
79
+ const MAX_SKILL_CONTENT_CHARS = 1e5;
80
+ /** How many content versions to retain per skill (skill-history.ts). 20 mirrors the count
81
+ * KiroCrew settled on for the same job (its `MAX_SKILL_VERSIONS`), and is an E2 deployment
82
+ * parameter — the value is a retention policy, not a protocol constant. */
83
+ const DEFAULT_SKILL_VERSION_KEEP = 20;
84
+ /** The authoring DISCIPLINE band, taken from the upstream standard (archive §5):
85
+ * peer skills sit at 8-14k characters and a body pushing past 20k belongs in
86
+ * `references/*.md`. Deliberately separate from `MAX_SKILL_CONTENT_CHARS`: the
87
+ * hard ceiling is a deployment-tunable limit, this band is the authoring
88
+ * standard — deriving the band from the ceiling is exactly what let a 40k
89
+ * ceiling hide a 99k body without a single signal saying "split me" (V3). */
90
+ const AUTHORING_SPLIT_LINE_CHARS = 2e4;
91
+ /** Upstream's conversion basis for CHARACTER LIMITS: 2.75 chars/token, labelled
92
+ * model-independent in the config template (\`cli-config.yaml.example:538\`), and the
93
+ * basis behind every quoted token figure there — memory 2200 chars ≈ 800 tokens,
94
+ * user 1375 ≈ 500, SKILL.md 100_000 ≈ 36k (\`tools/skill_manager_tool.py:455\`).
95
+ * Limits are deliberately conservative, so this is the basis a BORROWED LIMIT must
96
+ * be converted with. */
97
+ const UPSTREAM_LIMIT_CHARS_PER_TOKEN = 2.75;
98
+ /** The platform's own estimate basis: \`CHARS_PER_TOKEN = 4\` in
99
+ * \`@deepseek-ai/dsh-token-meter/estimate.ts\` (its comment reads "used until exact
100
+ * tokenization is needed"), matching upstream's ESTIMATE-side heuristic — "~4
101
+ * chars/token is the usual English heuristic" (\`agent/prompt_builder.py:1179\`).
102
+ * Estimates use this; limits use the constant above. */
103
+ const PLATFORM_ESTIMATE_CHARS_PER_TOKEN = 4;
104
+ const MAX_SKILL_FILE_BYTES = 1048576;
105
+ const DEFAULT_REVIEW_MEMORY_INTERVAL = 10;
106
+ const DEFAULT_REVIEW_SKILL_INTERVAL = 10;
107
+ /** Skill-review completion channel trigger mode: 'cadence' | 'completion' | 'both'.
108
+ * 0.3.39 (V6-53 follow-up): default is 'cadence' — since 0.3.38 the cadence
109
+ * channel's review is executed at conversation END (deferred), so 'both' would
110
+ * inject a second (task-complete) prompt at the same boundary; the cadence
111
+ * deferral alone IS the end-of-conversation summary. */
112
+ const DEFAULT_SKILL_REVIEW_TRIGGER = "cadence";
113
+ /** Cumulative session tool calls before a session counts as "proven long" for the completion channel. */
114
+ const DEFAULT_SKILL_REVIEW_COMPLETION_MIN_TOOL_CALLS = 20;
115
+ const DEFAULT_SUBSTANTIVE_MIN_TOOL_CALLS = 3;
116
+ const DEFAULT_SUBSTANTIVE_MIN_USER_CHARS = 200;
117
+ const DEFAULT_SUBSTANTIVE_MIN_AGENT_CHARS = 500;
118
+ const DEFAULT_CURATOR_INTERVAL_HOURS = 168;
119
+ const DEFAULT_MIN_IDLE_HOURS = 2;
120
+ const DEFAULT_STALE_AFTER_DAYS = 30;
121
+ const DEFAULT_ARCHIVE_AFTER_DAYS = 90;
122
+ /**
123
+ * Support-file count above which `references-sprawl` warns. **NOT CALIBRATED YET** — 60 is a
124
+ * placeholder: the platform corpus is empty (no platform skills available here), so the admission
125
+ * band cannot be checked. Until `gen-health-baseline` reports both corpora, the rule is
126
+ * REPORT-ONLY: its count must not be shown as a number on any surface (plan G4 ③).
127
+ */
128
+ const SUPPORT_SPRAWL_FILES = 60;
129
+ const DEFAULT_MEMORY_CHAR_LIMIT = 2200;
130
+ const DEFAULT_USER_CHAR_LIMIT = 1375;
131
+ /** Consolidation-failure backoff cap, shared by MemoryStore and memory-files' Config default. */
132
+ const DEFAULT_CONSOLIDATION_FAILURES = 3;
133
+ /** F-20 (v18): the authored-body budget and the hard ceiling are the same
134
+ * number today. Derive it so a future divergence is one edit, not two names
135
+ * that silently disagree. */
136
+ const DEFAULT_SKILL_CONTENT_CHARS = MAX_SKILL_CONTENT_CHARS;
137
+ /** P3-19 (v14): defaults that were written twice (schema `.default()` AND the
138
+ * clamp fallback literal) now have one home per value. */
139
+ const DEFAULT_REVIEW_TIMEOUT_MS = 12e4;
140
+ const DEFAULT_REVIEW_CONTEXT_MESSAGES = 60;
141
+ const DEFAULT_REVIEW_MESSAGE_CHARS = 2e3;
142
+ const DEFAULT_CURATOR_BOOT_GRACE_SECONDS = 10;
143
+ const DEFAULT_CURATOR_REVIEW_MAX_TOKENS = 2048;
144
+ /** Threat-scan WINDOW SIZE (not a total cap — E-12: the whole text is scanned in
145
+ * overlapping windows, so content beyond this stays in scope). The coverage
146
+ * floor is `PATTERN_OVERLAP + 1` (V6-05). Single home for the core scanners'
147
+ * default parameter and clamp fallback, plus evolution-threat's Config default
148
+ * — the two packages previously wrote 65_536 independently (G0/S0.1). */
149
+ const DEFAULT_THREAT_MAX_SCAN_CHARS = 65536;
150
+ /** 0.3.17 (S3.10, T-1): control-plane fields a model-facing write call may
151
+ * never carry — single source for plan-validator, evolution-policy and the
152
+ * threat scanner (they used to each hardcode the list).
153
+ * P2-13 (v37): staged_from_sha256 joins the list — it is the replay's own
154
+ * staleness anchor, and the tool-arguments root is an OPEN object, so a model
155
+ * could otherwise choose the anchor that decides the write's outcome. */
156
+ const FORBIDDEN_CONTROL_KEYS = [
157
+ "policy",
158
+ "threshold",
159
+ "prompt_hash",
160
+ "model_route",
161
+ "evolution_config",
162
+ "staged_from_sha256"
163
+ ];
164
+ /** 0.3.17 (S3.10): the model-facing write tools the policy guard and threat
165
+ * scanner cover. */
166
+ const EVOLUTION_WRITE_TOOLS = ["memory", "skill_manage"];
167
+ /** Hermes authoring quality bar for descriptions (the 60-char Rule). The
168
+ * platform's own index limit stays in validateFrontmatter; this bar is the
169
+ * target the authoring standard names, enforced as ADVISORY feedback.
170
+ * 0.3.16 (T-4): moved here from skill-store.ts so drift-signals (pure, no IO)
171
+ * can reference it without importing the skill-store module. */
172
+ const AUTHORING_DESCRIPTION_BAR = 60;
173
+ /** The PLATFORM's default cap on the description a skill catalog shows —
174
+ * `catalogDescriptionMaxLength` on the platform's `tool-skill` row (default 500).
175
+ *
176
+ * Recorded here because it is the third number in the description-length relationship, and the one
177
+ * that is easiest to misread as a family rule: the family's own host/all rows SET that field to
178
+ * `AUTHORING_DESCRIPTION_BAR` (60), so what a family deployment truncates at is the ROW's value —
179
+ * this default only governs compositions that do not override it. It is NOT a refusal threshold:
180
+ * the only refusal is `MAX_DESCRIPTION_LENGTH` / the row's `maxDescriptionLength`, and the catalog
181
+ * cut is a view, not a validation. See tool-skill-manage/README.md for the three-number table. */
182
+ const PLATFORM_CATALOG_DESCRIPTION_DEFAULT = 500;
183
+ /** The split hint both size refusals share (0.5.0 V1). The same sentence used to
184
+ * be copied into validateFrontmatter AND the patch path, and neither copy named
185
+ * where the content should go — the upstream cap message names the destination
186
+ * directories, and that is the part a model actually acts on. */
187
+ const CONTENT_SPLIT_HINT = "建议拆成更小的 SKILL.md,把支撑文件放进 references/ 或 templates/。";
188
+ /** V27 G2.4: the largest millisecond delay a timer accepts. `AbortSignal.timeout`
189
+ * (and `setTimeout`) coerce anything larger to 1ms after a Node warning, so a
190
+ * timeout configured above this ceiling silently collapses to "immediately
191
+ * aborted". The curator's review timeout and the review timeout each carried
192
+ * their own copy of the literal; the bound is one protocol constant.
193
+ * (v19 P2-10 corrected the value from 2^32-1 to Node's real 2^31-1 ceiling.) */
194
+ const MAX_TIMER_DELAY_MS = 2147483647;
195
+ /**
196
+ * Model-facing budget of one `maintenance_probe` call (ms) — a HANG GUARD, not a
197
+ * performance knob.
198
+ *
199
+ * Measured (2026-10-10): one probe costs 188/220/225 ms on the deployed library
200
+ * (28 skills / 418 KB) and scales linearly at ~5.5 ms per skill (100 skills
201
+ * 0.4-0.6 s, 400 skills 1.9-2.5 s), so this default is ~50x the worst measured
202
+ * case and ~600x the deployed one — it will not fire in normal use, and the
203
+ * ~305 s desktop interaction wall is ~5e4 skills away.
204
+ *
205
+ * It exists for the state the probe cannot report itself: a provider that never
206
+ * answers. The platform's tool-timeout guard reads this budget off the tool
207
+ * definition and turns the hang into a diagnosable `tool call timed out after
208
+ * <ms>ms` error result, instead of a request that ends with nothing to read.
209
+ * Reopen the default when the library approaches ~1e4 skills, when the
210
+ * `evolutionIo` provider stops being local, or when a model leg enters a tool's
211
+ * execute (the same conditions the probe's own note lists).
212
+ */
213
+ const DEFAULT_PROBE_TIMEOUT_MS = 12e4;
214
+ /** V27 G2.4: the model each review/curation leg defaults to. The policy schema,
215
+ * the policy resolver and the curator's LLM nomination pass each carried their
216
+ * own copy of these strings — a deployment that changed the policy default used
217
+ * to leave the curator passing a different model than the reviews. */
218
+ const DEFAULT_CURATOR_MODEL = "deepseek-v4-pro";
219
+ /** Order of the `evolution:memory-guidance` section (before the skills one). */
220
+ const MEMORY_GUIDANCE_SECTION_ORDER = 11e3;
221
+ /** Order of the `evolution-skills-guidance` section (last of the two). */
222
+ const SKILLS_GUIDANCE_SECTION_ORDER = 11100;
223
+ //#endregion
224
+ //#region lib/types/limits.js
225
+ /**
226
+ * Skill content limits: the byte/char budgets every write path validates against.
227
+ *
228
+ * Split out of skill-store.ts (S2-1) so the frontmatter validators and the
229
+ * store share one declaration site. Re-exported by skill-store.ts: the package
230
+ * export surface is unchanged.
231
+ */
232
+ /** `verify` checks that every cited target exists and otherwise allows the move;
233
+ * `refuse` restores the pre-0.5 behaviour of refusing ANY citation-carrying
234
+ * section. Resolved at the call site, so every existing limits object keeps
235
+ * working (unknown policy never silently changes a write path). */
236
+ const DEFAULT_CITATION_POLICY = "verify";
237
+ /** Default: report the plan on refusal, never write (behaviour unchanged). */
238
+ const DEFAULT_REFERENCE_REWRITE_POLICY = "plan";
239
+ /** Default: report-only, because upstream's hard invariant is never to delete. */
240
+ const DEFAULT_ARCHIVE_RETENTION_POLICY = "report";
241
+ /** Default: report, so the cap cannot brick an existing oversize file on upgrade
242
+ * (the live library carries a 189k-character release log today). */
243
+ const DEFAULT_SUPPORT_FILE_CHAR_POLICY = "report";
244
+ /** The four stage defaults in ONE object, so the policy schema's `z.default(...)`
245
+ * calls and the store's fallbacks cannot drift apart. */
246
+ const POLICY_STAGE_DEFAULTS = Object.freeze({
247
+ citationPolicy: DEFAULT_CITATION_POLICY,
248
+ referenceRewrite: DEFAULT_REFERENCE_REWRITE_POLICY,
249
+ archiveRetention: DEFAULT_ARCHIVE_RETENTION_POLICY,
250
+ supportFileCharPolicy: DEFAULT_SUPPORT_FILE_CHAR_POLICY
251
+ });
252
+ /**
253
+ * The ONE conversion from the deployment policy snapshot to library limits
254
+ * (design §16.7): every plugin that owns a writable SkillLibrary spreads this into
255
+ * its limits, so a stage selected in cordis.yml reaches every write path. A
256
+ * per-plugin copy would be the third home for the same threshold.
257
+ *
258
+ * Only PRESENT fields are copied: an absent policy field must fall through to the
259
+ * library default rather than pinning `undefined` onto an optional limit (which
260
+ * `exactOptionalPropertyTypes` forbids and which would defeat the `?? DEFAULT`
261
+ * resolution inside the store).
262
+ * @param snapshot - the evolutionPolicy snapshot, or undefined when unmounted.
263
+ * @returns the stage fields the snapshot actually carries.
264
+ */
265
+ function policyStageLimits(snapshot) {
266
+ if (snapshot === void 0) return {};
267
+ const stages = {};
268
+ if (snapshot.citationPolicy !== void 0) stages.citationPolicy = snapshot.citationPolicy;
269
+ if (snapshot.referenceRewrite !== void 0) stages.referenceRewrite = snapshot.referenceRewrite;
270
+ if (snapshot.archiveRetention !== void 0) stages.archiveRetention = snapshot.archiveRetention;
271
+ if (snapshot.supportFileCharPolicy !== void 0) stages.supportFileCharPolicy = snapshot.supportFileCharPolicy;
272
+ return stages;
273
+ }
274
+ const DEFAULT_SKILL_LIMITS = {
275
+ maxNameLength: 64,
276
+ maxDescriptionLength: MAX_DESCRIPTION_LENGTH,
277
+ maxSkillContentChars: MAX_SKILL_CONTENT_CHARS,
278
+ maxSkillFileBytes: MAX_SKILL_FILE_BYTES,
279
+ versionKeep: 20
280
+ };
281
+ //#endregion
282
+ //#region lib/types/numeric.js
283
+ /**
284
+ * Numeric config clamping for the dsh-evolution plugin family.
285
+ *
286
+ * G3.1 (0.3.23): numeric configuration values are normalised through a single
287
+ * helper so 0 / negative / NaN / ±Infinity / out-of-range all fall back to the
288
+ * package default instead of silently becoming a "disabled" special value or
289
+ * folding as NaN into a computation. A non-finite value (NaN, ±Infinity) is
290
+ * never a legitimate config, so it always falls back. The schema layer (a
291
+ * `.min(1)` clamp on the number schema) is a first-line guard where it can
292
+ * reject invalid values; this helper is the mandatory assembly-time clamp that
293
+ * also catches what schemastery lets through (NaN and +Infinity both pass a
294
+ * bare number schema).
295
+ *
296
+ * The scope here is pure numeric conversion only (no schemastery import), so
297
+ * evolution-core stays free of a schemastery dependency. Per-package Config
298
+ * schemas keep their own `.min()`/`.default()` call sites.
299
+ * @module @lmzhen/dsh-evolution-core
300
+ */
301
+ /**
302
+ * Clamp a numeric config to the `[min, max]` range.
303
+ *
304
+ * A non-finite value (NaN, ±Infinity), a non-number, or a value outside the
305
+ * inclusive range falls back to `fallback`. When `opts.min >= 1`, 0 and
306
+ * negative values also fall back to `fallback` — a 0 is never treated as a
307
+ * special "disabled" meaning (G3.1 decision). Callers that legitimately allow
308
+ * 0 (e.g. a threshold or a zero-cost weight) pass `{ min: 0 }` or omit the
309
+ * range.
310
+ *
311
+ * @param value - the raw numeric config, possibly `undefined` (absent).
312
+ * @param fallback - the default value to return when the value is invalid.
313
+ * @param opts - optional inclusive lower/upper bound.
314
+ * @returns `value` when it is a finite number within range, else `fallback`.
315
+ */
316
+ function clampedNumber(value, fallback, opts) {
317
+ if (typeof value !== "number" || !Number.isFinite(value)) return fallback;
318
+ const { min, max } = opts ?? {};
319
+ if (min !== void 0 && value < min) return fallback;
320
+ if (max !== void 0 && value > max) return fallback;
321
+ return value;
322
+ }
323
+ //#endregion
324
+ export { UPSTREAM_LIMIT_CHARS_PER_TOKEN as $, DEFAULT_STALE_AFTER_DAYS as A, MAX_SKILL_CONTENT_CHARS as B, DEFAULT_REVIEW_MESSAGE_CHARS as C, DEFAULT_SKILL_REVIEW_COMPLETION_MIN_TOOL_CALLS as D, DEFAULT_SKILL_CONTENT_CHARS as E, DEFAULT_USER_CHAR_LIMIT as F, PLATFORM_CATALOG_DESCRIPTION_DEFAULT as G, MAX_SKILL_NAME_LENGTH as H, ENTRY_DELIMITER as I, SKILLS_GUIDANCE_SECTION_ORDER as J, PLATFORM_ESTIMATE_CHARS_PER_TOKEN as K, EVOLUTION_WRITE_TOOLS as L, DEFAULT_SUBSTANTIVE_MIN_TOOL_CALLS as M, DEFAULT_SUBSTANTIVE_MIN_USER_CHARS as N, DEFAULT_SKILL_REVIEW_TRIGGER as O, DEFAULT_THREAT_MAX_SCAN_CHARS as P, SUPPORT_SPRAWL_FILES as Q, FORBIDDEN_CONTROL_KEYS as R, DEFAULT_REVIEW_MEMORY_INTERVAL as S, DEFAULT_REVIEW_TIMEOUT_MS as T, MAX_TIMER_DELAY_MS as U, MAX_SKILL_FILE_BYTES as V, MEMORY_GUIDANCE_SECTION_ORDER as W, SKILL_NAME_RE as X, SKILL_ACTION_REQUIRED_FIELDS as Y, SUPPORT_DIRS as Z, DEFAULT_CURATOR_REVIEW_MAX_TOKENS as _, DEFAULT_SKILL_LIMITS as a, DEFAULT_PROBE_TIMEOUT_MS as b, policyStageLimits as c, CONTENT_SPLIT_HINT as d, DEFAULT_ARCHIVE_AFTER_DAYS as f, DEFAULT_CURATOR_MODEL as g, DEFAULT_CURATOR_INTERVAL_HOURS as h, DEFAULT_REFERENCE_REWRITE_POLICY as i, DEFAULT_SUBSTANTIVE_MIN_AGENT_CHARS as j, DEFAULT_SKILL_VERSION_KEEP as k, AUTHORING_DESCRIPTION_BAR as l, DEFAULT_CURATOR_BOOT_GRACE_SECONDS as m, DEFAULT_ARCHIVE_RETENTION_POLICY as n, DEFAULT_SUPPORT_FILE_CHAR_POLICY as o, DEFAULT_CONSOLIDATION_FAILURES as p, PROTECTED_BUILTIN_SKILLS as q, DEFAULT_CITATION_POLICY as r, POLICY_STAGE_DEFAULTS as s, clampedNumber as t, AUTHORING_SPLIT_LINE_CHARS as u, DEFAULT_MEMORY_CHAR_LIMIT as v, DEFAULT_REVIEW_SKILL_INTERVAL as w, DEFAULT_REVIEW_CONTEXT_MESSAGES as x, DEFAULT_MIN_IDLE_HOURS as y, MAX_DESCRIPTION_LENGTH as z };
@@ -1,4 +1,4 @@
1
1
  import { t as presetsPort } from "../presets-C8vuCuNA.js";
2
- import { a as createUserMessage, c as domainTable, d as EvolutionLlmError, f as llmPort, i as createToolResultMessage, l as escapeText, m as projectionPort, n as DomainError, o as defineDomain, p as modelRoute, r as SessionId, s as defineTool, t as BlockAssembler, u as scopeOf } from "../platform-B06_h8t-.js";
2
+ import { a as createUserMessage, c as domainTable, d as EvolutionLlmError, f as llmPort, i as createToolResultMessage, l as escapeText, m as projectionPort, n as DomainError, o as defineDomain, p as modelRoute, r as SessionId, s as defineTool, t as BlockAssembler, u as scopeOf } from "../platform-CFA12Jam.js";
3
3
  import { n as toolsPort, t as registerEvolutionTool } from "../tools-DzcNFex2.js";
4
4
  export { BlockAssembler, DomainError, EvolutionLlmError, SessionId, createToolResultMessage, createUserMessage, defineDomain, defineTool, domainTable, escapeText, llmPort, modelRoute, presetsPort, projectionPort, registerEvolutionTool, scopeOf, toolsPort };
@@ -5,33 +5,50 @@ import { escapeText } from "@deepseek-ai/dsh-skill";
5
5
  import { BlockAssembler, createToolResultMessage, createUserMessage } from "@deepseek-ai/dsh-llm";
6
6
  import { SessionId } from "@deepseek-ai/dsh-session";
7
7
  //#region lib/types/platform/projections.js
8
- function isCallableThenable(value) {
9
- return typeof value === "function" && typeof value.then === "function";
10
- }
8
+ const isThenable = (value) => (typeof value === "object" || typeof value === "function") && value !== null && typeof value.then === "function";
9
+ const isHandle = (value) => value !== null && typeof value === "object" && typeof value.stateOf === "function" && typeof value.dispose === "function";
11
10
  /** Resolve the projection port; undefined means the host has no projection registry. */
12
11
  function projectionPort(ctx) {
13
12
  const registry = ctx.get("sessionProjections");
14
13
  if (registry === void 0) return void 0;
15
- return { async register(definition) {
16
- const raw = registry.register(definition);
17
- if (isCallableThenable(raw)) {
18
- const resolved = await raw;
19
- if (resolved !== null && typeof resolved === "object" && typeof resolved.stateOf === "function") {
20
- const handle = resolved;
14
+ let shape = "unrecognised";
15
+ let reason = "sessionProjections.register has not answered yet";
16
+ return {
17
+ get shape() {
18
+ return shape;
19
+ },
20
+ get reason() {
21
+ return shape === "unrecognised" ? reason : void 0;
22
+ },
23
+ async register(definition) {
24
+ const raw = registry.register(definition);
25
+ const resolved = isThenable(raw) ? await raw : raw;
26
+ if (isHandle(resolved)) {
27
+ shape = "handle";
28
+ reason = void 0;
21
29
  return {
22
- stateOf: (session) => handle.stateOf(session),
23
- dispose: () => handle.dispose()
30
+ stateOf: (session) => resolved.stateOf(session),
31
+ dispose: () => resolved.dispose()
24
32
  };
25
33
  }
26
- }
27
- const dispose = raw;
28
- return {
29
- stateOf: (session) => registry.stateOf?.(session, definition.key),
30
- dispose: async () => {
31
- dispose();
34
+ if (resolved === raw && typeof raw === "function" && typeof registry.stateOf === "function") {
35
+ shape = "legacy";
36
+ reason = void 0;
37
+ return {
38
+ stateOf: (session) => registry.stateOf?.(session, definition.key),
39
+ dispose: async () => {
40
+ raw();
41
+ }
42
+ };
32
43
  }
33
- };
34
- } };
44
+ shape = "unrecognised";
45
+ reason = "sessionProjections.register returned " + (resolved === null ? "null" : typeof resolved) + " with neither a projection handle nor a legacy disposer";
46
+ return {
47
+ stateOf: () => void 0,
48
+ dispose: async () => {}
49
+ };
50
+ }
51
+ };
35
52
  }
36
53
  //#endregion
37
54
  //#region lib/types/platform/llm.js
package/lib/policy.js ADDED
@@ -0,0 +1,99 @@
1
+ import { E as DEFAULT_SKILL_CONTENT_CHARS, F as DEFAULT_USER_CHAR_LIMIT, L as EVOLUTION_WRITE_TOOLS, R as FORBIDDEN_CONTROL_KEYS, g as DEFAULT_CURATOR_MODEL, i as DEFAULT_REFERENCE_REWRITE_POLICY, n as DEFAULT_ARCHIVE_RETENTION_POLICY, o as DEFAULT_SUPPORT_FILE_CHAR_POLICY, q as PROTECTED_BUILTIN_SKILLS, r as DEFAULT_CITATION_POLICY, s as POLICY_STAGE_DEFAULTS, t as clampedNumber, v as DEFAULT_MEMORY_CHAR_LIMIT } from "./numeric-DLeLvvGb.js";
2
+ import { t as asRecord } from "./guards-3f02mnf2.js";
3
+ import { n as toolsPort } from "./tools-DzcNFex2.js";
4
+ import { Service } from "@deepseek-ai/cordis";
5
+ import z from "@deepseek-ai/schemastery";
6
+ //#region lib/types/policy.js
7
+ /**
8
+ * Immutable evolution policy service.
9
+ * The policy is the control plane. Model plans may not change it.
10
+ * @module @lmzhen/dsh-evolution-core/policy
11
+ */
12
+ const Config = z.object({
13
+ reviewMemoryInterval: z.number().min(1).default(10),
14
+ reviewSkillInterval: z.number().min(1).default(10),
15
+ substantiveMinToolCalls: z.number().min(1).default(3),
16
+ substantiveMinUserChars: z.number().min(1).default(200),
17
+ substantiveMinAgentChars: z.number().min(1).default(500),
18
+ reviewMode: z.union([z.const("inject"), z.const("aux")]).default("aux"),
19
+ curatorModel: z.string().default(DEFAULT_CURATOR_MODEL),
20
+ memoryChars: z.number().min(1).default(DEFAULT_MEMORY_CHAR_LIMIT),
21
+ userChars: z.number().min(1).default(DEFAULT_USER_CHAR_LIMIT),
22
+ skillContentChars: z.number().min(1).default(DEFAULT_SKILL_CONTENT_CHARS),
23
+ curatorIntervalHours: z.number().min(1).default(168),
24
+ staleAfterDays: z.number().min(1).default(30),
25
+ archiveAfterDays: z.number().min(1).default(90),
26
+ protectedSkillNames: z.array(z.string()).default([]),
27
+ citationPolicy: z.union([z.const("verify"), z.const("refuse")]).default(POLICY_STAGE_DEFAULTS.citationPolicy),
28
+ referenceRewrite: z.union([
29
+ z.const("off"),
30
+ z.const("plan"),
31
+ z.const("apply")
32
+ ]).default(POLICY_STAGE_DEFAULTS.referenceRewrite),
33
+ archiveRetention: z.union([z.const("report"), z.const("prune")]).default(POLICY_STAGE_DEFAULTS.archiveRetention),
34
+ supportFileCharPolicy: z.union([z.const("report"), z.const("enforce")]).default(POLICY_STAGE_DEFAULTS.supportFileCharPolicy)
35
+ });
36
+ var EvolutionPolicy = class extends Service {
37
+ static Config = Config;
38
+ snapshot;
39
+ constructor(ctx, config = {}) {
40
+ super(ctx, "evolutionPolicy");
41
+ ctx.inject(["tools"], (toolCtx) => {
42
+ const tools = toolsPort(toolCtx);
43
+ if (tools === void 0) return;
44
+ toolCtx.effect(() => tools.guard((exec) => this.guardReason(exec.name, exec.arguments)), "evolution-policy.tools-guard");
45
+ });
46
+ const clamped = [];
47
+ const field = (name, value, fallback) => {
48
+ const result = clampedNumber(value, fallback, { min: 1 });
49
+ if (value !== void 0 && result !== value) clamped.push(name);
50
+ return result;
51
+ };
52
+ this.snapshot = Object.freeze({
53
+ version: 1,
54
+ reviewMemoryInterval: field("reviewMemoryInterval", config.reviewMemoryInterval, 10),
55
+ reviewSkillInterval: field("reviewSkillInterval", config.reviewSkillInterval, 10),
56
+ substantiveMinToolCalls: field("substantiveMinToolCalls", config.substantiveMinToolCalls, 3),
57
+ substantiveMinUserChars: field("substantiveMinUserChars", config.substantiveMinUserChars, 200),
58
+ substantiveMinAgentChars: field("substantiveMinAgentChars", config.substantiveMinAgentChars, 500),
59
+ reviewMode: (() => {
60
+ return config.reviewMode === "aux" ? "aux" : "inject";
61
+ })(),
62
+ curatorModel: config.curatorModel ?? "deepseek-v4-pro",
63
+ memoryChars: field("memoryChars", config.memoryChars, DEFAULT_MEMORY_CHAR_LIMIT),
64
+ userChars: field("userChars", config.userChars, DEFAULT_USER_CHAR_LIMIT),
65
+ skillContentChars: field("skillContentChars", config.skillContentChars, DEFAULT_SKILL_CONTENT_CHARS),
66
+ curatorIntervalHours: field("curatorIntervalHours", config.curatorIntervalHours, 168),
67
+ staleAfterDays: field("staleAfterDays", config.staleAfterDays, 30),
68
+ citationPolicy: config.citationPolicy === "refuse" ? "refuse" : DEFAULT_CITATION_POLICY,
69
+ referenceRewrite: config.referenceRewrite === "off" || config.referenceRewrite === "apply" ? config.referenceRewrite : DEFAULT_REFERENCE_REWRITE_POLICY,
70
+ archiveRetention: config.archiveRetention === "prune" ? "prune" : DEFAULT_ARCHIVE_RETENTION_POLICY,
71
+ supportFileCharPolicy: config.supportFileCharPolicy === "enforce" ? "enforce" : DEFAULT_SUPPORT_FILE_CHAR_POLICY,
72
+ archiveAfterDays: field("archiveAfterDays", config.archiveAfterDays, 90),
73
+ protectedSkillNames: Object.freeze([...new Set([...PROTECTED_BUILTIN_SKILLS, ...config.protectedSkillNames ?? []])])
74
+ });
75
+ if (clamped.length > 0) ctx.logger.warn(`evolution-policy: ${clamped.join(", ")} provided an invalid value; falling back to the default`);
76
+ }
77
+ get() {
78
+ return this.snapshot;
79
+ }
80
+ guardReason(toolName, args) {
81
+ if (EVOLUTION_WRITE_TOOLS.includes(toolName)) {
82
+ const scan = (candidate) => {
83
+ for (const forbidden of FORBIDDEN_CONTROL_KEYS) if (forbidden in candidate) return `evolution-policy: tool call may not mutate ${forbidden}`;
84
+ };
85
+ const record = asRecord(args);
86
+ if (record === void 0) return void 0;
87
+ const top = scan(record);
88
+ if (top) return top;
89
+ if (Array.isArray(record.operations)) for (const op of record.operations) {
90
+ const opRecord = asRecord(op);
91
+ if (opRecord === void 0) continue;
92
+ const inner = scan(opRecord);
93
+ if (inner) return inner;
94
+ }
95
+ }
96
+ }
97
+ };
98
+ //#endregion
99
+ export { Config, EvolutionPolicy, EvolutionPolicy as default };
@@ -1,6 +1,6 @@
1
1
  import { a as evolutionSignalsProjection, i as evolutionReadsProjection, n as evolutionEvidenceProjection, r as evolutionProjectionHistoryProjection, t as evolutionActivityProjection } from "../session-projection-EB7mUOlJ.js";
2
2
  import { t as presetsPort } from "../presets-C8vuCuNA.js";
3
- import { d as EvolutionLlmError, f as llmPort, m as projectionPort, p as modelRoute } from "../platform-B06_h8t-.js";
3
+ import { d as EvolutionLlmError, f as llmPort, m as projectionPort, p as modelRoute } from "../platform-CFA12Jam.js";
4
4
  import { n as toolsPort } from "../tools-DzcNFex2.js";
5
5
  import { Service } from "@deepseek-ai/cordis";
6
6
  //#region lib/types/runtime/llm.js
@@ -148,6 +148,13 @@ var EvolutionProjections = class extends Service {
148
148
  partial.reads = await port.register(evolutionReadsProjection);
149
149
  partial.history = await port.register(evolutionProjectionHistoryProjection);
150
150
  partial.signals = await port.register(evolutionSignalsProjection);
151
+ if (port.shape === "unrecognised") {
152
+ for (const handle of Object.values(partial).reverse()) try {
153
+ await handle.dispose();
154
+ } catch {}
155
+ this.markDegraded("projection port shape not recognised: " + (port.reason ?? "no reason reported"));
156
+ return;
157
+ }
151
158
  this.handles = partial;
152
159
  } catch (error) {
153
160
  for (const handle of Object.values(partial).reverse()) try {