@lmzhen/dsh-evolution-core 0.54.0 → 0.55.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/lib/{extract-plan-D4zO7dmD.js → extract-plan-BxDhKSki.js} +2 -1
  2. package/lib/extract.js +7 -7
  3. package/lib/index.js +830 -546
  4. package/lib/{limits-TD4Pv92Q.js → limits-CO4JGSJL.js} +20 -6
  5. package/lib/{skill-history-CZp8vhyL.js → mutation-storage-adapter-7R3ra0wj.js} +4 -647
  6. package/lib/mutations-mvTnWkua.js +592 -0
  7. package/lib/policy.js +9 -3
  8. package/lib/{quality-BLc6UQQb.js → quality-CREp6s1G.js} +1 -1
  9. package/lib/{skill-health-BIpiPvw6.js → review-context-70XYS11J.js} +124 -183
  10. package/lib/runtime/plugin.js +1 -1
  11. package/lib/{session-projection-ByNxQi9O.js → session-projection-CbIKvDfJ.js} +3 -2
  12. package/lib/skill-history-YX84wO20.js +647 -0
  13. package/lib/skills.js +16 -11
  14. package/lib/text-metrics-CyJhxWBs.js +132 -0
  15. package/lib/types/constants.d.ts +19 -5
  16. package/lib/types/constants.js +19 -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/signals.js +3 -2
  32. package/lib/types/skill-health.d.ts +8 -5
  33. package/lib/types/skill-health.js +27 -28
  34. package/lib/types/skill-history.d.ts +2 -2
  35. package/lib/types/skill-history.js +9 -8
  36. package/lib/types/skill-lint.d.ts +1 -1
  37. package/lib/types/skill-lint.js +4 -4
  38. package/lib/types/skill-stats.d.ts +3 -1
  39. package/lib/types/skill-stats.js +7 -3
  40. package/lib/types/skill-store.js +2 -1
  41. package/lib/types/text-budgets.d.ts +185 -0
  42. package/lib/types/text-budgets.js +70 -0
  43. package/lib/types/text-metrics.d.ts +88 -0
  44. package/lib/types/text-metrics.js +131 -0
  45. package/lib/{usage-B1qveKi9.js → usage-DrczLTP4.js} +2 -515
  46. package/lib/write.js +3 -2
  47. package/package.json +1 -1
  48. package/lib/mutations-DQXddSJd.js +0 -75
  49. package/lib/types/cost.d.ts +0 -63
  50. package/lib/types/cost.js +0 -67
@@ -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,8 @@ 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";
34
+ import { TEXT_DIFF_MAX_GRAPHEMES } from "./constants.js";
33
35
  /** Root-level history directory. Dot-prefixed so skill discovery skips it. */
34
36
  export const HISTORY_DIR = '.history';
35
37
  /** Versioned index shape, so a future field can migrate without guessing. */
@@ -37,11 +39,11 @@ export const HISTORY_INDEX_VERSION = 1;
37
39
  /** The action label for a predecessor the index had never seen (content found on disk before this
38
40
  * feature existed, or a hand-edited tree): it says "this is what was there", not what wrote it. */
39
41
  export const BASELINE_ACTION = 'baseline';
40
- /** Default hard cap for a change summary, counted in Unicode code points. */
42
+ /** Default hard cap for a change summary, counted in grapheme clusters. */
41
43
  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). */
44
+ /** Count a summary the same way the write gate does (graphemes, not UTF-16 units). */
43
45
  export function summaryChars(text) {
44
- return [...text].length;
46
+ return graphemeCount(text);
45
47
  }
46
48
  /** Normalize a model-supplied summary: single line, trimmed, non-empty, within the hard cap. */
47
49
  export function normalizeChangeSummary(value, cap = DEFAULT_SKILL_WRITE_SUMMARY_CHARS) {
@@ -58,8 +60,7 @@ export function normalizeChangeSummary(value, cap = DEFAULT_SKILL_WRITE_SUMMARY_
58
60
  /** Clip a host-generated summary to the same hard cap; host facts are not rejected. */
59
61
  export function clipChangeSummary(text, cap = DEFAULT_SKILL_WRITE_SUMMARY_CHARS) {
60
62
  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('') + '…';
63
+ return truncateGraphemes(line, cap);
63
64
  }
64
65
  /** The root-level history directory. */
65
66
  export function historyRoot(root) {
@@ -648,7 +649,7 @@ export function versionActionKind(action) {
648
649
  /** Lines one changed region may carry before it is windowed and flagged. */
649
650
  export const TEXT_DIFF_MAX_LINES = 40;
650
651
  /** Characters one windowed side may carry, so a single enormous line cannot travel whole. */
651
- export const TEXT_DIFF_MAX_CHARS = 4_000;
652
+ export const TEXT_DIFF_MAX_CHARS = TEXT_DIFF_MAX_GRAPHEMES;
652
653
  /**
653
654
  * The facts of one whole-body replacement: how many lines the changed region gained and lost, and
654
655
  * that region itself as one hunk.
@@ -685,9 +686,9 @@ export function textDiffFacts(before, after, path, maxLines = TEXT_DIFF_MAX_LINE
685
686
  const window = (lines) => {
686
687
  const byLines = lines.slice(0, maxLines);
687
688
  const joined = byLines.join('\n');
688
- if (joined.length <= TEXT_DIFF_MAX_CHARS)
689
+ if (graphemeCount(joined) <= TEXT_DIFF_MAX_CHARS)
689
690
  return { text: joined, cut: lines.length > maxLines };
690
- return { text: joined.slice(0, TEXT_DIFF_MAX_CHARS), cut: true };
691
+ return { text: truncateGraphemes(joined, TEXT_DIFF_MAX_CHARS, ''), cut: true };
691
692
  };
692
693
  const oldWindow = window(oldRegion);
693
694
  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';
@@ -50,11 +50,13 @@ export function verdictRank(verdict) {
50
50
  return 0;
51
51
  if (verdict === 'warn')
52
52
  return 1;
53
- if (verdict === 'unknown')
53
+ if (verdict === 'unreadable')
54
54
  return 2;
55
- if (verdict === 'healthy')
55
+ if (verdict === 'unknown')
56
56
  return 3;
57
- return 4;
57
+ if (verdict === 'healthy')
58
+ return 4;
59
+ return 5;
58
60
  }
59
61
  /** Stable name comparison shared by every tie-break. */
60
62
  function compareNames(left, right) {
@@ -66,6 +68,7 @@ export function sortValue(row, key) {
66
68
  case 'name': return row.name;
67
69
  case 'verdict': return verdictRank(row.health?.verdict);
68
70
  case 'bodyChars': return row.health?.bodyChars ?? null;
71
+ case 'bodyTokens': return row.health?.bodyTokens ?? null;
69
72
  case 'supportFiles': return row.health?.supportFiles ?? null;
70
73
  case 'versions': return row.versions;
71
74
  case 'useCount': return row.usage?.useCount ?? null;
@@ -129,6 +132,7 @@ export function computeSkillStatsTotals(rows, counts) {
129
132
  skills: rows.length,
130
133
  needsAttention: rows.filter(needsAttention).length,
131
134
  bodyChars: sumNullable(rows.map(row => row.health?.bodyChars ?? null)),
135
+ bodyTokens: sumNullable(rows.map(row => row.health?.bodyTokens ?? null)),
132
136
  supportFiles: sumNullable(rows.map(row => row.health?.supportFiles ?? null)),
133
137
  successes: counts,
134
138
  };
@@ -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,185 @@
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 diffWindow: {
121
+ readonly id: "history.diff-window";
122
+ readonly axis: "display";
123
+ readonly unit: "graphemes";
124
+ readonly limit: 4000;
125
+ readonly severity: "report";
126
+ };
127
+ readonly reviewPreview: {
128
+ readonly id: "history.review-preview";
129
+ readonly axis: "display";
130
+ readonly unit: "graphemes";
131
+ readonly limit: 2000;
132
+ readonly severity: "report";
133
+ };
134
+ readonly memoryPreview: {
135
+ readonly id: "memory.entry-preview";
136
+ readonly axis: "display";
137
+ readonly unit: "graphemes";
138
+ readonly limit: 200;
139
+ readonly severity: "report";
140
+ };
141
+ readonly versionBodyPreview: {
142
+ readonly id: "history.body-preview";
143
+ readonly axis: "display";
144
+ readonly unit: "graphemes";
145
+ readonly limit: 20000;
146
+ readonly severity: "report";
147
+ };
148
+ readonly mergeBodyPreview: {
149
+ readonly id: "merge.body-preview";
150
+ readonly axis: "display";
151
+ readonly unit: "utf8Bytes";
152
+ readonly limit: number;
153
+ readonly severity: "report";
154
+ };
155
+ readonly bodySoft: {
156
+ readonly id: "skill.body.soft";
157
+ readonly axis: "context";
158
+ readonly unit: "tokens";
159
+ readonly limit: number;
160
+ readonly severity: "soft";
161
+ };
162
+ readonly memory: {
163
+ readonly id: "memory.budget";
164
+ readonly axis: "context";
165
+ readonly unit: "tokens";
166
+ readonly limit: number;
167
+ readonly severity: "hard";
168
+ };
169
+ readonly user: {
170
+ readonly id: "user.budget";
171
+ readonly axis: "context";
172
+ readonly unit: "tokens";
173
+ readonly limit: number;
174
+ readonly severity: "hard";
175
+ };
176
+ };
177
+ /**
178
+ * Compare one string against one named budget.
179
+ * @param text - the string to measure.
180
+ * @param budget - the budget to apply.
181
+ * @param estimator - optional token source for token budgets.
182
+ * @returns the measured value and the remaining allowance (negative when over).
183
+ */
184
+ export declare function compareTextBudget(text: string, budget: TextBudget, estimator?: TokenEstimator): TextBudgetResult;
185
+ //# sourceMappingURL=text-budgets.d.ts.map
@@ -0,0 +1,70 @@
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, MERGE_BODY_PREVIEW_BYTES, MEMORY_ENTRY_PREVIEW_GRAPHEMES, REVIEW_TEXT_PREVIEW_GRAPHEMES, TEXT_DIFF_MAX_GRAPHEMES, VERSION_BODY_PREVIEW_GRAPHEMES, } 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
+ diffWindow: { id: 'history.diff-window', axis: 'display', unit: 'graphemes', limit: TEXT_DIFF_MAX_GRAPHEMES, severity: 'report' },
39
+ reviewPreview: { id: 'history.review-preview', axis: 'display', unit: 'graphemes', limit: REVIEW_TEXT_PREVIEW_GRAPHEMES, severity: 'report' },
40
+ memoryPreview: { id: 'memory.entry-preview', axis: 'display', unit: 'graphemes', limit: MEMORY_ENTRY_PREVIEW_GRAPHEMES, severity: 'report' },
41
+ versionBodyPreview: { id: 'history.body-preview', axis: 'display', unit: 'graphemes', limit: VERSION_BODY_PREVIEW_GRAPHEMES, severity: 'report' },
42
+ mergeBodyPreview: { id: 'merge.body-preview', axis: 'display', unit: 'utf8Bytes', limit: MERGE_BODY_PREVIEW_BYTES, severity: 'report' },
43
+ bodySoft: { id: 'skill.body.soft', axis: 'context', unit: 'tokens', limit: SOFT_BODY_TOKENS, severity: 'soft' },
44
+ memory: { id: 'memory.budget', axis: 'context', unit: 'tokens', limit: MEMORY_TOKENS, severity: 'hard' },
45
+ user: { id: 'user.budget', axis: 'context', unit: 'tokens', limit: USER_TOKENS, severity: 'hard' },
46
+ };
47
+ /**
48
+ * Compare one string against one named budget.
49
+ * @param text - the string to measure.
50
+ * @param budget - the budget to apply.
51
+ * @param estimator - optional token source for token budgets.
52
+ * @returns the measured value and the remaining allowance (negative when over).
53
+ */
54
+ export function compareTextBudget(text, budget, estimator) {
55
+ const metrics = measureText(text, estimator);
56
+ const measured = budget.unit === 'tokens'
57
+ ? metrics.tokens.value
58
+ : budget.unit === 'utf8Bytes'
59
+ ? metrics.utf8Bytes
60
+ : budget.unit === 'codePoints'
61
+ ? metrics.codePoints
62
+ : metrics.graphemes;
63
+ return {
64
+ budget,
65
+ value: measured,
66
+ over: measured > budget.limit,
67
+ remaining: budget.limit - measured,
68
+ };
69
+ }
70
+ //# sourceMappingURL=text-budgets.js.map
@@ -0,0 +1,88 @@
1
+ /**
2
+ * One text-metrics source for every character-based budget in the family.
3
+ *
4
+ * A budget is not a language: the same text needs different units for storage,
5
+ * display, context cost and quality heuristics. This module measures ONE string
6
+ * once and exposes the four units; callers choose a unit through a named budget
7
+ * instead of reaching for `String.length`, `[...text].length` or `slice()`.
8
+ *
9
+ * The token figure is deliberately an ESTIMATE. With no model tokenizer it uses
10
+ * a script-neutral conservative upper bound (`utf8Bytes / 3`, floored by
11
+ * `codePoints / 4`); a caller may inject a provider/model estimator later
12
+ * without changing any budget.
13
+ *
14
+ * @module @lmzhen/dsh-evolution-core
15
+ */
16
+ /** Units a text budget may use. */
17
+ export type TextUnit = 'utf8Bytes' | 'codePoints' | 'graphemes' | 'tokens';
18
+ /** One token estimate, with the measurement range kept visible for UI copy. */
19
+ export interface TokenEstimate {
20
+ /** Conservative point estimate a gate should compare against. */
21
+ readonly value: number;
22
+ /** Lower end of the model-agnostic range (never presented as an exact count). */
23
+ readonly low: number;
24
+ /** Upper end of the model-agnostic range. */
25
+ readonly high: number;
26
+ readonly source: 'unicode-heuristic' | 'platform' | 'model';
27
+ }
28
+ /** All units for one text, measured together so callers cannot drift. */
29
+ export interface TextMetrics {
30
+ /** UTF-8 byte length. */
31
+ readonly utf8Bytes: number;
32
+ /** Unicode scalar values (code points). */
33
+ readonly codePoints: number;
34
+ /** User-perceived characters; falls back to code points without Intl.Segmenter. */
35
+ readonly graphemes: number;
36
+ readonly tokens: TokenEstimate;
37
+ /** True when the runtime lacked Intl.Segmenter and graphemes are code points. */
38
+ readonly degraded: boolean;
39
+ }
40
+ /** Replaceable token estimator; a provider/model adapter can supply exact counts. */
41
+ export type TokenEstimator = (text: string) => TokenEstimate;
42
+ /** UTF-8 byte length; TextEncoder is available on every Node/browser target this package runs on. */
43
+ export declare function utf8ByteLength(text: string): number;
44
+ /** Unicode scalar-value count. */
45
+ export declare function codePointCount(text: string): number;
46
+ /**
47
+ * User-perceived character count.
48
+ * @param text - the string to measure.
49
+ * @returns grapheme clusters, or code points when the runtime has no Segmenter.
50
+ */
51
+ export declare function graphemeCount(text: string): number;
52
+ /**
53
+ * Conservative, model-agnostic token estimate.
54
+ *
55
+ * English prose is about 4 characters/token; CJK prose is about 1 token/char.
56
+ * UTF-8 bytes encode that difference naturally (3 bytes for CJK, 1 for ASCII),
57
+ * so the upper bound is `bytes / 3` while `codePoints / 4` keeps the lower end
58
+ * anchored to the common English heuristic. The point estimate is the upper
59
+ * bound: early warnings are recoverable, silent over-budget is not.
60
+ * @param text - the string to estimate.
61
+ * @returns the estimate and its range; never an exact tokenizer count.
62
+ */
63
+ export declare function conservativeTokenEstimator(text: string): TokenEstimate;
64
+ /**
65
+ * Measure every unit for one string in one pass over the text.
66
+ * @param text - the raw string; body callers should pass the on-disk form.
67
+ * @param estimator - optional exact/estimated token source; defaults to the conservative fallback.
68
+ * @returns all units and the token range.
69
+ */
70
+ export declare function measureText(text: string, estimator?: TokenEstimator): TextMetrics;
71
+ /**
72
+ * Read one unit from a fresh measurement.
73
+ * @param text - the string to measure.
74
+ * @param unit - the budget unit to read.
75
+ * @param estimator - optional token source; ignored for non-token units.
76
+ * @returns the numeric value in that unit.
77
+ */
78
+ export declare function measureUnit(text: string, unit: TextUnit, estimator?: TokenEstimator): number;
79
+ /**
80
+ * Truncate to a grapheme budget without splitting emoji or combining sequences.
81
+ * The ellipsis counts inside `max`, matching how UI budgets are described.
82
+ * @param text - the string to shorten.
83
+ * @param max - maximum output graphemes, ellipsis included.
84
+ * @param ellipsis - marker appended when shortened; may itself be multi-grapheme.
85
+ * @returns the original text or a grapheme-safe prefix plus marker.
86
+ */
87
+ export declare function truncateGraphemes(text: string, max: number, ellipsis?: string): string;
88
+ //# sourceMappingURL=text-metrics.d.ts.map