@lmzhen/dsh-evolution-core 0.53.0 → 0.55.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 (53) hide show
  1. package/lib/{extract-plan-D4zO7dmD.js → extract-plan-ihQznLVT.js} +2 -1
  2. package/lib/extract.js +7 -7
  3. package/lib/index.js +795 -546
  4. package/lib/{limits-TD4Pv92Q.js → limits-DBg3UMkw.js} +11 -6
  5. package/lib/{skill-history-CZp8vhyL.js → mutation-storage-adapter-BM7mIJKp.js} +4 -647
  6. package/lib/mutations-1wLISSrY.js +592 -0
  7. package/lib/policy.js +9 -3
  8. package/lib/{quality-BLc6UQQb.js → quality-DNUVRbUm.js} +1 -1
  9. package/lib/{skill-health-BIpiPvw6.js → review-context-CXKwGGd8.js} +124 -183
  10. package/lib/runtime/plugin.js +92 -1
  11. package/lib/{session-projection-ByNxQi9O.js → session-projection-CbIKvDfJ.js} +3 -2
  12. package/lib/skill-history-B-DyIedq.js +646 -0
  13. package/lib/skills.js +12 -8
  14. package/lib/text-metrics-CyJhxWBs.js +132 -0
  15. package/lib/types/constants.d.ts +10 -5
  16. package/lib/types/constants.js +10 -5
  17. package/lib/types/drift-signals.d.ts +1 -4
  18. package/lib/types/drift-signals.js +14 -23
  19. package/lib/types/extract-request.js +3 -2
  20. package/lib/types/frontmatter.js +12 -8
  21. package/lib/types/index.d.ts +2 -1
  22. package/lib/types/index.js +2 -1
  23. package/lib/types/memory-store.d.ts +32 -6
  24. package/lib/types/memory-store.js +86 -30
  25. package/lib/types/mutation-unit.js +2 -1
  26. package/lib/types/params.js +6 -3
  27. package/lib/types/policy.d.ts +5 -0
  28. package/lib/types/policy.js +8 -2
  29. package/lib/types/prompts.d.ts +1 -1
  30. package/lib/types/prompts.js +1 -1
  31. package/lib/types/runtime/coherence.d.ts +27 -0
  32. package/lib/types/runtime/coherence.js +115 -0
  33. package/lib/types/runtime/plugin.js +2 -0
  34. package/lib/types/signals.js +3 -2
  35. package/lib/types/skill-health.d.ts +8 -5
  36. package/lib/types/skill-health.js +27 -28
  37. package/lib/types/skill-history.d.ts +2 -2
  38. package/lib/types/skill-history.js +7 -7
  39. package/lib/types/skill-lint.d.ts +1 -1
  40. package/lib/types/skill-lint.js +4 -4
  41. package/lib/types/skill-stats.d.ts +3 -1
  42. package/lib/types/skill-stats.js +2 -0
  43. package/lib/types/skill-store.js +2 -1
  44. package/lib/types/text-budgets.d.ts +150 -0
  45. package/lib/types/text-budgets.js +65 -0
  46. package/lib/types/text-metrics.d.ts +88 -0
  47. package/lib/types/text-metrics.js +131 -0
  48. package/lib/{usage-B1qveKi9.js → usage-e34VZPmK.js} +2 -515
  49. package/lib/write.js +3 -2
  50. package/package.json +1 -1
  51. package/lib/mutations-DQXddSJd.js +0 -75
  52. package/lib/types/cost.d.ts +0 -63
  53. package/lib/types/cost.js +0 -67
@@ -0,0 +1,115 @@
1
+ /**
2
+ * Family version coherence probe.
3
+ *
4
+ * A profile can contain one bundle whose implementation packages come from
5
+ * different family releases: the bundle row updates while a directly pinned
6
+ * sibling stays behind, or old hand-copied packages shadow the pnpm tree. The
7
+ * loader then runs an old client against a new host, which looks like a UI
8
+ * regression rather than a mixed install. This probe names that state at
9
+ * startup; it never repairs a live profile (a package-manager write while the
10
+ * host runs is unsafe and needs a restart).
11
+ *
12
+ * @module @lmzhen/dsh-evolution-core/runtime/coherence
13
+ */
14
+ import { existsSync, readFileSync } from 'node:fs';
15
+ import { join } from 'node:path';
16
+ import { profileContextPort } from "../platform/profileContext.js";
17
+ function packageTail(name) {
18
+ return name.slice(name.lastIndexOf('/') + 1);
19
+ }
20
+ /** Family implementation tails; external @deepseek-ai packages stay out. */
21
+ function isFamilyPackage(name) {
22
+ const tail = packageTail(name);
23
+ return tail.startsWith('dsh-evolution-')
24
+ || tail === 'dsh-memory'
25
+ || tail === 'dsh-memory-files'
26
+ || tail === 'dsh-skill-usage'
27
+ || tail === 'dsh-tool-memory'
28
+ || tail === 'dsh-tool-skill-manage';
29
+ }
30
+ /**
31
+ * Compare every implementation package with the installed `all` bundle.
32
+ * Missing packages count as a mismatch because the old loader would fall back
33
+ * to an unrelated copy or fail at load.
34
+ * @param profileDir - profile directory containing `package.json` and `node_modules`.
35
+ * @returns The coherence result, or undefined when the profile has no readable `all` bundle.
36
+ */
37
+ export function checkFamilyCoherence(profileDir) {
38
+ const profileManifest = join(profileDir, 'package.json');
39
+ if (!existsSync(profileManifest))
40
+ return undefined;
41
+ // Resolve ONLY inside this profile. A createRequire fallback can walk the
42
+ // test/launcher NODE_PATH and report the build tree's packages as installed,
43
+ // which would hide exactly the mixed profile this probe exists to catch.
44
+ const resolveManifest = (name) => {
45
+ const path = join(profileDir, 'node_modules', name, 'package.json');
46
+ return existsSync(path) ? path : undefined;
47
+ };
48
+ const allPath = resolveManifest('@lmzhen/dsh-evolution-all') ?? resolveManifest('@lmzhen/dsh-evolution-all');
49
+ if (allPath === undefined)
50
+ return undefined;
51
+ let all;
52
+ try {
53
+ all = JSON.parse(readFileSync(allPath, 'utf8'));
54
+ }
55
+ catch {
56
+ return undefined;
57
+ }
58
+ if (typeof all.version !== 'string')
59
+ return undefined;
60
+ const components = [];
61
+ const visited = new Set();
62
+ const queue = Object.keys(all.dependencies ?? {}).filter(isFamilyPackage);
63
+ while (queue.length > 0) {
64
+ const name = queue.shift();
65
+ if (name === undefined || visited.has(name))
66
+ continue;
67
+ visited.add(name);
68
+ const manifestPath = resolveManifest(name);
69
+ if (manifestPath === undefined) {
70
+ components.push({ name });
71
+ continue;
72
+ }
73
+ try {
74
+ const manifest = JSON.parse(readFileSync(manifestPath, 'utf8'));
75
+ components.push({ name, ...(typeof manifest.version === 'string' ? { version: manifest.version } : {}) });
76
+ // The family is a dependency graph, not only the bundle's direct list:
77
+ // client-kit arrives through evolution-ui, merge-engine through merge.
78
+ for (const child of [
79
+ ...Object.keys(manifest.dependencies ?? {}),
80
+ ...Object.keys(manifest.optionalDependencies ?? {}),
81
+ ]) {
82
+ if (isFamilyPackage(child) && !visited.has(child))
83
+ queue.push(child);
84
+ }
85
+ }
86
+ catch {
87
+ components.push({ name });
88
+ }
89
+ }
90
+ return {
91
+ allVersion: all.version,
92
+ components,
93
+ mismatched: components.filter(component => component.version !== all.version),
94
+ };
95
+ }
96
+ /**
97
+ * Warn once when the running profile is a mixed family install.
98
+ * @param ctx - the running host context; a bare library mount has no profile and is skipped.
99
+ * @returns The detected mismatch, or undefined when no profile/all bundle is present.
100
+ */
101
+ export function warnIfFamilyMixed(ctx) {
102
+ const profile = profileContextPort(ctx);
103
+ if (profile === undefined)
104
+ return undefined;
105
+ const coherence = checkFamilyCoherence(profile.dir);
106
+ if (coherence === undefined || coherence.mismatched.length === 0)
107
+ return undefined;
108
+ const details = coherence.mismatched
109
+ .map(component => `${component.name}@${component.version ?? 'missing'}`)
110
+ .join(', ');
111
+ console.warn(`[dsh-evolution] mixed family install: all@${coherence.allVersion} but ${details}; `
112
+ + 'the loaded client may be an older release. Run the profile repair in INSTALL.md before restarting.');
113
+ return coherence;
114
+ }
115
+ //# sourceMappingURL=coherence.js.map
@@ -1,3 +1,4 @@
1
+ import { warnIfFamilyMixed } from "./coherence.js";
1
2
  import { EvolutionLlm } from "./llm.js";
2
3
  import { EvolutionPlatform } from "./platform.js";
3
4
  import { EvolutionProjections } from "./projections.js";
@@ -9,5 +10,6 @@ export async function apply(ctx) {
9
10
  await ctx.plugin(EvolutionPlatform);
10
11
  await ctx.plugin(EvolutionProjections);
11
12
  await ctx.plugin(EvolutionLlm);
13
+ warnIfFamilyMixed(ctx);
12
14
  }
13
15
  //# sourceMappingURL=plugin.js.map
@@ -6,6 +6,7 @@
6
6
  * accumulated until a configured interval fires.
7
7
  */
8
8
  import { dispatchStepOf, isSkillToolName } from "./tool-dispatch.js";
9
+ import { graphemeCount } from "./text-metrics.js";
9
10
  const CORRECTION_PATTERNS = [
10
11
  /(?:don'?t|do not|stop|never)\s+(?:do|use|format|explain|write|say)/i,
11
12
  /(?:too|very|way\s+too)\s+(?:verbose|long|detailed|short|brief)/i,
@@ -69,7 +70,7 @@ export function foldTurnEvent(state, event) {
69
70
  const text = content.map(textOfBlock).join(' ');
70
71
  return {
71
72
  ...state,
72
- userChars: state.userChars + text.length,
73
+ userChars: state.userChars + graphemeCount(text),
73
74
  memorySignal: state.memorySignal || CORRECTION_PATTERNS.some(pattern => pattern.test(text)),
74
75
  skillSignal: state.skillSignal || FIX_PATTERNS.some(pattern => pattern.test(text)),
75
76
  };
@@ -81,7 +82,7 @@ export function foldTurnEvent(state, event) {
81
82
  if (!message || !Array.isArray(message.content))
82
83
  return state;
83
84
  const text = message.content.map(textOfBlock).join(' ');
84
- return { ...state, assistantChars: state.assistantChars + text.length };
85
+ return { ...state, assistantChars: state.assistantChars + graphemeCount(text) };
85
86
  }
86
87
  // Tool evidence (v37 P7a): the dispatch vocabulary lives in `tool-dispatch.ts` — the ONE reader
87
88
  // of the platform's dispatch event types — and `dispatchStepOf` is its pure half, so this fold
@@ -11,11 +11,12 @@
11
11
  */
12
12
  import { type LintFinding } from './skill-lint.ts';
13
13
  export interface SkillHealthThresholds {
14
- /** Soft body limit: a body of `softBodyChars` or MORE -> 'warn'; >= 2x ->
15
- * 'needs-restructure'. V6-34 (0.3.37): the doc comment used to claim
16
- * "at/below stay healthy" while the engine warns at `>=` — fixed to the
17
- * implementation edge (the reason copy said "above"). */
18
- softBodyChars: number;
14
+ /** Fixed soft body budget in tokens: a body at/above it -> 'warn'; 2x ->
15
+ * 'needs-restructure'. This is the judged quantity. */
16
+ softBodyTokens?: number;
17
+ /** Deprecated legacy character line. Used only when `softBodyTokens` is absent,
18
+ * converted on the documented UPSTREAM basis; never a per-body token line. */
19
+ softBodyChars?: number;
19
20
  /** Stamp-density ceiling per KB of body text: rc.NN / commit shas / ISO
20
21
  * dates per KB at/above this -> 'warn' (log-like content living in the
21
22
  * body — the "invalid info" indicator). */
@@ -27,6 +28,8 @@ export interface SkillHealthThresholds {
27
28
  hardCapMinHits: number;
28
29
  }
29
30
  export declare const DEFAULT_HEALTH_THRESHOLDS: SkillHealthThresholds;
31
+ /** Resolve the judged soft-body token budget, accepting the legacy character line. */
32
+ export declare function softBodyTokenBudget(thresholds: SkillHealthThresholds): number;
30
33
  /**
31
34
  * Stamp regex shared by health assessment and the maintenance probe (single
32
35
  * source, 011). Two refinements over the naive form (F-320): the hex branch
@@ -9,22 +9,26 @@
9
9
  * stay in the review/curator judgment layer. Never become a 7th factor of
10
10
  * `computeQualityScores` (different dimension, different consumers).
11
11
  */
12
- import { AUTHORING_SPLIT_LINE_CHARS, UPSTREAM_LIMIT_CHARS_PER_TOKEN } from "./constants.js";
13
- import { bodyCost, tokenLineFor } from "./cost.js";
12
+ import { DEFAULT_SOFT_BODY_TOKENS, UPSTREAM_LIMIT_CHARS_PER_TOKEN } from "./constants.js";
13
+ import { measureText, measureUnit } from "./text-metrics.js";
14
14
  import { lintSkill } from "./skill-lint.js";
15
15
  export const DEFAULT_HEALTH_THRESHOLDS = {
16
- // V6: the number is the UPSTREAM line itself (20k characters — "if you're
17
- // pushing past 20k, split into references/*.md"). The previous 40k was twice
18
- // that line, which is why a body could sit at 2x the authoring discipline and
19
- // still read as merely "warn". The JUDGMENT happens in tokens (see
20
- // assessStructureHealth): the line is converted per body composition, so the
21
- // textual trigger stays exactly "20k characters" while every reported number is
22
- // a token count.
23
- softBodyChars: AUTHORING_SPLIT_LINE_CHARS,
16
+ // V6: the number was the UPSTREAM 20k-character authoring line. The judgment
17
+ // is now a fixed token budget derived from that line; the character field stays
18
+ // as a deprecated migration input only.
19
+ softBodyTokens: DEFAULT_SOFT_BODY_TOKENS,
24
20
  stampDensityPerKb: 2,
25
21
  churnMinPatches: 20,
26
22
  hardCapMinHits: 3,
27
23
  };
24
+ /** Resolve the judged soft-body token budget, accepting the legacy character line. */
25
+ export function softBodyTokenBudget(thresholds) {
26
+ if (thresholds.softBodyTokens !== undefined)
27
+ return thresholds.softBodyTokens;
28
+ if (thresholds.softBodyChars !== undefined)
29
+ return Math.round(thresholds.softBodyChars / UPSTREAM_LIMIT_CHARS_PER_TOKEN);
30
+ return DEFAULT_SOFT_BODY_TOKENS;
31
+ }
28
32
  /**
29
33
  * Stamp regex shared by health assessment and the maintenance probe (single
30
34
  * source, 011). Two refinements over the naive form (F-320): the hex branch
@@ -75,30 +79,25 @@ export function assessStructureHealth(snapshot, thresholds = DEFAULT_HEALTH_THRE
75
79
  churnReads: null,
76
80
  hardCapHits: snapshot.hardCapHits ?? null,
77
81
  };
78
- // V6: the JUDGMENT runs on the token scale. The configured number stays the
79
- // borrowed UPSTREAM character line, converted per body composition, so the
80
- // textual trigger is unchanged while every reported number is a token count.
82
+ // V6: the JUDGMENT runs on a FIXED token budget. A legacy character line is
83
+ // converted once on the documented UPSTREAM basis; it is not re-converted per
84
+ // body composition (that would preserve the character edge and defeat the point).
81
85
  // Without body text the token scale is unavailable — the character line then
82
86
  // decides, because an absent measurement must never read as a pass.
83
87
  const text = snapshot.bodyText;
84
88
  const hasText = typeof text === 'string' && text.length > 0;
85
- const cost = hasText ? bodyCost(text) : null;
86
- const lineTokens = cost === null ? null : tokenLineFor(thresholds.softBodyChars, cost);
87
- dims.bodyTokens = cost === null
89
+ const tokenBudget = softBodyTokenBudget(thresholds);
90
+ dims.bodyTokens = hasText
91
+ ? measureText(text).tokens.value
88
92
  // No text: no composition to weigh, so the LIMIT basis is the only honest
89
- // conversion — the estimate range would need a CJK/ASCII split we do not have.
90
- ? Math.round(snapshot.bodyChars / UPSTREAM_LIMIT_CHARS_PER_TOKEN)
91
- : cost.tokens;
92
- const overLine = cost === null || lineTokens === null
93
- ? snapshot.bodyChars >= thresholds.softBodyChars
94
- : cost.tokens >= lineTokens;
95
- const overTwice = cost === null || lineTokens === null
96
- ? snapshot.bodyChars >= thresholds.softBodyChars * 2
97
- : cost.tokens >= lineTokens * 2;
93
+ // conversion — the estimate range would need a script split we do not have.
94
+ : Math.round(snapshot.bodyChars / UPSTREAM_LIMIT_CHARS_PER_TOKEN);
95
+ const overLine = dims.bodyTokens >= tokenBudget;
96
+ const overTwice = dims.bodyTokens >= tokenBudget * 2;
98
97
  // G2 ③: the over-line judgement is now expressed as `findings` (see the RULES table in skill-lint);
99
98
  // the free-text copy that used to live here is gone, and `overLine`/`overTwice` feed the facts above.
100
- if (snapshot.bodyText && snapshot.bodyChars >= MIN_STAMP_BODY_CHARS) {
101
- const kb = Math.max(1, snapshot.bodyChars / 1024);
99
+ if (snapshot.bodyText && measureUnit(snapshot.bodyText, 'codePoints') >= MIN_STAMP_BODY_CHARS) {
100
+ const kb = Math.max(1, measureUnit(snapshot.bodyText, 'codePoints') / 1024);
102
101
  const stamps = (snapshot.bodyText.match(HEALTH_STAMP_RE) ?? []).length;
103
102
  dims.stampDensityPerKb = stamps / kb;
104
103
  dims.stampHits = stamps;
@@ -112,7 +111,7 @@ export function assessStructureHealth(snapshot, thresholds = DEFAULT_HEALTH_THRE
112
111
  const findings = lintSkill({
113
112
  skillName: snapshot.skillName,
114
113
  dims,
115
- softLineChars: thresholds.softBodyChars,
114
+ softLineTokens: tokenBudget,
116
115
  overSoftLine: overLine,
117
116
  overTwiceSoftLine: overTwice,
118
117
  stampLimitPerKb: thresholds.stampDensityPerKb,
@@ -41,9 +41,9 @@ export interface ChangeSummary {
41
41
  text: string;
42
42
  source: SummarySource;
43
43
  }
44
- /** Default hard cap for a change summary, counted in Unicode code points. */
44
+ /** Default hard cap for a change summary, counted in grapheme clusters. */
45
45
  export declare const DEFAULT_SKILL_WRITE_SUMMARY_CHARS = 50;
46
- /** Count a summary the same way the write gate does (code points, not UTF-16 units). */
46
+ /** Count a summary the same way the write gate does (graphemes, not UTF-16 units). */
47
47
  export declare function summaryChars(text: string): number;
48
48
  /** Normalize a model-supplied summary: single line, trimmed, non-empty, within the hard cap. */
49
49
  export declare function normalizeChangeSummary(value: unknown, cap?: number): {
@@ -30,6 +30,7 @@ import { join } from 'node:path';
30
30
  import { transactIo } from "./io.js";
31
31
  import { isPresent, isUnknown, probeText } from "./probe.js";
32
32
  import { contentHash } from "./mutations.js";
33
+ import { graphemeCount, truncateGraphemes } from "./text-metrics.js";
33
34
  /** Root-level history directory. Dot-prefixed so skill discovery skips it. */
34
35
  export const HISTORY_DIR = '.history';
35
36
  /** Versioned index shape, so a future field can migrate without guessing. */
@@ -37,11 +38,11 @@ export const HISTORY_INDEX_VERSION = 1;
37
38
  /** The action label for a predecessor the index had never seen (content found on disk before this
38
39
  * feature existed, or a hand-edited tree): it says "this is what was there", not what wrote it. */
39
40
  export const BASELINE_ACTION = 'baseline';
40
- /** Default hard cap for a change summary, counted in Unicode code points. */
41
+ /** Default hard cap for a change summary, counted in grapheme clusters. */
41
42
  export const DEFAULT_SKILL_WRITE_SUMMARY_CHARS = 50;
42
- /** Count a summary the same way the write gate does (code points, not UTF-16 units). */
43
+ /** Count a summary the same way the write gate does (graphemes, not UTF-16 units). */
43
44
  export function summaryChars(text) {
44
- return [...text].length;
45
+ return graphemeCount(text);
45
46
  }
46
47
  /** Normalize a model-supplied summary: single line, trimmed, non-empty, within the hard cap. */
47
48
  export function normalizeChangeSummary(value, cap = DEFAULT_SKILL_WRITE_SUMMARY_CHARS) {
@@ -58,8 +59,7 @@ export function normalizeChangeSummary(value, cap = DEFAULT_SKILL_WRITE_SUMMARY_
58
59
  /** Clip a host-generated summary to the same hard cap; host facts are not rejected. */
59
60
  export function clipChangeSummary(text, cap = DEFAULT_SKILL_WRITE_SUMMARY_CHARS) {
60
61
  const line = text.replace(/\s+/g, ' ').trim();
61
- const chars = [...line];
62
- return chars.length <= cap ? line : chars.slice(0, Math.max(1, cap - 1)).join('') + '…';
62
+ return truncateGraphemes(line, cap);
63
63
  }
64
64
  /** The root-level history directory. */
65
65
  export function historyRoot(root) {
@@ -685,9 +685,9 @@ export function textDiffFacts(before, after, path, maxLines = TEXT_DIFF_MAX_LINE
685
685
  const window = (lines) => {
686
686
  const byLines = lines.slice(0, maxLines);
687
687
  const joined = byLines.join('\n');
688
- if (joined.length <= TEXT_DIFF_MAX_CHARS)
688
+ if (graphemeCount(joined) <= TEXT_DIFF_MAX_CHARS)
689
689
  return { text: joined, cut: lines.length > maxLines };
690
- return { text: joined.slice(0, TEXT_DIFF_MAX_CHARS), cut: true };
690
+ return { text: truncateGraphemes(joined, TEXT_DIFF_MAX_CHARS, ''), cut: true };
691
691
  };
692
692
  const oldWindow = window(oldRegion);
693
693
  const newWindow = window(newRegion);
@@ -28,7 +28,7 @@ export interface SkillDims {
28
28
  export interface LintFacts {
29
29
  skillName: string;
30
30
  dims: SkillDims;
31
- softLineChars: number;
31
+ softLineTokens: number;
32
32
  overSoftLine: boolean;
33
33
  overTwiceSoftLine: boolean;
34
34
  stampLimitPerKb: number;
@@ -25,14 +25,14 @@ export const RULES = [
25
25
  id: 'body-oversize-2x',
26
26
  severity: 'error',
27
27
  run: facts => facts.overTwiceSoftLine
28
- ? { severity: 'error', rule: 'body-oversize-2x', message: msg([facts.skillName, ': body is at or past twice the soft line (', facts.softLineChars, ' chars); keeping the current skill is valid']), count: 1 }
28
+ ? { severity: 'error', rule: 'body-oversize-2x', message: msg([facts.skillName, ': body is at or past twice the soft line (', facts.softLineTokens, ' tokens); keeping the current skill is valid']), count: 1 }
29
29
  : null,
30
30
  },
31
31
  {
32
32
  id: 'body-oversize',
33
33
  severity: 'warn',
34
34
  run: facts => !facts.overTwiceSoftLine && facts.overSoftLine
35
- ? { severity: 'warn', rule: 'body-oversize', message: msg([facts.skillName, ': body is at or above the soft line (', facts.softLineChars, ' chars); keep is valid — size alone does not require a split']), count: 1 }
35
+ ? { severity: 'warn', rule: 'body-oversize', message: msg([facts.skillName, ': body is at or above the soft line (', facts.softLineTokens, ' tokens); keep is valid — size alone does not require a split']), count: 1 }
36
36
  : null,
37
37
  },
38
38
  {
@@ -49,8 +49,8 @@ export const RULES = [
49
49
  {
50
50
  id: 'body-without-support',
51
51
  severity: 'warn',
52
- run: facts => facts.dims.supportGroups === 0 && facts.dims.bodyChars !== null && facts.dims.bodyChars >= facts.softLineChars / 2
53
- ? { severity: 'warn', rule: 'body-without-support', message: msg([facts.skillName, ': large body (', facts.dims.bodyChars, ' chars) with NO support files']), count: 1 }
52
+ run: facts => facts.dims.supportGroups === 0 && facts.dims.bodyTokens !== null && facts.dims.bodyTokens >= facts.softLineTokens / 2
53
+ ? { severity: 'warn', rule: 'body-without-support', message: msg([facts.skillName, ': large body (', facts.dims.bodyTokens, ' tokens) with NO support files']), count: 1 }
54
54
  : null,
55
55
  },
56
56
  {
@@ -83,6 +83,8 @@ export interface SkillStatsTotals {
83
83
  readonly skills: number;
84
84
  readonly needsAttention: number;
85
85
  readonly bodyChars: number | null;
86
+ /** Sum of the health rows' estimated tokens; null when any contributing row was unmeasured. */
87
+ readonly bodyTokens: number | null;
86
88
  readonly supportFiles: number | null;
87
89
  readonly successes: SkillStatsCounts | null;
88
90
  }
@@ -114,7 +116,7 @@ export interface SkillStatsSnapshot {
114
116
  readonly generatedAt: string;
115
117
  }
116
118
  /** Sortable columns the table exposes. */
117
- export type SkillStatsSortKey = 'name' | 'verdict' | 'bodyChars' | 'supportFiles' | 'versions' | 'useCount' | 'viewCount' | 'viewCount30d' | 'feedback' | 'feedback30d' | 'negativeFeedback30d' | 'feedbackRate30d' | 'lastAt';
119
+ export type SkillStatsSortKey = 'name' | 'verdict' | 'bodyChars' | 'bodyTokens' | 'supportFiles' | 'versions' | 'useCount' | 'viewCount' | 'viewCount30d' | 'feedback' | 'feedback30d' | 'negativeFeedback30d' | 'feedbackRate30d' | 'lastAt';
118
120
  export type SortDirection = 'asc' | 'desc';
119
121
  /** Filter chips in the table header. */
120
122
  export type SkillStatsFilter = 'all' | 'attention' | 'recent';
@@ -66,6 +66,7 @@ export function sortValue(row, key) {
66
66
  case 'name': return row.name;
67
67
  case 'verdict': return verdictRank(row.health?.verdict);
68
68
  case 'bodyChars': return row.health?.bodyChars ?? null;
69
+ case 'bodyTokens': return row.health?.bodyTokens ?? null;
69
70
  case 'supportFiles': return row.health?.supportFiles ?? null;
70
71
  case 'versions': return row.versions;
71
72
  case 'useCount': return row.usage?.useCount ?? null;
@@ -129,6 +130,7 @@ export function computeSkillStatsTotals(rows, counts) {
129
130
  skills: rows.length,
130
131
  needsAttention: rows.filter(needsAttention).length,
131
132
  bodyChars: sumNullable(rows.map(row => row.health?.bodyChars ?? null)),
133
+ bodyTokens: sumNullable(rows.map(row => row.health?.bodyTokens ?? null)),
132
134
  supportFiles: sumNullable(rows.map(row => row.health?.supportFiles ?? null)),
133
135
  successes: counts,
134
136
  };
@@ -45,6 +45,7 @@ import { evolutionRoot } from "./state-store.js";
45
45
  import { DEFAULT_ARCHIVE_RETENTION_POLICY, DEFAULT_CITATION_POLICY, DEFAULT_REFERENCE_REWRITE_POLICY, DEFAULT_SKILL_LIMITS, DEFAULT_SUPPORT_FILE_CHAR_POLICY } from "./limits.js";
46
46
  import { applyReferenceRewrite, describeReferenceRewrite, planReferenceRewrite, planRehoming } from "./reference-rewrite.js";
47
47
  import { exceedsContentLimit, frontmatterBlock, normalizeFrontmatter, parseFrontmatter, shrinksOverLimit, validateFrontmatter } from "./frontmatter.js";
48
+ import { measureUnit } from "./text-metrics.js";
48
49
  import { FUZZY_MAX_PATTERN_CHARS, FUZZY_MAX_WORK, trimPatternBoundaries, fuzzyPatch } from "./fuzzy-match.js";
49
50
  import { makeSerialQueue } from "./serial.js";
50
51
  import { supportRefs } from "./support-refs.js";
@@ -935,7 +936,7 @@ export class SkillLibrary {
935
936
  */
936
937
  badName(name, opts = {}) {
937
938
  const normalized = name.trim();
938
- if (!SKILL_NAME_RE.test(normalized) || normalized.length > this.limits.maxNameLength) {
939
+ if (!SKILL_NAME_RE.test(normalized) || measureUnit(normalized, 'codePoints') > this.limits.maxNameLength) {
939
940
  return `技能名「${normalized}」不合法:请只用小写字母、数字和连字符(不超过 ${this.limits.maxNameLength} 个)。`;
940
941
  }
941
942
  // P2-11 (v15): win32 reserves these stems for ANY directory component —
@@ -0,0 +1,150 @@
1
+ /**
2
+ * Named text budgets: every character-based decision declares its axis, unit and
3
+ * severity here, so business code never invents a measurement or a unit inline.
4
+ *
5
+ * A budget is not a language profile. Storage/display/context/quality are
6
+ * different questions about the same string; the metric module answers all of
7
+ * them, and this table decides which answer each gate uses.
8
+ *
9
+ * @module @lmzhen/dsh-evolution-core
10
+ */
11
+ import { type TextUnit, type TokenEstimator } from './text-metrics.ts';
12
+ /** What a budget protects. */
13
+ export type BudgetAxis = 'storage' | 'display' | 'context' | 'quality';
14
+ /** How a violation is handled; "report" never blocks a write. */
15
+ export type BudgetSeverity = 'hard' | 'soft' | 'report';
16
+ /** One named budget. */
17
+ export interface TextBudget {
18
+ readonly id: string;
19
+ readonly axis: BudgetAxis;
20
+ readonly unit: TextUnit;
21
+ readonly limit: number;
22
+ readonly severity: BudgetSeverity;
23
+ }
24
+ /** One measurement against one budget. */
25
+ export interface TextBudgetResult {
26
+ readonly budget: TextBudget;
27
+ readonly value: number;
28
+ readonly over: boolean;
29
+ readonly remaining: number;
30
+ }
31
+ /** The default soft body token budget. */
32
+ export declare const SOFT_BODY_TOKENS: number;
33
+ /** The derived token budgets for the old character memory limits. */
34
+ export declare const MEMORY_TOKENS: number;
35
+ export declare const USER_TOKENS: number;
36
+ /**
37
+ * The family's named budgets.
38
+ *
39
+ * Context budgets are registered here before their wiring lands so the inventory
40
+ * and doctor have one authority; P2 is what makes them stop being dormant.
41
+ */
42
+ export declare const TEXT_BUDGETS: {
43
+ readonly skillBodyHard: {
44
+ readonly id: "skill.body.hard";
45
+ readonly axis: "storage";
46
+ readonly unit: "codePoints";
47
+ readonly limit: 100000;
48
+ readonly severity: "hard";
49
+ };
50
+ readonly skillFileBytes: {
51
+ readonly id: "skill.file.bytes";
52
+ readonly axis: "storage";
53
+ readonly unit: "utf8Bytes";
54
+ readonly limit: 1048576;
55
+ readonly severity: "hard";
56
+ };
57
+ readonly skillName: {
58
+ readonly id: "skill.name";
59
+ readonly axis: "storage";
60
+ readonly unit: "codePoints";
61
+ readonly limit: 64;
62
+ readonly severity: "hard";
63
+ };
64
+ readonly skillDescription: {
65
+ readonly id: "skill.description.hard";
66
+ readonly axis: "display";
67
+ readonly unit: "graphemes";
68
+ readonly limit: 1024;
69
+ readonly severity: "hard";
70
+ };
71
+ readonly skillDescriptionAuthoring: {
72
+ readonly id: "skill.description.authoring";
73
+ readonly axis: "display";
74
+ readonly unit: "graphemes";
75
+ readonly limit: 60;
76
+ readonly severity: "soft";
77
+ };
78
+ readonly skillSummary: {
79
+ readonly id: "skill.summary";
80
+ readonly axis: "display";
81
+ readonly unit: "graphemes";
82
+ readonly limit: 50;
83
+ readonly severity: "hard";
84
+ };
85
+ readonly feedbackNote: {
86
+ readonly id: "feedback.note";
87
+ readonly axis: "display";
88
+ readonly unit: "graphemes";
89
+ readonly limit: 20;
90
+ readonly severity: "hard";
91
+ };
92
+ readonly lineLength: {
93
+ readonly id: "skill.line";
94
+ readonly axis: "display";
95
+ readonly unit: "graphemes";
96
+ readonly limit: 1500;
97
+ readonly severity: "soft";
98
+ };
99
+ readonly substantiveUser: {
100
+ readonly id: "review.substantive.user";
101
+ readonly axis: "display";
102
+ readonly unit: "graphemes";
103
+ readonly limit: 200;
104
+ readonly severity: "soft";
105
+ };
106
+ readonly substantiveAgent: {
107
+ readonly id: "review.substantive.agent";
108
+ readonly axis: "display";
109
+ readonly unit: "graphemes";
110
+ readonly limit: 500;
111
+ readonly severity: "soft";
112
+ };
113
+ readonly retentionFeedback: {
114
+ readonly id: "history.retention-feedback";
115
+ readonly axis: "display";
116
+ readonly unit: "graphemes";
117
+ readonly limit: 200;
118
+ readonly severity: "report";
119
+ };
120
+ readonly bodySoft: {
121
+ readonly id: "skill.body.soft";
122
+ readonly axis: "context";
123
+ readonly unit: "tokens";
124
+ readonly limit: number;
125
+ readonly severity: "soft";
126
+ };
127
+ readonly memory: {
128
+ readonly id: "memory.budget";
129
+ readonly axis: "context";
130
+ readonly unit: "tokens";
131
+ readonly limit: number;
132
+ readonly severity: "hard";
133
+ };
134
+ readonly user: {
135
+ readonly id: "user.budget";
136
+ readonly axis: "context";
137
+ readonly unit: "tokens";
138
+ readonly limit: number;
139
+ readonly severity: "hard";
140
+ };
141
+ };
142
+ /**
143
+ * Compare one string against one named budget.
144
+ * @param text - the string to measure.
145
+ * @param budget - the budget to apply.
146
+ * @param estimator - optional token source for token budgets.
147
+ * @returns the measured value and the remaining allowance (negative when over).
148
+ */
149
+ export declare function compareTextBudget(text: string, budget: TextBudget, estimator?: TokenEstimator): TextBudgetResult;
150
+ //# sourceMappingURL=text-budgets.d.ts.map
@@ -0,0 +1,65 @@
1
+ /**
2
+ * Named text budgets: every character-based decision declares its axis, unit and
3
+ * severity here, so business code never invents a measurement or a unit inline.
4
+ *
5
+ * A budget is not a language profile. Storage/display/context/quality are
6
+ * different questions about the same string; the metric module answers all of
7
+ * them, and this table decides which answer each gate uses.
8
+ *
9
+ * @module @lmzhen/dsh-evolution-core
10
+ */
11
+ import { AUTHORING_DESCRIPTION_BAR, DEFAULT_SOFT_BODY_TOKENS, DEFAULT_MEMORY_TOKENS, DEFAULT_USER_TOKENS, DEFAULT_SUBSTANTIVE_MIN_AGENT_CHARS, DEFAULT_SUBSTANTIVE_MIN_USER_CHARS, MAX_DESCRIPTION_LENGTH, MAX_SKILL_CONTENT_CHARS, MAX_SKILL_FILE_BYTES, MAX_SKILL_NAME_LENGTH, } from "./constants.js";
12
+ import { DEFAULT_SKILL_WRITE_SUMMARY_CHARS } from "./skill-history.js";
13
+ import { measureText } from "./text-metrics.js";
14
+ import { DRIFT_MAX_LINE_CHARS } from "./drift-signals.js";
15
+ /** The default soft body token budget. */
16
+ export const SOFT_BODY_TOKENS = DEFAULT_SOFT_BODY_TOKENS;
17
+ /** The derived token budgets for the old character memory limits. */
18
+ export const MEMORY_TOKENS = DEFAULT_MEMORY_TOKENS;
19
+ export const USER_TOKENS = DEFAULT_USER_TOKENS;
20
+ /**
21
+ * The family's named budgets.
22
+ *
23
+ * Context budgets are registered here before their wiring lands so the inventory
24
+ * and doctor have one authority; P2 is what makes them stop being dormant.
25
+ */
26
+ export const TEXT_BUDGETS = {
27
+ skillBodyHard: { id: 'skill.body.hard', axis: 'storage', unit: 'codePoints', limit: MAX_SKILL_CONTENT_CHARS, severity: 'hard' },
28
+ skillFileBytes: { id: 'skill.file.bytes', axis: 'storage', unit: 'utf8Bytes', limit: MAX_SKILL_FILE_BYTES, severity: 'hard' },
29
+ skillName: { id: 'skill.name', axis: 'storage', unit: 'codePoints', limit: MAX_SKILL_NAME_LENGTH, severity: 'hard' },
30
+ skillDescription: { id: 'skill.description.hard', axis: 'display', unit: 'graphemes', limit: MAX_DESCRIPTION_LENGTH, severity: 'hard' },
31
+ skillDescriptionAuthoring: { id: 'skill.description.authoring', axis: 'display', unit: 'graphemes', limit: AUTHORING_DESCRIPTION_BAR, severity: 'soft' },
32
+ skillSummary: { id: 'skill.summary', axis: 'display', unit: 'graphemes', limit: DEFAULT_SKILL_WRITE_SUMMARY_CHARS, severity: 'hard' },
33
+ feedbackNote: { id: 'feedback.note', axis: 'display', unit: 'graphemes', limit: 20, severity: 'hard' },
34
+ lineLength: { id: 'skill.line', axis: 'display', unit: 'graphemes', limit: DRIFT_MAX_LINE_CHARS, severity: 'soft' },
35
+ substantiveUser: { id: 'review.substantive.user', axis: 'display', unit: 'graphemes', limit: DEFAULT_SUBSTANTIVE_MIN_USER_CHARS, severity: 'soft' },
36
+ substantiveAgent: { id: 'review.substantive.agent', axis: 'display', unit: 'graphemes', limit: DEFAULT_SUBSTANTIVE_MIN_AGENT_CHARS, severity: 'soft' },
37
+ retentionFeedback: { id: 'history.retention-feedback', axis: 'display', unit: 'graphemes', limit: 200, severity: 'report' },
38
+ bodySoft: { id: 'skill.body.soft', axis: 'context', unit: 'tokens', limit: SOFT_BODY_TOKENS, severity: 'soft' },
39
+ memory: { id: 'memory.budget', axis: 'context', unit: 'tokens', limit: MEMORY_TOKENS, severity: 'hard' },
40
+ user: { id: 'user.budget', axis: 'context', unit: 'tokens', limit: USER_TOKENS, severity: 'hard' },
41
+ };
42
+ /**
43
+ * Compare one string against one named budget.
44
+ * @param text - the string to measure.
45
+ * @param budget - the budget to apply.
46
+ * @param estimator - optional token source for token budgets.
47
+ * @returns the measured value and the remaining allowance (negative when over).
48
+ */
49
+ export function compareTextBudget(text, budget, estimator) {
50
+ const metrics = measureText(text, estimator);
51
+ const measured = budget.unit === 'tokens'
52
+ ? metrics.tokens.value
53
+ : budget.unit === 'utf8Bytes'
54
+ ? metrics.utf8Bytes
55
+ : budget.unit === 'codePoints'
56
+ ? metrics.codePoints
57
+ : metrics.graphemes;
58
+ return {
59
+ budget,
60
+ value: measured,
61
+ over: measured > budget.limit,
62
+ remaining: budget.limit - measured,
63
+ };
64
+ }
65
+ //# sourceMappingURL=text-budgets.js.map