@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
package/lib/skills.js CHANGED
@@ -1,13 +1,15 @@
1
1
  import { _ as probeMtime, b as probeText, c as transactIo, d as isAbsent, g as probeList, h as probeAbsent, i as isCommittedWarning, m as isUnknown, o as nodeEvolutionIo, p as isPresent, t as TransactionNotInvokedError, v as probePresent, x as probeUnknown, y as probeReason } from "./io-GxghO3Ip.js";
2
2
  import { n as mutationLockFrom } from "./mutation-authority-DQfpXs1O.js";
3
3
  import { o as resolveCitations } from "./citations-CZKTUGQF.js";
4
- import { G as SKILL_NAME_RE, H as PROTECTED_BUILTIN_SKILLS, K as SUPPORT_DIRS, a as DEFAULT_SUPPORT_FILE_CHAR_POLICY, i as DEFAULT_SKILL_LIMITS, n as DEFAULT_CITATION_POLICY, o as POLICY_STAGE_DEFAULTS, r as DEFAULT_REFERENCE_REWRITE_POLICY, s as policyStageLimits, t as DEFAULT_ARCHIVE_RETENTION_POLICY, u as CONTENT_SPLIT_HINT } from "./limits-TD4Pv92Q.js";
5
- import { C as trimPatternBoundaries, I as RULES, J as filterUnreadSkillOps, L as diffFindings, O as appendEvolutionEvent, R as lintSkill, S as fuzzyPatch, X as sessionReadSkillNames, Y as isUnreadWrite, Z as sessionReadSupportFiles, a as lintBody, et as authorityFrom, g as scanContentThreats, i as assessStructureHealth, k as eventsFile, n as HEALTH_STAMP_RE, o as currentReviewContext, q as READ_REQUIRED_ACTIONS, r as MIN_STAMP_BODY_CHARS, t as DEFAULT_HEALTH_THRESHOLDS, u as isReviewChannelSession, y as makeSerialQueue } from "./skill-health-BIpiPvw6.js";
6
- import { B as shrinksOverLimit, E as usageFile, F as frontmatterBlock, G as supportRefs, H as validateFrontmatter, I as frontmatterCatalogInvalid, J as planReferenceRewrite, K as applyReferenceRewrite, L as normalizeFrontmatter, M as authoringFeedback, N as ensureSkillFrontmatter, O as selectSections, P as exceedsContentLimit, R as parseFrontmatter, U as yamlPlainScalarNeedsQuotes, V as skillMdOnDisk, Y as planRehoming, _ as loadUsage, p as getRecord, q as describeReferenceRewrite, w as suppressedFile, y as mutateUsage, z as relatedSkillNames } from "./usage-B1qveKi9.js";
4
+ import { Q as SUPPORT_DIRS, Z as SKILL_NAME_RE, a as DEFAULT_SUPPORT_FILE_CHAR_POLICY, i as DEFAULT_SKILL_LIMITS, n as DEFAULT_CITATION_POLICY, o as POLICY_STAGE_DEFAULTS, q as PROTECTED_BUILTIN_SKILLS, r as DEFAULT_REFERENCE_REWRITE_POLICY, s as policyStageLimits, t as DEFAULT_ARCHIVE_RETENTION_POLICY, u as CONTENT_SPLIT_HINT } from "./limits-CO4JGSJL.js";
5
+ import { B as READ_REQUIRED_ACTIONS, C as appendEvolutionEvent, F as lintBody, H as isUnreadWrite, I as softBodyTokenBudget, L as RULES, M as HEALTH_STAMP_RE, N as MIN_STAMP_BODY_CHARS, P as assessStructureHealth, R as diffFindings, U as sessionReadSkillNames, V as filterUnreadSkillOps, W as sessionReadSupportFiles, _ as fuzzyPatch, a as isReviewChannelSession, d as scanContentThreats, j as DEFAULT_HEALTH_THRESHOLDS, m as makeSerialQueue, q as authorityFrom, t as currentReviewContext, v as trimPatternBoundaries, w as eventsFile, z as lintSkill } from "./review-context-70XYS11J.js";
6
+ import { a as measureUnit } from "./text-metrics-CyJhxWBs.js";
7
+ import { E as usageFile, F as describeReferenceRewrite, I as planReferenceRewrite, L as planRehoming, N as supportRefs, O as selectSections, P as applyReferenceRewrite, _ as loadUsage, p as getRecord, w as suppressedFile, y as mutateUsage } from "./usage-DrczLTP4.js";
8
+ import { _ as validateFrontmatter, c as ensureSkillFrontmatter, d as frontmatterCatalogInvalid, f as normalizeFrontmatter, g as skillMdOnDisk, h as shrinksOverLimit, i as loadMutations, l as exceedsContentLimit, m as relatedSkillNames, o as recordMutation, p as parseFrontmatter, r as contentHash, s as authoringFeedback, u as frontmatterBlock, v as yamlPlainScalarNeedsQuotes } from "./mutations-mvTnWkua.js";
7
9
  import { n as evolutionRoot } from "./state-store-Jpa-iYIZ.js";
8
- import { i as loadMutations, o as recordMutation, r as contentHash } from "./mutations-DQXddSJd.js";
9
- import { A as pruneTreeChangeUnits, C as partitionVersions, D as textDiffFacts, E as summaryChars, M as unitSnapshotPort, O as versionActionKind, S as parseHistoryIndex, T as recordVersions, _ as loadVersionContent, a as RETENTION_FEEDBACK_KEEP_RATIO, b as normalizeChangeSummary, c as TEXT_DIFF_MAX_LINES, d as contentRetentionFeedback, f as elapsedSince, g as latestVersionAt, h as historyRoot, i as HISTORY_INDEX_VERSION, j as unitJournalPort, k as versionTarget, l as blobPath, m as historyIndexFile, n as DEFAULT_SKILL_WRITE_SUMMARY_CHARS, nt as fileMutationLock, o as RETENTION_FEEDBACK_MIN_CHARS, p as entryTarget, r as HISTORY_DIR, s as TEXT_DIFF_MAX_CHARS, t as BASELINE_ACTION, tt as MutationUnit, u as clipChangeSummary, v as loadVersions, w as readHistoryIndex, x as orderVersions, y as nextHistoryIndex } from "./skill-history-CZp8vhyL.js";
10
- import { n as projectExtractBodies } from "./extract-plan-D4zO7dmD.js";
10
+ import { C as partitionVersions, D as textDiffFacts, E as summaryChars, O as versionActionKind, S as parseHistoryIndex, T as recordVersions, _ as loadVersionContent, a as RETENTION_FEEDBACK_KEEP_RATIO, b as normalizeChangeSummary, c as TEXT_DIFF_MAX_LINES, d as contentRetentionFeedback, f as elapsedSince, g as latestVersionAt, h as historyRoot, i as HISTORY_INDEX_VERSION, k as versionTarget, l as blobPath, m as historyIndexFile, n as DEFAULT_SKILL_WRITE_SUMMARY_CHARS, o as RETENTION_FEEDBACK_MIN_CHARS, p as entryTarget, r as HISTORY_DIR, s as TEXT_DIFF_MAX_CHARS, t as BASELINE_ACTION, u as clipChangeSummary, v as loadVersions, w as readHistoryIndex, x as orderVersions, y as nextHistoryIndex } from "./skill-history-YX84wO20.js";
11
+ import { D as fileMutationLock, E as MutationUnit, n as unitJournalPort, r as unitSnapshotPort, t as pruneTreeChangeUnits } from "./mutation-storage-adapter-7R3ra0wj.js";
12
+ import { n as projectExtractBodies } from "./extract-plan-BxDhKSki.js";
11
13
  import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
12
14
  //#region lib/types/skill-stats.js
13
15
  /**
@@ -55,9 +57,10 @@ function verdictRank(verdict) {
55
57
  if (verdict === null || verdict === void 0 || verdict === "") return null;
56
58
  if (verdict === "needs-restructure") return 0;
57
59
  if (verdict === "warn") return 1;
58
- if (verdict === "unknown") return 2;
59
- if (verdict === "healthy") return 3;
60
- return 4;
60
+ if (verdict === "unreadable") return 2;
61
+ if (verdict === "unknown") return 3;
62
+ if (verdict === "healthy") return 4;
63
+ return 5;
61
64
  }
62
65
  /** Stable name comparison shared by every tie-break. */
63
66
  function compareNames(left, right) {
@@ -72,6 +75,7 @@ function sortValue(row, key) {
72
75
  case "name": return row.name;
73
76
  case "verdict": return verdictRank(row.health?.verdict);
74
77
  case "bodyChars": return row.health?.bodyChars ?? null;
78
+ case "bodyTokens": return row.health?.bodyTokens ?? null;
75
79
  case "supportFiles": return row.health?.supportFiles ?? null;
76
80
  case "versions": return row.versions;
77
81
  case "useCount": return row.usage?.useCount ?? null;
@@ -126,6 +130,7 @@ function computeSkillStatsTotals(rows, counts) {
126
130
  skills: rows.length,
127
131
  needsAttention: rows.filter(needsAttention).length,
128
132
  bodyChars: sumNullable(rows.map((row) => row.health?.bodyChars ?? null)),
133
+ bodyTokens: sumNullable(rows.map((row) => row.health?.bodyTokens ?? null)),
129
134
  supportFiles: sumNullable(rows.map((row) => row.health?.supportFiles ?? null)),
130
135
  successes: counts
131
136
  };
@@ -1298,7 +1303,7 @@ var SkillLibrary = class {
1298
1303
  */
1299
1304
  badName(name, opts = {}) {
1300
1305
  const normalized = name.trim();
1301
- if (!SKILL_NAME_RE.test(normalized) || normalized.length > this.limits.maxNameLength) return `技能名「${normalized}」不合法:请只用小写字母、数字和连字符(不超过 ${this.limits.maxNameLength} 个)。`;
1306
+ if (!SKILL_NAME_RE.test(normalized) || measureUnit(normalized, "codePoints") > this.limits.maxNameLength) return `技能名「${normalized}」不合法:请只用小写字母、数字和连字符(不超过 ${this.limits.maxNameLength} 个)。`;
1302
1307
  if (!opts.allowReserved && WIN32_RESERVED_DEVICE_NAMES.has(normalized)) return `"${normalized}" is a Windows reserved device name and cannot be used as a skill name.`;
1303
1308
  return null;
1304
1309
  }
@@ -4330,4 +4335,4 @@ function newSkillLibrary(options) {
4330
4335
  } : void 0, transact, [...threatExemptLabels ?? []], authority, options.mutationLock ?? mutationLockFrom(ctx), options.fence ?? ctx?.get?.("evolutionMutationAuthority")?.homeFence);
4331
4336
  }
4332
4337
  //#endregion
4333
- export { BASELINE_ACTION, DEFAULT_ARCHIVE_RETENTION_POLICY, DEFAULT_CITATION_POLICY, DEFAULT_HEALTH_THRESHOLDS, DEFAULT_REFERENCE_REWRITE_POLICY, DEFAULT_SKILL_LIMITS, DEFAULT_SKILL_WRITE_SUMMARY_CHARS, DEFAULT_SUPPORT_FILE_CHAR_POLICY, HEALTH_STAMP_RE, HISTORY_DIR, HISTORY_INDEX_VERSION, MAX_RESTRUCTURE_MOVES, MIN_STAMP_BODY_CHARS, POLICY_STAGE_DEFAULTS, READ_REQUIRED_ACTIONS, RECENT_USE_WINDOW_DAYS, RESTRUCTURE_TARGET_RE, RETENTION_FEEDBACK_KEEP_RATIO, RETENTION_FEEDBACK_MIN_CHARS, RULES, SKILL_OPERATIONS, SNAPSHOT_EXTRA_NAME_RE, SkillLibrary, SkillModel, TEXT_DIFF_MAX_CHARS, TEXT_DIFF_MAX_LINES, ageCopyKey, anchorVerdict, assertSkillsRootAliasRetired, assessStructureHealth, authoringFeedback, blobPath, clipChangeSummary, compareSkillStats, computeSkillStatsTotals, contentRetentionFeedback, diffFindings, elapsedSince, ensureSkillFrontmatter, entryTarget, exceedsContentLimit, filterSkillStats, filterUnreadSkillOps, frontmatterBlock, frontmatterCatalogInvalid, historyIndexFile, historyRoot, isUnreadWrite, latestActivityAt, latestVersionAt, lintBody, lintSkill, loadVersionContent, loadVersions, markerEntryName, needsAttention, newSkillLibrary, nextHistoryIndex, normalizeChangeSummary, normalizeFrontmatter, orderVersions, parseFrontmatter, parseHistoryIndex, partitionVersions, policyStageLimits, readHistoryIndex, recentlyUsedAt, recordVersions, relatedSkillNames, resolveExecOrigins, resolveOrigins, resolveRootConfig, resolveSkillsRoot, revisionAnchor, revisionAnchorOf, revisionFingerprint, revisionSupportDigest, sessionReadSkillNames, sessionReadSupportFiles, shrinksOverLimit, skillMdOnDisk, skillRowCells, skillStateKey, skillsRoot, sortSkillStats, sortValue, summaryChars, textDiffFacts, validateFrontmatter, validateRestructureTarget, validateSupportPath, verdictRank, versionActionKind, versionRowCells, versionTarget, yamlPlainScalarNeedsQuotes };
4338
+ export { BASELINE_ACTION, DEFAULT_ARCHIVE_RETENTION_POLICY, DEFAULT_CITATION_POLICY, DEFAULT_HEALTH_THRESHOLDS, DEFAULT_REFERENCE_REWRITE_POLICY, DEFAULT_SKILL_LIMITS, DEFAULT_SKILL_WRITE_SUMMARY_CHARS, DEFAULT_SUPPORT_FILE_CHAR_POLICY, HEALTH_STAMP_RE, HISTORY_DIR, HISTORY_INDEX_VERSION, MAX_RESTRUCTURE_MOVES, MIN_STAMP_BODY_CHARS, POLICY_STAGE_DEFAULTS, READ_REQUIRED_ACTIONS, RECENT_USE_WINDOW_DAYS, RESTRUCTURE_TARGET_RE, RETENTION_FEEDBACK_KEEP_RATIO, RETENTION_FEEDBACK_MIN_CHARS, RULES, SKILL_OPERATIONS, SNAPSHOT_EXTRA_NAME_RE, SkillLibrary, SkillModel, TEXT_DIFF_MAX_CHARS, TEXT_DIFF_MAX_LINES, ageCopyKey, anchorVerdict, assertSkillsRootAliasRetired, assessStructureHealth, authoringFeedback, blobPath, clipChangeSummary, compareSkillStats, computeSkillStatsTotals, contentRetentionFeedback, diffFindings, elapsedSince, ensureSkillFrontmatter, entryTarget, exceedsContentLimit, filterSkillStats, filterUnreadSkillOps, frontmatterBlock, frontmatterCatalogInvalid, historyIndexFile, historyRoot, isUnreadWrite, latestActivityAt, latestVersionAt, lintBody, lintSkill, loadVersionContent, loadVersions, markerEntryName, needsAttention, newSkillLibrary, nextHistoryIndex, normalizeChangeSummary, normalizeFrontmatter, orderVersions, parseFrontmatter, parseHistoryIndex, partitionVersions, policyStageLimits, readHistoryIndex, recentlyUsedAt, recordVersions, relatedSkillNames, resolveExecOrigins, resolveOrigins, resolveRootConfig, resolveSkillsRoot, revisionAnchor, revisionAnchorOf, revisionFingerprint, revisionSupportDigest, sessionReadSkillNames, sessionReadSupportFiles, shrinksOverLimit, skillMdOnDisk, skillRowCells, skillStateKey, skillsRoot, softBodyTokenBudget, sortSkillStats, sortValue, summaryChars, textDiffFacts, validateFrontmatter, validateRestructureTarget, validateSupportPath, verdictRank, versionActionKind, versionRowCells, versionTarget, yamlPlainScalarNeedsQuotes };
@@ -0,0 +1,132 @@
1
+ //#region lib/types/text-metrics.js
2
+ /**
3
+ * One text-metrics source for every character-based budget in the family.
4
+ *
5
+ * A budget is not a language: the same text needs different units for storage,
6
+ * display, context cost and quality heuristics. This module measures ONE string
7
+ * once and exposes the four units; callers choose a unit through a named budget
8
+ * instead of reaching for `String.length`, `[...text].length` or `slice()`.
9
+ *
10
+ * The token figure is deliberately an ESTIMATE. With no model tokenizer it uses
11
+ * a script-neutral conservative upper bound (`utf8Bytes / 3`, floored by
12
+ * `codePoints / 4`); a caller may inject a provider/model estimator later
13
+ * without changing any budget.
14
+ *
15
+ * @module @lmzhen/dsh-evolution-core
16
+ */
17
+ const segmenterCtor = Intl.Segmenter;
18
+ const segmenter = segmenterCtor === void 0 ? void 0 : new segmenterCtor(void 0, { granularity: "grapheme" });
19
+ /** UTF-8 byte length; TextEncoder is available on every Node/browser target this package runs on. */
20
+ function utf8ByteLength(text) {
21
+ return new TextEncoder().encode(text).length;
22
+ }
23
+ /** Unicode scalar-value count. */
24
+ function codePointCount(text) {
25
+ let count = 0;
26
+ for (const _codePoint of text) count += 1;
27
+ return count;
28
+ }
29
+ /**
30
+ * User-perceived character count.
31
+ * @param text - the string to measure.
32
+ * @returns grapheme clusters, or code points when the runtime has no Segmenter.
33
+ */
34
+ function graphemeCount(text) {
35
+ if (segmenter === void 0) return codePointCount(text);
36
+ let count = 0;
37
+ for (const _grapheme of segmenter.segment(text)) count += 1;
38
+ return count;
39
+ }
40
+ /** Split a string without ever cutting through a grapheme cluster. */
41
+ function graphemeParts(text) {
42
+ if (segmenter === void 0) return [...text];
43
+ const parts = [];
44
+ for (const part of segmenter.segment(text)) {
45
+ const value = part.segment;
46
+ if (typeof value === "string") parts.push(value);
47
+ }
48
+ return parts;
49
+ }
50
+ /** The pure estimate from already-counted bytes/code points. */
51
+ function estimateFromCounts(bytes, codePoints) {
52
+ if (bytes === 0) return {
53
+ value: 0,
54
+ low: 0,
55
+ high: 0,
56
+ source: "unicode-heuristic"
57
+ };
58
+ const low = Math.ceil(codePoints / 4);
59
+ const high = Math.ceil(bytes / 3);
60
+ return {
61
+ value: Math.max(low, high),
62
+ low,
63
+ high,
64
+ source: "unicode-heuristic"
65
+ };
66
+ }
67
+ /**
68
+ * Conservative, model-agnostic token estimate.
69
+ *
70
+ * English prose is about 4 characters/token; CJK prose is about 1 token/char.
71
+ * UTF-8 bytes encode that difference naturally (3 bytes for CJK, 1 for ASCII),
72
+ * so the upper bound is `bytes / 3` while `codePoints / 4` keeps the lower end
73
+ * anchored to the common English heuristic. The point estimate is the upper
74
+ * bound: early warnings are recoverable, silent over-budget is not.
75
+ * @param text - the string to estimate.
76
+ * @returns the estimate and its range; never an exact tokenizer count.
77
+ */
78
+ function conservativeTokenEstimator(text) {
79
+ return estimateFromCounts(utf8ByteLength(text), codePointCount(text));
80
+ }
81
+ /**
82
+ * Measure every unit for one string in one pass over the text.
83
+ * @param text - the raw string; body callers should pass the on-disk form.
84
+ * @param estimator - optional exact/estimated token source; defaults to the conservative fallback.
85
+ * @returns all units and the token range.
86
+ */
87
+ function measureText(text, estimator) {
88
+ const bytes = utf8ByteLength(text);
89
+ const codePoints = codePointCount(text);
90
+ return {
91
+ utf8Bytes: bytes,
92
+ codePoints,
93
+ graphemes: graphemeCount(text),
94
+ tokens: estimator === void 0 ? estimateFromCounts(bytes, codePoints) : estimator(text),
95
+ degraded: segmenter === void 0
96
+ };
97
+ }
98
+ /**
99
+ * Read one unit from a fresh measurement.
100
+ * @param text - the string to measure.
101
+ * @param unit - the budget unit to read.
102
+ * @param estimator - optional token source; ignored for non-token units.
103
+ * @returns the numeric value in that unit.
104
+ */
105
+ function measureUnit(text, unit, estimator) {
106
+ const metrics = measureText(text, estimator);
107
+ switch (unit) {
108
+ case "utf8Bytes": return metrics.utf8Bytes;
109
+ case "codePoints": return metrics.codePoints;
110
+ case "graphemes": return metrics.graphemes;
111
+ case "tokens": return metrics.tokens.value;
112
+ }
113
+ }
114
+ /**
115
+ * Truncate to a grapheme budget without splitting emoji or combining sequences.
116
+ * The ellipsis counts inside `max`, matching how UI budgets are described.
117
+ * @param text - the string to shorten.
118
+ * @param max - maximum output graphemes, ellipsis included.
119
+ * @param ellipsis - marker appended when shortened; may itself be multi-grapheme.
120
+ * @returns the original text or a grapheme-safe prefix plus marker.
121
+ */
122
+ function truncateGraphemes(text, max, ellipsis = "…") {
123
+ if (!Number.isFinite(max) || max <= 0) return "";
124
+ const limit = Math.floor(max);
125
+ const parts = graphemeParts(text);
126
+ if (parts.length <= limit) return text;
127
+ const marker = graphemeParts(ellipsis);
128
+ if (marker.length >= limit) return marker.slice(0, limit).join("");
129
+ return parts.slice(0, limit - marker.length).join("") + ellipsis;
130
+ }
131
+ //#endregion
132
+ export { measureUnit as a, measureText as i, conservativeTokenEstimator as n, truncateGraphemes as o, graphemeCount as r, utf8ByteLength as s, codePointCount as t };
@@ -63,6 +63,15 @@ export declare const DEFAULT_SKILL_VERSION_KEEP = 20;
63
63
  * standard — deriving the band from the ceiling is exactly what let a 40k
64
64
  * ceiling hide a 99k body without a single signal saying "split me" (V3). */
65
65
  export declare const AUTHORING_SPLIT_LINE_CHARS = 20000;
66
+ /** Display-only truncation caps. They are answers about what a reader gets, never
67
+ * write limits; every one is measured in graphemes and declared in TEXT_BUDGETS.
68
+ * Keeping them here is what lets the route, the activity store, the memory tool
69
+ * and the merge panel stop carrying private copies of the same number. */
70
+ export declare const TEXT_DIFF_MAX_GRAPHEMES = 4000;
71
+ export declare const REVIEW_TEXT_PREVIEW_GRAPHEMES = 2000;
72
+ export declare const MEMORY_ENTRY_PREVIEW_GRAPHEMES = 200;
73
+ export declare const VERSION_BODY_PREVIEW_GRAPHEMES = 20000;
74
+ export declare const MERGE_BODY_PREVIEW_BYTES: number;
66
75
  /** Upstream's conversion basis for CHARACTER LIMITS: 2.75 chars/token, labelled
67
76
  * model-independent in the config template (\`cli-config.yaml.example:538\`), and the
68
77
  * basis behind every quoted token figure there — memory 2200 chars ≈ 800 tokens,
@@ -70,11 +79,13 @@ export declare const AUTHORING_SPLIT_LINE_CHARS = 20000;
70
79
  * Limits are deliberately conservative, so this is the basis a BORROWED LIMIT must
71
80
  * be converted with. */
72
81
  export declare const UPSTREAM_LIMIT_CHARS_PER_TOKEN = 2.75;
73
- /** The platform's own estimate basis: \`CHARS_PER_TOKEN = 4\` in
74
- * \`@deepseek-ai/dsh-token-meter/estimate.ts\` (its comment reads "used until exact
75
- * tokenization is needed"), matching upstream's ESTIMATE-side heuristic — "~4
76
- * chars/token is the usual English heuristic" (\`agent/prompt_builder.py:1179\`).
77
- * Estimates use this; limits use the constant above. */
82
+ /** Default soft body budget in tokens: the upstream 20k-character authoring line
83
+ * converted on the documented 2.75 chars/token basis. Judged as a fixed token
84
+ * budget, not as a per-body character line (see text-metrics). */
85
+ export declare const DEFAULT_SOFT_BODY_TOKENS: number;
86
+ /** Hard storage cap for one skill file, in bytes. The platform token meter's
87
+ * `CHARS_PER_TOKEN = 4` is a session-pressure estimate only; plugin gates use
88
+ * `text-metrics` (see docs/text-budgets.md), not this byte cap, as a token meter. */
78
89
  export declare const MAX_SKILL_FILE_BYTES = 1048576;
79
90
  export declare const DEFAULT_REVIEW_MEMORY_INTERVAL = 10;
80
91
  export declare const DEFAULT_REVIEW_SKILL_INTERVAL = 10;
@@ -102,6 +113,9 @@ export declare const DEFAULT_ARCHIVE_AFTER_DAYS = 90;
102
113
  export declare const SUPPORT_SPRAWL_FILES = 60;
103
114
  export declare const DEFAULT_MEMORY_CHAR_LIMIT = 2200;
104
115
  export declare const DEFAULT_USER_CHAR_LIMIT = 1375;
116
+ /** Token budgets derived from the legacy character limits on the 2.75 basis. */
117
+ export declare const DEFAULT_MEMORY_TOKENS: number;
118
+ export declare const DEFAULT_USER_TOKENS: number;
105
119
  /** Consolidation-failure backoff cap, shared by MemoryStore and memory-files' Config default. */
106
120
  export declare const DEFAULT_CONSOLIDATION_FAILURES = 3;
107
121
  /** F-20 (v18): the authored-body budget and the hard ceiling are the same
@@ -78,6 +78,15 @@ export const DEFAULT_SKILL_VERSION_KEEP = 20;
78
78
  * standard — deriving the band from the ceiling is exactly what let a 40k
79
79
  * ceiling hide a 99k body without a single signal saying "split me" (V3). */
80
80
  export const AUTHORING_SPLIT_LINE_CHARS = 20_000;
81
+ /** Display-only truncation caps. They are answers about what a reader gets, never
82
+ * write limits; every one is measured in graphemes and declared in TEXT_BUDGETS.
83
+ * Keeping them here is what lets the route, the activity store, the memory tool
84
+ * and the merge panel stop carrying private copies of the same number. */
85
+ export const TEXT_DIFF_MAX_GRAPHEMES = 4_000;
86
+ export const REVIEW_TEXT_PREVIEW_GRAPHEMES = 2_000;
87
+ export const MEMORY_ENTRY_PREVIEW_GRAPHEMES = 200;
88
+ export const VERSION_BODY_PREVIEW_GRAPHEMES = 20_000;
89
+ export const MERGE_BODY_PREVIEW_BYTES = 64 * 1024;
81
90
  /** Upstream's conversion basis for CHARACTER LIMITS: 2.75 chars/token, labelled
82
91
  * model-independent in the config template (\`cli-config.yaml.example:538\`), and the
83
92
  * basis behind every quoted token figure there — memory 2200 chars ≈ 800 tokens,
@@ -85,11 +94,13 @@ export const AUTHORING_SPLIT_LINE_CHARS = 20_000;
85
94
  * Limits are deliberately conservative, so this is the basis a BORROWED LIMIT must
86
95
  * be converted with. */
87
96
  export const UPSTREAM_LIMIT_CHARS_PER_TOKEN = 2.75;
88
- /** The platform's own estimate basis: \`CHARS_PER_TOKEN = 4\` in
89
- * \`@deepseek-ai/dsh-token-meter/estimate.ts\` (its comment reads "used until exact
90
- * tokenization is needed"), matching upstream's ESTIMATE-side heuristic — "~4
91
- * chars/token is the usual English heuristic" (\`agent/prompt_builder.py:1179\`).
92
- * Estimates use this; limits use the constant above. */
97
+ /** Default soft body budget in tokens: the upstream 20k-character authoring line
98
+ * converted on the documented 2.75 chars/token basis. Judged as a fixed token
99
+ * budget, not as a per-body character line (see text-metrics). */
100
+ export const DEFAULT_SOFT_BODY_TOKENS = Math.round(AUTHORING_SPLIT_LINE_CHARS / UPSTREAM_LIMIT_CHARS_PER_TOKEN);
101
+ /** Hard storage cap for one skill file, in bytes. The platform token meter's
102
+ * `CHARS_PER_TOKEN = 4` is a session-pressure estimate only; plugin gates use
103
+ * `text-metrics` (see docs/text-budgets.md), not this byte cap, as a token meter. */
93
104
  export const MAX_SKILL_FILE_BYTES = 1_048_576;
94
105
  // ── Cross-package shared tunable defaults ────────────────────────────────────
95
106
  // Fallback defaults when no config override is set. Single-sourced here;
@@ -120,6 +131,9 @@ export const DEFAULT_ARCHIVE_AFTER_DAYS = 90;
120
131
  export const SUPPORT_SPRAWL_FILES = 60;
121
132
  export const DEFAULT_MEMORY_CHAR_LIMIT = 2200;
122
133
  export const DEFAULT_USER_CHAR_LIMIT = 1375;
134
+ /** Token budgets derived from the legacy character limits on the 2.75 basis. */
135
+ export const DEFAULT_MEMORY_TOKENS = Math.round(DEFAULT_MEMORY_CHAR_LIMIT / UPSTREAM_LIMIT_CHARS_PER_TOKEN);
136
+ export const DEFAULT_USER_TOKENS = Math.round(DEFAULT_USER_CHAR_LIMIT / UPSTREAM_LIMIT_CHARS_PER_TOKEN);
123
137
  /** Consolidation-failure backoff cap, shared by MemoryStore and memory-files' Config default. */
124
138
  export const DEFAULT_CONSOLIDATION_FAILURES = 3;
125
139
  /** F-20 (v18): the authored-body budget and the hard ceiling are the same
@@ -11,7 +11,6 @@
11
11
  * Distinct from `signals.ts` — the session-level review signal gate.
12
12
  */
13
13
  import { type CitationReport } from './citations.ts';
14
- import { type BodyCost } from './cost.ts';
15
14
  /** One skill's library state; the assembler (not this module) reads IO. */
16
15
  export interface DriftSkillSnapshot {
17
16
  name: string;
@@ -29,8 +28,6 @@ export interface DriftSkillSnapshot {
29
28
  protected?: string | null | undefined;
30
29
  /** Frontmatter values the strict-YAML platform catalog cannot load (0.3.11). */
31
30
  catalogInvalid?: boolean | undefined;
32
- /** Weighted context cost of the body (design §5.2); undefined = not measured. */
33
- cost?: BodyCost | undefined;
34
31
  /** Citation scan of the body (design §5.2); undefined = not scanned. */
35
32
  citations?: CitationReport | undefined;
36
33
  /** Per-support-file read counts (design §5.5); undefined = no evidence. */
@@ -113,7 +110,7 @@ export declare function duplicateHeadings(body: string): Array<{
113
110
  heading: string;
114
111
  count: number;
115
112
  }>;
116
- /** Physical lines over `max` characters: `{ lineNo, chars }`, 1-based line numbers. */
113
+ /** Physical lines over `max` graphemes: `{ lineNo, chars }`, 1-based line numbers. */
117
114
  export declare function overlongLines(body: string, max?: number): Array<{
118
115
  lineNo: number;
119
116
  chars: number;
@@ -10,11 +10,11 @@
10
10
  *
11
11
  * Distinct from `signals.ts` — the session-level review signal gate.
12
12
  */
13
- import { assessStructureHealth, DEFAULT_HEALTH_THRESHOLDS } from "./skill-health.js";
13
+ import { assessStructureHealth, DEFAULT_HEALTH_THRESHOLDS, softBodyTokenBudget } from "./skill-health.js";
14
14
  import { computeDedupGroups, computePrefixClusters, LOW_QUALITY_THRESHOLD } from "./quality.js";
15
15
  import { AUTHORING_DESCRIPTION_BAR, DEFAULT_STALE_AFTER_DAYS, MAX_SKILL_CONTENT_CHARS } from "./constants.js";
16
16
  import { isFileShapedPath, scanBodyHooks } from "./citations.js";
17
- import { tokenLineFor } from "./cost.js";
17
+ import { graphemeCount } from "./text-metrics.js";
18
18
  /** Physical line length at/above which a body line is reported overlong (011 §4). */
19
19
  export const DRIFT_MAX_LINE_CHARS = 1_500;
20
20
  /** Signal-set version: bump whenever ids/thresholds change (011 §7 version coupling). */
@@ -114,16 +114,17 @@ export function duplicateHeadings(body) {
114
114
  .filter(([, count]) => count > 1)
115
115
  .map(([heading, count]) => ({ heading, count }));
116
116
  }
117
- /** Physical lines over `max` characters: `{ lineNo, chars }`, 1-based line numbers. */
117
+ /** Physical lines over `max` graphemes: `{ lineNo, chars }`, 1-based line numbers. */
118
118
  export function overlongLines(body, max = DRIFT_MAX_LINE_CHARS) {
119
119
  const out = [];
120
120
  const lines = body.split('\n');
121
121
  for (let index = 0; index < lines.length; index += 1) {
122
122
  // S1.8 (v37 P2-3): the CR is a line terminator, not a visible character — a
123
- // 1500-character CRLF line used to report 1501 and send the model after a
123
+ // 1500-grapheme CRLF line used to report 1501 and send the model after a
124
124
  // line that already complies.
125
125
  const raw = lines[index] ?? '';
126
- const length = raw.endsWith('\r') ? raw.length - 1 : raw.length;
126
+ const line = raw.endsWith('\r') ? raw.slice(0, -1) : raw;
127
+ const length = graphemeCount(line);
127
128
  if (length > max)
128
129
  out.push({ lineNo: index + 1, chars: length });
129
130
  }
@@ -189,23 +190,12 @@ export function computeDriftSignals(snapshots) {
189
190
  signals.push(density === null
190
191
  ? sig('stamp_density', 'pass', 'below-min-body')
191
192
  : sig('stamp_density', density >= DEFAULT_HEALTH_THRESHOLDS.stampDensityPerKb ? 'over' : 'pass', `${density.toFixed(2)}/KB`, `${DEFAULT_HEALTH_THRESHOLDS.stampDensityPerKb}/KB`));
192
- // V6: judged on the TOKEN scale. The threshold is the borrowed upstream
193
- // character line, converted per body composition (tokenLineFor), so the textual
194
- // trigger stays "20k characters" while value/threshold/detail all speak tokens.
195
- // Without a cost breakdown the character line decides (never a silent pass).
196
- const cost = snapshot.cost;
197
- const lineTokens = cost === undefined ? null : tokenLineFor(DEFAULT_HEALTH_THRESHOLDS.softBodyChars, cost);
198
- const overLine = cost === undefined || lineTokens === null
199
- ? body.length >= DEFAULT_HEALTH_THRESHOLDS.softBodyChars
200
- : cost.tokens >= lineTokens;
201
- signals.push(sig('body_size', overLine ? 'over' : 'pass', cost === undefined ? `${body.length}` : `${cost.tokens} tokens / ${body.length} chars`, cost === undefined || lineTokens === null
202
- ? `${DEFAULT_HEALTH_THRESHOLDS.softBodyChars}`
203
- : `line=${lineTokens} tokens (${DEFAULT_HEALTH_THRESHOLDS.softBodyChars} chars)`, cost === undefined
204
- ? undefined
205
- // V3: the band is the AUTHORING discipline band (upstream's 20k split
206
- // line, drawn on this body's token scale), and the multiple is what makes
207
- // it actionable — a bare ceiling says nothing about how far past it is.
208
- : `estimate range ${cost.tokensLow}-${cost.tokensHigh} tokens (4 chars/token basis); cjk=${cost.cjk}${lineTokens === null ? '' : `; line=${lineTokens}, body=${(cost.tokens / lineTokens).toFixed(1)}x`}${oversizeSupportNote(snapshot.supportChars)}`));
193
+ // V6: judged on the FIXED token budget. The old per-body token line preserved
194
+ // the character edge; the budget now means the same context cost in every script.
195
+ const bodyTokens = health.dims.bodyTokens;
196
+ const tokenBudget = softBodyTokenBudget(DEFAULT_HEALTH_THRESHOLDS);
197
+ const overLine = bodyTokens >= tokenBudget;
198
+ signals.push(sig('body_size', overLine ? 'over' : 'pass', `${bodyTokens} tokens / ${body.length} chars`, `${tokenBudget} tokens`, `body=${(bodyTokens / tokenBudget).toFixed(1)}x${oversizeSupportNote(snapshot.supportChars)}`));
209
199
  const dupes = duplicateHeadings(body);
210
200
  signals.push(dupes.length === 0
211
201
  ? sig('dup_heading', 'pass', 'none')
@@ -234,12 +224,13 @@ export function computeDriftSignals(snapshots) {
234
224
  ? sig('narrow_name', 'pass', 'none')
235
225
  : sig('narrow_name', 'over', narrow.join(', '), undefined, `name=${snapshot.name}`));
236
226
  const description = snapshot.description;
227
+ const descriptionLength = description === undefined ? 0 : graphemeCount(description);
237
228
  signals.push(description === undefined
238
229
  // C-21 (v10 audit): the threshold renders from the constant like the
239
230
  // assessed branch below — the hardcoded '60' could drift from
240
231
  // AUTHORING_DESCRIPTION_BAR.
241
232
  ? sig('description_chars', 'unknown', 'missing', `${AUTHORING_DESCRIPTION_BAR}`)
242
- : sig('description_chars', description.length > AUTHORING_DESCRIPTION_BAR ? 'over' : 'pass', `${description.length}`, `${AUTHORING_DESCRIPTION_BAR}`));
233
+ : sig('description_chars', descriptionLength > AUTHORING_DESCRIPTION_BAR ? 'over' : 'pass', `${descriptionLength}`, `${AUTHORING_DESCRIPTION_BAR}`));
243
234
  const quality = snapshot.quality;
244
235
  signals.push(quality === null || quality === undefined
245
236
  ? sig('quality_low', 'unknown', 'not-assessed')
@@ -1,5 +1,6 @@
1
1
  import { dirname, join } from 'node:path';
2
2
  import { DEFAULT_SKILL_LIMITS } from "./limits.js";
3
+ import { measureUnit } from "./text-metrics.js";
3
4
  import { contentHash } from "./mutations.js";
4
5
  import { parseFrontmatter } from "./frontmatter.js";
5
6
  import { isPresent } from "./probe.js";
@@ -78,7 +79,7 @@ export async function buildExtractPlanFromLibrary(library, input) {
78
79
  return { ok: false, message: plan.message + candidateHint };
79
80
  return { ok: true, plan: plan.plan, candidates: lookup.candidates };
80
81
  }
81
- if (targetMd.length > DEFAULT_SKILL_LIMITS.maxSkillContentChars)
82
+ if (measureUnit(targetMd, 'codePoints') > DEFAULT_SKILL_LIMITS.maxSkillContentChars)
82
83
  return { ok: false, message: '目标技能「' + target + '」已超过 ' + DEFAULT_SKILL_LIMITS.maxSkillContentChars + ' 字符,拒绝继续提取。' };
83
84
  const candidate = findOwnerCandidate(lookup, target);
84
85
  if (candidate === undefined)
@@ -152,7 +153,7 @@ export async function buildExtractPlanFromLibrary(library, input) {
152
153
  });
153
154
  if (!plan.ok)
154
155
  return { ok: false, message: plan.message };
155
- const projectedChars = targetMd.length + plan.plan.parts.reduce((sum, part) => sum + part.movedText.length + 2, 0);
156
+ const projectedChars = measureUnit(targetMd, 'codePoints') + plan.plan.parts.reduce((sum, part) => sum + measureUnit(part.movedText, 'codePoints') + 2, 0);
156
157
  if (projectedChars > DEFAULT_SKILL_LIMITS.maxSkillContentChars) {
157
158
  return { ok: false, message: '目标「' + target + '」投影后约 ' + projectedChars + ' 字符,超过 ' + DEFAULT_SKILL_LIMITS.maxSkillContentChars + ' 上限;拒绝提取。' };
158
159
  }
@@ -24,6 +24,7 @@ import { parse as parseYaml } from 'yaml';
24
24
  import { AUTHORING_DESCRIPTION_BAR, CONTENT_SPLIT_HINT, SKILL_NAME_RE } from "./constants.js";
25
25
  import { isRecord } from "./guards.js";
26
26
  import { DEFAULT_SKILL_LIMITS } from "./limits.js";
27
+ import { graphemeCount, measureUnit, truncateGraphemes } from "./text-metrics.js";
27
28
  /**
28
29
  * Shared frontmatter block detection (P3-3 single owner): opening line `---`
29
30
  * and closing line exactly `---`. Used by `parseFrontmatter`,
@@ -546,14 +547,14 @@ export function skillMdOnDisk(content) {
546
547
  }
547
548
  /** Whether `content` would exceed `limit` once written. */
548
549
  export function exceedsContentLimit(content, limit) {
549
- return skillMdOnDisk(content).length > limit;
550
+ return measureUnit(skillMdOnDisk(content), 'codePoints') > limit;
550
551
  }
551
552
  /** S1.2: the repair path — a write that makes an already-over-limit file smaller.
552
553
  * Only a NET SHRINK is exempt; an equal or larger write stays refused. */
553
554
  export function shrinksOverLimit(next, current, limit) {
554
555
  if (current === null || current === undefined || !exceedsContentLimit(current, limit))
555
556
  return false;
556
- return skillMdOnDisk(next).length < skillMdOnDisk(current).length;
557
+ return measureUnit(skillMdOnDisk(next), 'codePoints') < measureUnit(skillMdOnDisk(current), 'codePoints');
557
558
  }
558
559
  /**
559
560
  * Synthesize a missing SKILL.md header at the write boundary.
@@ -576,7 +577,9 @@ export function ensureSkillFrontmatter(content, name, description) {
576
577
  const heading = /^#{1,6}\s+(.+?)\s*$/m.exec(body)?.[1];
577
578
  const firstLine = body.split(/\r?\n/).map(line => line.trim()).find(line => line !== '' && !line.startsWith('#')) ?? '';
578
579
  const source = (description?.trim() || heading || firstLine || name).replace(/\s+/g, ' ').trim();
579
- const clipped = source.length > AUTHORING_DESCRIPTION_BAR - 2 ? source.slice(0, AUTHORING_DESCRIPTION_BAR - 3) + '…' : source;
580
+ const clipped = graphemeCount(source) > AUTHORING_DESCRIPTION_BAR - 2
581
+ ? truncateGraphemes(source, AUTHORING_DESCRIPTION_BAR - 2)
582
+ : source;
580
583
  const summary = /[.。!?!?]$/.test(clipped) ? clipped : clipped + '.';
581
584
  const encoded = yamlPlainScalarNeedsQuotes(summary) ? JSON.stringify(summary) : summary;
582
585
  const header = ['---', `name: ${name}`, `description: ${encoded}`, 'version: 0.1.0', 'author: Hermes', '---', ''].join('\n');
@@ -613,7 +616,7 @@ current) {
613
616
  if (!parsed.frontmatter.description)
614
617
  return 'Frontmatter 必须包含 description 字段。';
615
618
  const description = parsed.frontmatter.description;
616
- if (description.length > limits.maxDescriptionLength)
619
+ if (graphemeCount(description) > limits.maxDescriptionLength)
617
620
  return `description 超过 ${limits.maxDescriptionLength} 个字符。`;
618
621
  // S1.2: the limit is judged on the bytes that will land on disk, and a NET
619
622
  // SHRINK of an already-over-limit file is allowed (the repair path).
@@ -631,15 +634,16 @@ current) {
631
634
  */
632
635
  export function authoringFeedback(frontmatter) {
633
636
  const description = frontmatter.description ?? '';
634
- const over60 = description.length > AUTHORING_DESCRIPTION_BAR;
637
+ const descriptionLength = graphemeCount(description);
638
+ const over60 = descriptionLength > AUTHORING_DESCRIPTION_BAR;
635
639
  const hasColon = description.includes(':');
636
640
  const lines = [];
637
641
  lines.push(over60
638
- ? `描述为 ${description.length}/60 个字符 —— 超过 60 字符的作者规范上限(Hermes 标准;技能目录会按平台配置的上限截断)。`
639
- : `描述为 ${description.length}/60 个字符 —— 在作者规范上限之内。`);
642
+ ? `描述为 ${descriptionLength}/60 个字符 —— 超过 60 字符的作者规范上限(Hermes 标准;技能目录会按平台配置的上限截断)。`
643
+ : `描述为 ${descriptionLength}/60 个字符 —— 在作者规范上限之内。`);
640
644
  if (hasColon)
641
645
  lines.push('描述里含冒号 —— 请用双引号把整个取值包起来。');
642
- return { descriptionChars: description.length, over60, hasColon, lines };
646
+ return { descriptionChars: descriptionLength, over60, hasColon, lines };
643
647
  }
644
648
  /** A1-15 (v18) / P2-2 (v19): the io layer marks an error `committed: true` when
645
649
  * the rename landed and only the directory fsync failed. Every single-file
@@ -44,7 +44,8 @@ export * from './owner-resolver.ts';
44
44
  export * from './proposal-view.ts';
45
45
  export * from './proposal-report.ts';
46
46
  export * from './external-support.ts';
47
- export * from './cost.ts';
47
+ export * from './text-metrics.ts';
48
+ export * from './text-budgets.ts';
48
49
  export * from './health-baseline.ts';
49
50
  export * from './curator.ts';
50
51
  export * from './evolution-events.ts';
@@ -45,7 +45,8 @@ export * from "./owner-resolver.js";
45
45
  export * from "./proposal-view.js";
46
46
  export * from "./proposal-report.js";
47
47
  export * from "./external-support.js";
48
- export * from "./cost.js";
48
+ export * from "./text-metrics.js";
49
+ export * from "./text-budgets.js";
49
50
  export * from "./health-baseline.js";
50
51
  export * from "./curator.js";
51
52
  export * from "./evolution-events.js";
@@ -18,16 +18,26 @@ export interface MemoryApplyResult {
18
18
  ok: boolean;
19
19
  message: string;
20
20
  entries: string[];
21
+ /** Raw UTF-16 code units; the display/compat fact, never the token judgement. */
21
22
  chars: number;
23
+ /** Active limit: tokens when token mode is configured, otherwise the legacy char limit. */
22
24
  limit: number;
25
+ /** Estimated tokens for the same entries; present on public add/applyBatch results. */
26
+ tokens?: number;
27
+ /** Token budget when token mode is configured; absent in legacy char mode. */
28
+ tokenLimit?: number;
23
29
  }
24
30
  export declare function memoryRoot(env?: NodeJS.ProcessEnv): string;
25
31
  export interface MemoryFence {
26
32
  run<T>(body: () => Promise<T>): Promise<T>;
27
33
  }
28
34
  export interface MemoryStoreOptions {
35
+ /** Legacy character budgets; converted once when no token budget is supplied. */
29
36
  memoryCharLimit?: number;
30
37
  userCharLimit?: number;
38
+ /** Token budgets; the judged unit when present. */
39
+ memoryTokenLimit?: number;
40
+ userTokenLimit?: number;
31
41
  addDatePrefix?: boolean;
32
42
  root?: string;
33
43
  maxConsolidationFailures?: number;
@@ -44,6 +54,8 @@ export type { EvolutionIoLike };
44
54
  export declare class MemoryStore {
45
55
  readonly memoryLimit: number;
46
56
  readonly userLimit: number;
57
+ private readonly memoryTokenLimit;
58
+ private readonly userTokenLimit;
47
59
  readonly addDatePrefix: boolean;
48
60
  readonly root: string;
49
61
  private readonly maxFailures;
@@ -67,15 +79,29 @@ export declare class MemoryStore {
67
79
  * label (scanMemoryThreats already embeds it) plus the self-heal hint. */
68
80
  private memoryThreatBlock;
69
81
  limitFor(target: MemoryTarget): number;
82
+ /** Token budget when the target opted into token mode; undefined keeps legacy chars. */
83
+ private tokenLimitFor;
84
+ /** The value the active gate compares: tokens in token mode, UTF-16 chars otherwise. */
85
+ private judgedValue;
86
+ /** Unit noun for model-facing messages; legacy mode keeps its old wording. */
87
+ private unitFor;
88
+ /**
89
+ * Byte ceiling for the oversized-read guard. It is NOT the token budget:
90
+ * a token cannot be compared to bytes. Token mode uses a conservative byte
91
+ * envelope so a canonical English/CJK file is never mistaken for corruption.
92
+ */
93
+ private byteGuardFor;
94
+ /** Add the public dual-unit facts to one internal result. */
95
+ private decorateResult;
70
96
  /** P2-1 (v18): the generated date prefix participates in duplicate detection
71
97
  * only when THIS store writes it. With addDatePrefix=false a fact's own
72
98
  * leading `## YYYY-MM-DD\n` is content, not a generated prefix. */
73
99
  private dedupeKey;
74
100
  /**
75
- * Read-guard probe: `{ size, limit }` when the on-disk file exceeds
76
- * `limit * READ_GUARD_FACTOR` bytes, `null` when it is absent, unknown
77
- * (backend without a size probe), under the bound, or the target has no
78
- * limit configured.
101
+ * Read-guard probe: `{ size, byteLimit }` when the on-disk file exceeds the
102
+ * target's byte ceiling, `null` when it is absent, unknown, under the bound,
103
+ * or the target has no limit configured. The ceiling is bytes, never the
104
+ * token/char budget itself.
79
105
  */
80
106
  private oversizedFile;
81
107
  read(target: MemoryTarget): Promise<string[]>;
@@ -83,8 +109,8 @@ export declare class MemoryStore {
83
109
  private failure;
84
110
  /**
85
111
  * StorageHint percentage must clamp at 100 like the render header: a drifted
86
- * entry can push chars past the limit, and "Storage at 125%" contradicts the
87
- * clamped usage indicator.
112
+ * entry can push usage past the limit, and "Storage at 125%" contradicts the
113
+ * clamped usage indicator. The percentage is computed in the ACTIVE unit.
88
114
  */
89
115
  private storageHint;
90
116
  /**