@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
@@ -1,7 +1,7 @@
1
1
  import { c as transactIo } from "./io-GxghO3Ip.js";
2
- import { J as UPSTREAM_LIMIT_CHARS_PER_TOKEN, j as DEFAULT_THREAT_MAX_SCAN_CHARS, l as AUTHORING_SPLIT_LINE_CHARS } from "./limits-TD4Pv92Q.js";
3
- import { O as collectReadSkillNames, R as supportFileReadFromPath, k as collectReadSupportFiles, l as sessionReadNames, o as isProjectableSession, v as DEFAULT_SUPPORT_READ_TOOL_NAMES } from "./session-projection-ByNxQi9O.js";
4
- import { V as skillMdOnDisk } from "./usage-B1qveKi9.js";
2
+ import { N as DEFAULT_THREAT_MAX_SCAN_CHARS, O as DEFAULT_SOFT_BODY_TOKENS, Z as UPSTREAM_LIMIT_CHARS_PER_TOKEN } from "./limits-DBg3UMkw.js";
3
+ import { O as collectReadSkillNames, R as supportFileReadFromPath, k as collectReadSupportFiles, l as sessionReadNames, o as isProjectableSession, v as DEFAULT_SUPPORT_READ_TOOL_NAMES } from "./session-projection-CbIKvDfJ.js";
4
+ import { a as measureUnit, i as measureText } from "./text-metrics-CyJhxWBs.js";
5
5
  import { t as clampedNumber } from "./numeric-Dc53KQoe.js";
6
6
  import { AsyncLocalStorage } from "node:async_hooks";
7
7
  import { dirname, join } from "node:path";
@@ -135,71 +135,6 @@ function filterUnreadSkillOps(ops, readNames) {
135
135
  return dropped;
136
136
  }
137
137
  //#endregion
138
- //#region lib/types/cost.js
139
- /**
140
- * Context-cost accounting for skill bodies (design §5.2).
141
- *
142
- * A raw character count is a poor budget: the same 100k characters cost very
143
- * different amounts of context in Chinese-heavy prose and in English. The
144
- * weighted unit makes the two comparable, and the token range exists only to
145
- * make the load cost visible next to the character count — it is an ESTIMATE,
146
- * never a measurement.
147
- *
148
- * Accounting basis: the ON-DISK form (`skillMdOnDisk()`, the same view the
149
- * write limit uses), so a body that is exactly at the limit cannot read as
150
- * over-limit here and pass there (the v37 P2-1 deadlock class).
151
- */
152
- /** Token weight of one CJK / kana / full-width code unit on the LIMIT basis —
153
- * upstream's model-independent conversion is 2.75 chars/token for prose, and CJK
154
- * prose is ~1 token per character (the conservative end of the 0.6–1.0 range the
155
- * estimate side reports). Thresholds are compared on THIS basis so a borrowed
156
- * character line keeps its meaning; the estimate range below reports the spread. */
157
- const TOKEN_CJK_WEIGHT = 1;
158
- /** Token weight of one non-CJK code unit on the LIMIT basis (1 / 2.75 ≈ 0.364). */
159
- const TOKEN_ASCII_WEIGHT = 1 / UPSTREAM_LIMIT_CHARS_PER_TOKEN;
160
- /** Token-per-unit bounds of the estimate range (CJK: 0.6–1.0, non-CJK: 1/4–1/3).
161
- * The range is the 4-chars/token estimate family, so on ASCII-heavy bodies the
162
- * LIMIT-basis `tokens` point can sit above `tokensHigh` (1/2.75 > 1/3): the two
163
- * answer different questions and are never nested by construction. */
164
- const COST_CJK_TOKEN_LOW = .6;
165
- const COST_CJK_TOKEN_HIGH = 1;
166
- const COST_ASCII_TOKEN_LOW = .25;
167
- const COST_ASCII_TOKEN_HIGH = 1 / 3;
168
- /** The token line a borrowed CHARACTER threshold draws for ONE body: 20k characters
169
- * of THIS composition, expressed in the same tokens `bodyCost` counts. Comparing
170
- * `tokens` against this line is deliberately equivalent to "chars >= line" — that
171
- * equivalence is what keeps a borrowed line's textual effect identical — while the
172
- * judgment itself, and every number reported, stays on the token scale.
173
- * @param lineChars - the borrowed character line (whole-body characters).
174
- * @param cost - the body's own cost breakdown.
175
- * @returns the equivalent token line (0 when the body is empty). */
176
- function tokenLineFor(lineChars, cost) {
177
- if (cost.chars === 0) return 0;
178
- return Math.round(lineChars * cost.tokens / cost.chars);
179
- }
180
- /** CJK ideographs, kana, full-width forms and CJK punctuation. */
181
- const CJK_RE = /[\u3000-\u303f\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff\uff00-\uffef]/g;
182
- /**
183
- * Cost of one skill body.
184
- * @param content - the body text as written (trailing whitespace is normalized
185
- * away by the on-disk accounting, so callers need not pre-trim).
186
- * @returns the cost breakdown; an empty body answers all-zero.
187
- */
188
- function bodyCost(content) {
189
- const onDisk = skillMdOnDisk(content);
190
- const cjk = [...onDisk.matchAll(CJK_RE)].length;
191
- const chars = onDisk.length;
192
- const ascii = chars - cjk;
193
- return {
194
- chars,
195
- cjk,
196
- ascii,
197
- tokens: Math.round(cjk * 1 + ascii * TOKEN_ASCII_WEIGHT),
198
- tokensLow: Math.round(cjk * COST_CJK_TOKEN_LOW + ascii * COST_ASCII_TOKEN_LOW),
199
- tokensHigh: Math.round(cjk * 1 + ascii * COST_ASCII_TOKEN_HIGH)
200
- };
201
- }
202
- //#endregion
203
138
  //#region lib/types/skill-lint.js
204
139
  const msg = (parts) => parts.map((p) => typeof p === "string" ? p : String(p)).join("");
205
140
  /** One rule yields AT MOST one finding (contract §3). `body-oversize-2x` is the only rule whose
@@ -224,8 +159,8 @@ const RULES = [
224
159
  message: msg([
225
160
  facts.skillName,
226
161
  ": body is at or past twice the soft line (",
227
- facts.softLineChars,
228
- " chars); keeping the current skill is valid"
162
+ facts.softLineTokens,
163
+ " tokens); keeping the current skill is valid"
229
164
  ]),
230
165
  count: 1
231
166
  } : null
@@ -239,8 +174,8 @@ const RULES = [
239
174
  message: msg([
240
175
  facts.skillName,
241
176
  ": body is at or above the soft line (",
242
- facts.softLineChars,
243
- " chars); keep is valid — size alone does not require a split"
177
+ facts.softLineTokens,
178
+ " tokens); keep is valid — size alone does not require a split"
244
179
  ]),
245
180
  count: 1
246
181
  } : null
@@ -268,14 +203,14 @@ const RULES = [
268
203
  {
269
204
  id: "body-without-support",
270
205
  severity: "warn",
271
- run: (facts) => facts.dims.supportGroups === 0 && facts.dims.bodyChars !== null && facts.dims.bodyChars >= facts.softLineChars / 2 ? {
206
+ run: (facts) => facts.dims.supportGroups === 0 && facts.dims.bodyTokens !== null && facts.dims.bodyTokens >= facts.softLineTokens / 2 ? {
272
207
  severity: "warn",
273
208
  rule: "body-without-support",
274
209
  message: msg([
275
210
  facts.skillName,
276
211
  ": large body (",
277
- facts.dims.bodyChars,
278
- " chars) with NO support files"
212
+ facts.dims.bodyTokens,
213
+ " tokens) with NO support files"
279
214
  ]),
280
215
  count: 1
281
216
  } : null
@@ -365,6 +300,119 @@ function diffFindings(before, after) {
365
300
  };
366
301
  }
367
302
  //#endregion
303
+ //#region lib/types/skill-health.js
304
+ /**
305
+ * Skill structure-health domain (rc.73 A1, 008 design): a SECOND assessment
306
+ * dimension beside the six-factor usage quality — document hygiene, consumed
307
+ * by the curator health view and the `/evolution skills health` command.
308
+ *
309
+ * PURE and DERIVED: nothing is persisted; every assessment is computed from
310
+ * file facts at read time. The judgment split follows the original's
311
+ * boundary/治理 layering — deterministic signals here, refinement proposals
312
+ * stay in the review/curator judgment layer. Never become a 7th factor of
313
+ * `computeQualityScores` (different dimension, different consumers).
314
+ */
315
+ const DEFAULT_HEALTH_THRESHOLDS = {
316
+ softBodyTokens: DEFAULT_SOFT_BODY_TOKENS,
317
+ stampDensityPerKb: 2,
318
+ churnMinPatches: 20,
319
+ hardCapMinHits: 3
320
+ };
321
+ /** Resolve the judged soft-body token budget, accepting the legacy character line. */
322
+ function softBodyTokenBudget(thresholds) {
323
+ if (thresholds.softBodyTokens !== void 0) return thresholds.softBodyTokens;
324
+ if (thresholds.softBodyChars !== void 0) return Math.round(thresholds.softBodyChars / UPSTREAM_LIMIT_CHARS_PER_TOKEN);
325
+ return DEFAULT_SOFT_BODY_TOKENS;
326
+ }
327
+ /**
328
+ * Stamp regex shared by health assessment and the maintenance probe (single
329
+ * source, 011). Two refinements over the naive form (F-320): the hex branch
330
+ * requires at least one digit so coincidental all-letter English words
331
+ * (`defaced`, `feedback`) are not counted as commit shas; the ISO branch
332
+ * accepts a UTC `Z`, a numeric UTC offset (`+08:00`), or no timezone at all —
333
+ * non-UTC timestamps used to escape detection (log-like content missed).
334
+ *
335
+ * Known boundary, recorded not fixed (C-22, v10 audit): the hex branch also
336
+ * matches 7-40 char PURE-DIGIT strings (order numbers etc.), so stamp density
337
+ * can be over-reported for such content. The misjudgment direction is "extra
338
+ * stamp hits" only — never a miss — and no real incident exists; revisit only
339
+ * if curator decisions are actually distorted (v10 deferral ledger).
340
+ */
341
+ const HEALTH_STAMP_RE = new RegExp(String.raw`\brc\.\d+\b|\b(?=[0-9a-f]{7,40}\b)[0-9a-f]*[0-9][0-9a-f]*\b|\b\d{4}-\d{2}-\d{2}(?:T[0-9:.]+(?:Z|[+-]\d{2}:?\d{2})?)?\b`, "g");
342
+ /**
343
+ * Bodies below this size skip stamp-density assessment: a few dates or shas
344
+ * in a short body are ordinary documentation, not log-like content. With the
345
+ * 1KB density floor a 3-date sentence in a small skill measured 3.0/KB and
346
+ * warned on a perfectly healthy body (audit 2026-08-31 X1).
347
+ */
348
+ const MIN_STAMP_BODY_CHARS = 2e3;
349
+ /**
350
+ * The findings for ONE body, computed by the engine that owns the judgement (G4).
351
+ *
352
+ * Deliberately a thin call into `assessStructureHealth`: a later consumer (the write receipt) needs
353
+ * findings for a body it is about to store, and re-deriving the facts anywhere else would be a
354
+ * SECOND judgement — the token-scale line, the /1024 stamp density and the soft/2 support threshold
355
+ * all live in one place and must stay there.
356
+ * @param skillName - the skill the body belongs to (used in messages).
357
+ * @param content - the WHOLE SKILL.md text, frontmatter included (the engine's own convention).
358
+ * @param supportGroups - non-empty support dirs; pass the real count, never a guess.
359
+ * @param thresholds - the configured thresholds; defaults to the shipped ones.
360
+ * @returns the findings, in rule order.
361
+ */
362
+ function lintBody(skillName, content, supportGroups, thresholds = DEFAULT_HEALTH_THRESHOLDS) {
363
+ return assessStructureHealth({
364
+ skillName,
365
+ bodyChars: content.length,
366
+ bodyText: content,
367
+ supportGroups
368
+ }, thresholds).findings;
369
+ }
370
+ function assessStructureHealth(snapshot, thresholds = DEFAULT_HEALTH_THRESHOLDS) {
371
+ const dims = {
372
+ bodyChars: snapshot.bodyChars,
373
+ bodyTokens: Math.round(snapshot.bodyChars / UPSTREAM_LIMIT_CHARS_PER_TOKEN),
374
+ stampDensityPerKb: null,
375
+ stampHits: null,
376
+ supportGroups: snapshot.supportGroups,
377
+ supportFiles: snapshot.supportFiles ?? null,
378
+ churnPatches: null,
379
+ churnReads: null,
380
+ hardCapHits: snapshot.hardCapHits ?? null
381
+ };
382
+ const text = snapshot.bodyText;
383
+ const hasText = typeof text === "string" && text.length > 0;
384
+ const tokenBudget = softBodyTokenBudget(thresholds);
385
+ dims.bodyTokens = hasText ? measureText(text).tokens.value : Math.round(snapshot.bodyChars / UPSTREAM_LIMIT_CHARS_PER_TOKEN);
386
+ const overLine = dims.bodyTokens >= tokenBudget;
387
+ const overTwice = dims.bodyTokens >= tokenBudget * 2;
388
+ if (snapshot.bodyText && measureUnit(snapshot.bodyText, "codePoints") >= 2e3) {
389
+ const kb = Math.max(1, measureUnit(snapshot.bodyText, "codePoints") / 1024);
390
+ const stamps = (snapshot.bodyText.match(HEALTH_STAMP_RE) ?? []).length;
391
+ dims.stampDensityPerKb = stamps / kb;
392
+ dims.stampHits = stamps;
393
+ }
394
+ if (snapshot.patchCount !== void 0 && snapshot.readCount !== void 0) {
395
+ dims.churnPatches = snapshot.patchCount;
396
+ dims.churnReads = snapshot.readCount;
397
+ }
398
+ const findings = lintSkill({
399
+ skillName: snapshot.skillName,
400
+ dims,
401
+ softLineTokens: tokenBudget,
402
+ overSoftLine: overLine,
403
+ overTwiceSoftLine: overTwice,
404
+ stampLimitPerKb: thresholds.stampDensityPerKb,
405
+ churnMinPatches: thresholds.churnMinPatches,
406
+ hardCapMinHits: thresholds.hardCapMinHits,
407
+ readable: true
408
+ });
409
+ return {
410
+ verdict: findings.some((f) => f.rule === "body-oversize-2x") ? "needs-restructure" : findings.length > 0 ? "warn" : "healthy",
411
+ dims,
412
+ findings
413
+ };
414
+ }
415
+ //#endregion
368
416
  //#region lib/types/evolution-events.js
369
417
  /**
370
418
  * Self-evolution event log (rc.68): an append-only sidecar under
@@ -1308,111 +1356,4 @@ function recordReviewRead(name) {
1308
1356
  context.reads.add(name.trim());
1309
1357
  }
1310
1358
  //#endregion
1311
- //#region lib/types/skill-health.js
1312
- /**
1313
- * Skill structure-health domain (rc.73 A1, 008 design): a SECOND assessment
1314
- * dimension beside the six-factor usage quality — document hygiene, consumed
1315
- * by the curator health view and the `/evolution skills health` command.
1316
- *
1317
- * PURE and DERIVED: nothing is persisted; every assessment is computed from
1318
- * file facts at read time. The judgment split follows the original's
1319
- * boundary/治理 layering — deterministic signals here, refinement proposals
1320
- * stay in the review/curator judgment layer. Never become a 7th factor of
1321
- * `computeQualityScores` (different dimension, different consumers).
1322
- */
1323
- const DEFAULT_HEALTH_THRESHOLDS = {
1324
- softBodyChars: AUTHORING_SPLIT_LINE_CHARS,
1325
- stampDensityPerKb: 2,
1326
- churnMinPatches: 20,
1327
- hardCapMinHits: 3
1328
- };
1329
- /**
1330
- * Stamp regex shared by health assessment and the maintenance probe (single
1331
- * source, 011). Two refinements over the naive form (F-320): the hex branch
1332
- * requires at least one digit so coincidental all-letter English words
1333
- * (`defaced`, `feedback`) are not counted as commit shas; the ISO branch
1334
- * accepts a UTC `Z`, a numeric UTC offset (`+08:00`), or no timezone at all —
1335
- * non-UTC timestamps used to escape detection (log-like content missed).
1336
- *
1337
- * Known boundary, recorded not fixed (C-22, v10 audit): the hex branch also
1338
- * matches 7-40 char PURE-DIGIT strings (order numbers etc.), so stamp density
1339
- * can be over-reported for such content. The misjudgment direction is "extra
1340
- * stamp hits" only — never a miss — and no real incident exists; revisit only
1341
- * if curator decisions are actually distorted (v10 deferral ledger).
1342
- */
1343
- const HEALTH_STAMP_RE = new RegExp(String.raw`\brc\.\d+\b|\b(?=[0-9a-f]{7,40}\b)[0-9a-f]*[0-9][0-9a-f]*\b|\b\d{4}-\d{2}-\d{2}(?:T[0-9:.]+(?:Z|[+-]\d{2}:?\d{2})?)?\b`, "g");
1344
- /**
1345
- * Bodies below this size skip stamp-density assessment: a few dates or shas
1346
- * in a short body are ordinary documentation, not log-like content. With the
1347
- * 1KB density floor a 3-date sentence in a small skill measured 3.0/KB and
1348
- * warned on a perfectly healthy body (audit 2026-08-31 X1).
1349
- */
1350
- const MIN_STAMP_BODY_CHARS = 2e3;
1351
- /**
1352
- * The findings for ONE body, computed by the engine that owns the judgement (G4).
1353
- *
1354
- * Deliberately a thin call into `assessStructureHealth`: a later consumer (the write receipt) needs
1355
- * findings for a body it is about to store, and re-deriving the facts anywhere else would be a
1356
- * SECOND judgement — the token-scale line, the /1024 stamp density and the soft/2 support threshold
1357
- * all live in one place and must stay there.
1358
- * @param skillName - the skill the body belongs to (used in messages).
1359
- * @param content - the WHOLE SKILL.md text, frontmatter included (the engine's own convention).
1360
- * @param supportGroups - non-empty support dirs; pass the real count, never a guess.
1361
- * @param thresholds - the configured thresholds; defaults to the shipped ones.
1362
- * @returns the findings, in rule order.
1363
- */
1364
- function lintBody(skillName, content, supportGroups, thresholds = DEFAULT_HEALTH_THRESHOLDS) {
1365
- return assessStructureHealth({
1366
- skillName,
1367
- bodyChars: content.length,
1368
- bodyText: content,
1369
- supportGroups
1370
- }, thresholds).findings;
1371
- }
1372
- function assessStructureHealth(snapshot, thresholds = DEFAULT_HEALTH_THRESHOLDS) {
1373
- const dims = {
1374
- bodyChars: snapshot.bodyChars,
1375
- bodyTokens: Math.round(snapshot.bodyChars / UPSTREAM_LIMIT_CHARS_PER_TOKEN),
1376
- stampDensityPerKb: null,
1377
- stampHits: null,
1378
- supportGroups: snapshot.supportGroups,
1379
- supportFiles: snapshot.supportFiles ?? null,
1380
- churnPatches: null,
1381
- churnReads: null,
1382
- hardCapHits: snapshot.hardCapHits ?? null
1383
- };
1384
- const text = snapshot.bodyText;
1385
- const cost = typeof text === "string" && text.length > 0 ? bodyCost(text) : null;
1386
- const lineTokens = cost === null ? null : tokenLineFor(thresholds.softBodyChars, cost);
1387
- dims.bodyTokens = cost === null ? Math.round(snapshot.bodyChars / UPSTREAM_LIMIT_CHARS_PER_TOKEN) : cost.tokens;
1388
- const overLine = cost === null || lineTokens === null ? snapshot.bodyChars >= thresholds.softBodyChars : cost.tokens >= lineTokens;
1389
- const overTwice = cost === null || lineTokens === null ? snapshot.bodyChars >= thresholds.softBodyChars * 2 : cost.tokens >= lineTokens * 2;
1390
- if (snapshot.bodyText && snapshot.bodyChars >= 2e3) {
1391
- const kb = Math.max(1, snapshot.bodyChars / 1024);
1392
- const stamps = (snapshot.bodyText.match(HEALTH_STAMP_RE) ?? []).length;
1393
- dims.stampDensityPerKb = stamps / kb;
1394
- dims.stampHits = stamps;
1395
- }
1396
- if (snapshot.patchCount !== void 0 && snapshot.readCount !== void 0) {
1397
- dims.churnPatches = snapshot.patchCount;
1398
- dims.churnReads = snapshot.readCount;
1399
- }
1400
- const findings = lintSkill({
1401
- skillName: snapshot.skillName,
1402
- dims,
1403
- softLineChars: thresholds.softBodyChars,
1404
- overSoftLine: overLine,
1405
- overTwiceSoftLine: overTwice,
1406
- stampLimitPerKb: thresholds.stampDensityPerKb,
1407
- churnMinPatches: thresholds.churnMinPatches,
1408
- hardCapMinHits: thresholds.hardCapMinHits,
1409
- readable: true
1410
- });
1411
- return {
1412
- verdict: findings.some((f) => f.rule === "body-oversize-2x") ? "needs-restructure" : findings.length > 0 ? "warn" : "healthy",
1413
- dims,
1414
- findings
1415
- };
1416
- }
1417
- //#endregion
1418
- export { DEFAULT_WRITE_CONFIRM_TIMEOUT_SECONDS as $, evolutionEventPayloadIssue as A, COST_ASCII_TOKEN_LOW as B, trimPatternBoundaries as C, EVENT_LOG_VERSION as D, EVENT_LOG_ROTATE_AT as E, retainEventArchives as F, bodyCost as G, COST_CJK_TOKEN_LOW as H, RULES as I, filterUnreadSkillOps as J, tokenLineFor as K, diffFindings as L, parseEvolutionEvents as M, readEvolutionEvents as N, appendEvolutionEvent as O, readEvolutionTimeline as P, DEFAULT_WRITE_CONFIRM_MODE as Q, lintSkill as R, fuzzyPatch as S, EVENT_LOG_RETAIN_ARCHIVES as T, TOKEN_ASCII_WEIGHT as U, COST_CJK_TOKEN_HIGH as V, TOKEN_CJK_WEIGHT as W, sessionReadSkillNames as X, isUnreadWrite as Y, sessionReadSupportFiles as Z, scanMemoryThreats as _, lintBody as a, FUZZY_MAX_PATTERN_CHARS as b, withReviewContext as c, markReviewChannel as d, authorityFrom as et, sweepReviewChannelSessions as f, scanContentThreats as g, evaluateThreat as h, assessStructureHealth as i, listEventArchives as j, eventsFile as k, clearReviewChannel as l, THREAT_EXEMPTION_HINT as m, HEALTH_STAMP_RE as n, currentReviewContext as o, PATTERN_OVERLAP as p, READ_REQUIRED_ACTIONS as q, MIN_STAMP_BODY_CHARS as r, recordReviewRead as s, DEFAULT_HEALTH_THRESHOLDS as t, isReviewChannelSession as u, scanThreats as v, EVENT_ARCHIVE_PREFIX as w, FUZZY_MAX_WORK as x, makeSerialQueue as y, COST_ASCII_TOKEN_HIGH as z };
1359
+ export { retainEventArchives as A, READ_REQUIRED_ACTIONS as B, appendEvolutionEvent as C, parseEvolutionEvents as D, listEventArchives as E, lintBody as F, DEFAULT_WRITE_CONFIRM_MODE as G, isUnreadWrite as H, softBodyTokenBudget as I, DEFAULT_WRITE_CONFIRM_TIMEOUT_SECONDS as K, RULES as L, HEALTH_STAMP_RE as M, MIN_STAMP_BODY_CHARS as N, readEvolutionEvents as O, assessStructureHealth as P, diffFindings as R, EVENT_LOG_VERSION as S, evolutionEventPayloadIssue as T, sessionReadSkillNames as U, filterUnreadSkillOps as V, sessionReadSupportFiles as W, fuzzyPatch as _, isReviewChannelSession as a, EVENT_LOG_RETAIN_ARCHIVES as b, PATTERN_OVERLAP as c, scanContentThreats as d, scanMemoryThreats as f, FUZZY_MAX_WORK as g, FUZZY_MAX_PATTERN_CHARS as h, clearReviewChannel as i, DEFAULT_HEALTH_THRESHOLDS as j, readEvolutionTimeline as k, THREAT_EXEMPTION_HINT as l, makeSerialQueue as m, recordReviewRead as n, markReviewChannel as o, scanThreats as p, authorityFrom as q, withReviewContext as r, sweepReviewChannelSessions as s, currentReviewContext as t, evaluateThreat as u, trimPatternBoundaries as v, eventsFile as w, EVENT_LOG_ROTATE_AT as x, EVENT_ARCHIVE_PREFIX as y, lintSkill as z };
@@ -1,9 +1,99 @@
1
- import { a as evolutionSignalsProjection, i as evolutionReadsProjection, n as evolutionEvidenceProjection, r as evolutionProjectionHistoryProjection, t as evolutionActivityProjection } from "../session-projection-ByNxQi9O.js";
1
+ import { a as evolutionSignalsProjection, i as evolutionReadsProjection, n as evolutionEvidenceProjection, r as evolutionProjectionHistoryProjection, t as evolutionActivityProjection } from "../session-projection-CbIKvDfJ.js";
2
2
  import { t as connectionPort } from "../connection-DAJy7Xjm.js";
3
3
  import { C as workingDirectoryPort, D as profileContextPort, E as pluginManagerPort, O as commandsPort, S as skillsPort, T as pluginInventoryPort, _ as agentsPort, b as storageDomainPort, d as EvolutionLlmError, f as llmPort, g as subagentsPort, h as userQuestionsPort, m as projectionPort, p as modelRoute, v as systemPromptPort, w as configEditorPort, x as sessionQueryPort, y as settingsPort } from "../platform-DyHnHUmQ.js";
4
4
  import { t as presetsPort } from "../presets-C8vuCuNA.js";
5
5
  import { n as toolsPort } from "../tools-BrUswg8v.js";
6
+ import { join } from "node:path";
7
+ import { existsSync, readFileSync } from "node:fs";
6
8
  import { Service } from "@deepseek-ai/cordis";
9
+ //#region lib/types/runtime/coherence.js
10
+ /**
11
+ * Family version coherence probe.
12
+ *
13
+ * A profile can contain one bundle whose implementation packages come from
14
+ * different family releases: the bundle row updates while a directly pinned
15
+ * sibling stays behind, or old hand-copied packages shadow the pnpm tree. The
16
+ * loader then runs an old client against a new host, which looks like a UI
17
+ * regression rather than a mixed install. This probe names that state at
18
+ * startup; it never repairs a live profile (a package-manager write while the
19
+ * host runs is unsafe and needs a restart).
20
+ *
21
+ * @module @lmzhen/dsh-evolution-core/runtime/coherence
22
+ */
23
+ function packageTail(name) {
24
+ return name.slice(name.lastIndexOf("/") + 1);
25
+ }
26
+ /** Family implementation tails; external @deepseek-ai packages stay out. */
27
+ function isFamilyPackage(name) {
28
+ const tail = packageTail(name);
29
+ return tail.startsWith("dsh-evolution-") || tail === "dsh-memory" || tail === "dsh-memory-files" || tail === "dsh-skill-usage" || tail === "dsh-tool-memory" || tail === "dsh-tool-skill-manage";
30
+ }
31
+ /**
32
+ * Compare every implementation package with the installed `all` bundle.
33
+ * Missing packages count as a mismatch because the old loader would fall back
34
+ * to an unrelated copy or fail at load.
35
+ * @param profileDir - profile directory containing `package.json` and `node_modules`.
36
+ * @returns The coherence result, or undefined when the profile has no readable `all` bundle.
37
+ */
38
+ function checkFamilyCoherence(profileDir) {
39
+ if (!existsSync(join(profileDir, "package.json"))) return void 0;
40
+ const resolveManifest = (name) => {
41
+ const path = join(profileDir, "node_modules", name, "package.json");
42
+ return existsSync(path) ? path : void 0;
43
+ };
44
+ const allPath = resolveManifest("@lmzhen/dsh-evolution-all") ?? resolveManifest("@lmzhen/dsh-evolution-all");
45
+ if (allPath === void 0) return void 0;
46
+ let all;
47
+ try {
48
+ all = JSON.parse(readFileSync(allPath, "utf8"));
49
+ } catch {
50
+ return;
51
+ }
52
+ if (typeof all.version !== "string") return void 0;
53
+ const components = [];
54
+ const visited = /* @__PURE__ */ new Set();
55
+ const queue = Object.keys(all.dependencies ?? {}).filter(isFamilyPackage);
56
+ while (queue.length > 0) {
57
+ const name = queue.shift();
58
+ if (name === void 0 || visited.has(name)) continue;
59
+ visited.add(name);
60
+ const manifestPath = resolveManifest(name);
61
+ if (manifestPath === void 0) {
62
+ components.push({ name });
63
+ continue;
64
+ }
65
+ try {
66
+ const manifest = JSON.parse(readFileSync(manifestPath, "utf8"));
67
+ components.push({
68
+ name,
69
+ ...typeof manifest.version === "string" ? { version: manifest.version } : {}
70
+ });
71
+ for (const child of [...Object.keys(manifest.dependencies ?? {}), ...Object.keys(manifest.optionalDependencies ?? {})]) if (isFamilyPackage(child) && !visited.has(child)) queue.push(child);
72
+ } catch {
73
+ components.push({ name });
74
+ }
75
+ }
76
+ return {
77
+ allVersion: all.version,
78
+ components,
79
+ mismatched: components.filter((component) => component.version !== all.version)
80
+ };
81
+ }
82
+ /**
83
+ * Warn once when the running profile is a mixed family install.
84
+ * @param ctx - the running host context; a bare library mount has no profile and is skipped.
85
+ * @returns The detected mismatch, or undefined when no profile/all bundle is present.
86
+ */
87
+ function warnIfFamilyMixed(ctx) {
88
+ const profile = profileContextPort(ctx);
89
+ if (profile === void 0) return void 0;
90
+ const coherence = checkFamilyCoherence(profile.dir);
91
+ if (coherence === void 0 || coherence.mismatched.length === 0) return void 0;
92
+ const details = coherence.mismatched.map((component) => `${component.name}@${component.version ?? "missing"}`).join(", ");
93
+ console.warn(`[dsh-evolution] mixed family install: all@${coherence.allVersion} but ${details}; the loaded client may be an older release. Run the profile repair in INSTALL.md before restarting.`);
94
+ return coherence;
95
+ }
96
+ //#endregion
7
97
  //#region lib/types/runtime/llm.js
8
98
  /**
9
99
  * The family's LLM runtime: one route/purpose/transport path for auxiliary
@@ -231,6 +321,7 @@ async function apply(ctx) {
231
321
  await ctx.plugin(EvolutionPlatform);
232
322
  await ctx.plugin(EvolutionProjections);
233
323
  await ctx.plugin(EvolutionLlm);
324
+ warnIfFamilyMixed(ctx);
234
325
  }
235
326
  //#endregion
236
327
  export { apply, name };
@@ -1,4 +1,5 @@
1
1
  import { t as CITATION_SUPPORT_DIRS } from "./citations-CZKTUGQF.js";
2
+ import { r as graphemeCount } from "./text-metrics-CyJhxWBs.js";
2
3
  import { z } from "zod";
3
4
  //#region lib/types/tool-dispatch.js
4
5
  /**
@@ -608,7 +609,7 @@ function foldTurnEvent(state, event) {
608
609
  const text = content.map(textOfBlock).join(" ");
609
610
  return {
610
611
  ...state,
611
- userChars: state.userChars + text.length,
612
+ userChars: state.userChars + graphemeCount(text),
612
613
  memorySignal: state.memorySignal || CORRECTION_PATTERNS.some((pattern) => pattern.test(text)),
613
614
  skillSignal: state.skillSignal || FIX_PATTERNS.some((pattern) => pattern.test(text))
614
615
  };
@@ -619,7 +620,7 @@ function foldTurnEvent(state, event) {
619
620
  const text = message.content.map(textOfBlock).join(" ");
620
621
  return {
621
622
  ...state,
622
- assistantChars: state.assistantChars + text.length
623
+ assistantChars: state.assistantChars + graphemeCount(text)
623
624
  };
624
625
  }
625
626
  const dispatch = dispatchStepOf(event);