@lmzhen/dsh-evolution-core 0.49.0 → 0.51.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 (110) hide show
  1. package/lib/authority-plugin.js +2 -1
  2. package/lib/citations-CZKTUGQF.js +198 -0
  3. package/lib/composition/index.js +3 -3
  4. package/lib/{composition-Cqjbho0t.js → composition-CtNbVHq3.js} +1 -1
  5. package/lib/connection-DAJy7Xjm.js +28 -0
  6. package/lib/{ensure-CAjLGd9f.js → ensure-BLmEW0Ju.js} +25 -7
  7. package/lib/errors.js +2 -0
  8. package/lib/extract-plan-D6o__2Kf.js +271 -0
  9. package/lib/extract.js +240 -0
  10. package/lib/http-routes.js +27 -7
  11. package/lib/index.js +100 -811
  12. package/lib/{numeric-D8js3sqC.js → limits-C9jfvxBl.js} +1 -43
  13. package/lib/{mutation-authority-l57R626O.js → mutation-authority-DQfpXs1O.js} +2 -54
  14. package/lib/numeric-Dc53KQoe.js +43 -0
  15. package/lib/platform/index.js +4 -3
  16. package/lib/platform-DyHnHUmQ.js +251 -0
  17. package/lib/policy.js +3 -2
  18. package/lib/quality-DpAS0rd9.js +554 -0
  19. package/lib/restrictor.js +1 -1
  20. package/lib/result.js +33 -0
  21. package/lib/runtime/plugin.js +97 -43
  22. package/lib/{session-projection-DSXnUNZG.js → session-projection-ByNxQi9O.js} +2 -198
  23. package/lib/skill-health-BQCM4N8z.js +1419 -0
  24. package/lib/{skill-history-CxrDE3Rb.js → skill-history-CZp8vhyL.js} +46 -2
  25. package/lib/skills.js +140 -20
  26. package/lib/state-store-Jpa-iYIZ.js +54 -0
  27. package/lib/subagent/index.js +214 -176
  28. package/lib/{tools-DzcNFex2.js → tools-BrUswg8v.js} +3 -1
  29. package/lib/types/composition/ensure.js +21 -7
  30. package/lib/types/composition/preset-ids.d.ts +2 -1
  31. package/lib/types/composition/preset-ids.js +7 -1
  32. package/lib/types/events.d.ts +3 -0
  33. package/lib/types/extract-plan.d.ts +2 -0
  34. package/lib/types/extract.d.ts +12 -0
  35. package/lib/types/extract.js +12 -0
  36. package/lib/types/http-routes.js +32 -9
  37. package/lib/types/index.d.ts +0 -3
  38. package/lib/types/index.js +0 -3
  39. package/lib/types/opt-in.js +4 -3
  40. package/lib/types/params.js +2 -1
  41. package/lib/types/platform/agents.d.ts +32 -0
  42. package/lib/types/platform/agents.js +26 -0
  43. package/lib/types/platform/commands.d.ts +14 -0
  44. package/lib/types/platform/commands.js +9 -0
  45. package/lib/types/platform/connection.d.ts +26 -0
  46. package/lib/types/platform/connection.js +27 -0
  47. package/lib/types/platform/index.d.ts +26 -0
  48. package/lib/types/platform/index.js +13 -0
  49. package/lib/types/platform/llm.d.ts +3 -1
  50. package/lib/types/platform/llm.js +1 -0
  51. package/lib/types/platform/platformView.d.ts +21 -0
  52. package/lib/types/platform/platformView.js +29 -0
  53. package/lib/types/platform/profileContext.d.ts +16 -0
  54. package/lib/types/platform/profileContext.js +14 -0
  55. package/lib/types/platform/sessionQuery.d.ts +14 -0
  56. package/lib/types/platform/sessionQuery.js +9 -0
  57. package/lib/types/platform/settings.d.ts +22 -0
  58. package/lib/types/platform/settings.js +14 -0
  59. package/lib/types/platform/skills.d.ts +16 -0
  60. package/lib/types/platform/skills.js +9 -0
  61. package/lib/types/platform/storageDomain.d.ts +13 -0
  62. package/lib/types/platform/storageDomain.js +9 -0
  63. package/lib/types/platform/subagents.d.ts +25 -0
  64. package/lib/types/platform/subagents.js +17 -0
  65. package/lib/types/platform/systemPrompt.d.ts +16 -0
  66. package/lib/types/platform/systemPrompt.js +13 -0
  67. package/lib/types/platform/tools.d.ts +4 -0
  68. package/lib/types/platform/tools.js +2 -0
  69. package/lib/types/platform/userQuestions.d.ts +33 -0
  70. package/lib/types/platform/userQuestions.js +9 -0
  71. package/lib/types/platform/workingDirectory.d.ts +14 -0
  72. package/lib/types/platform/workingDirectory.js +9 -0
  73. package/lib/types/platform-line.generated.d.ts +5 -5
  74. package/lib/types/platform-line.generated.js +5 -5
  75. package/lib/types/platform-services.js +4 -0
  76. package/lib/types/prompts.d.ts +9 -8
  77. package/lib/types/prompts.js +20 -1
  78. package/lib/types/result.d.ts +35 -0
  79. package/lib/types/result.js +25 -0
  80. package/lib/types/review-context.d.ts +8 -0
  81. package/lib/types/review-context.js +11 -0
  82. package/lib/types/run-registry.d.ts +2 -1
  83. package/lib/types/run-registry.js +37 -7
  84. package/lib/types/runtime/llm.d.ts +2 -2
  85. package/lib/types/runtime/llm.js +5 -8
  86. package/lib/types/runtime/platform.d.ts +37 -4
  87. package/lib/types/runtime/platform.js +40 -5
  88. package/lib/types/runtime/projections.d.ts +9 -4
  89. package/lib/types/runtime/projections.js +64 -28
  90. package/lib/types/section-selection.js +5 -0
  91. package/lib/types/skill-history.d.ts +29 -3
  92. package/lib/types/skill-history.js +30 -0
  93. package/lib/types/skill-store.d.ts +32 -4
  94. package/lib/types/skill-store.js +109 -15
  95. package/lib/types/subagent/channel.d.ts +1 -3
  96. package/lib/types/subagent/channel.js +2 -332
  97. package/lib/types/subagent/index.d.ts +2 -0
  98. package/lib/types/subagent/index.js +2 -0
  99. package/lib/types/subagent/kernel.d.ts +4 -0
  100. package/lib/types/subagent/kernel.js +234 -0
  101. package/lib/types/subagent/readiness.js +5 -7
  102. package/lib/types/subagent/run.d.ts +53 -0
  103. package/lib/types/subagent/run.js +125 -0
  104. package/lib/types/subagent/types.d.ts +3 -3
  105. package/lib/types/write-gates.js +11 -1
  106. package/lib/usage-B5a90TKv.js +1257 -0
  107. package/lib/write.js +1 -1
  108. package/package.json +37 -25
  109. package/lib/platform-Cc9cNt5j.js +0 -111
  110. package/lib/skill-health-DP8z9TPf.js +0 -2923
@@ -0,0 +1,1419 @@
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-C9jfvxBl.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 { z as skillMdOnDisk } from "./usage-B5a90TKv.js";
5
+ import { t as clampedNumber } from "./numeric-Dc53KQoe.js";
6
+ import { AsyncLocalStorage } from "node:async_hooks";
7
+ import { dirname, join } from "node:path";
8
+ //#region lib/types/write-authority.js
9
+ /** The mode a deployment that configures nothing gets. */
10
+ const DEFAULT_WRITE_CONFIRM_MODE = "auto";
11
+ /** Seconds a timeout-mode prompt waits before the write is cancelled. */
12
+ const DEFAULT_WRITE_CONFIRM_TIMEOUT_SECONDS = 120;
13
+ /**
14
+ * The batch-one migration aid: every call site becomes ONE of these instead of hand-building the
15
+ * object - so the shape cannot drift between callers, and each site still has to say its own
16
+ * origin out loud (origin is required here on purpose: the whole point is that no caller inherits
17
+ * a default identity).
18
+ */
19
+ function authorityFrom(input) {
20
+ return {
21
+ origin: input.origin,
22
+ threatExemptLabels: input.threatExemptLabels ?? [],
23
+ protectedNames: input.protectedNames,
24
+ readNames: input.readNames,
25
+ ...input.confirm === void 0 ? {} : { confirm: input.confirm },
26
+ ...input.confirmMode === void 0 ? {} : { confirmMode: input.confirmMode },
27
+ ...input.confirmTimeoutSeconds === void 0 ? {} : { confirmTimeoutSeconds: input.confirmTimeoutSeconds },
28
+ warn: input.warn ?? (() => {})
29
+ };
30
+ }
31
+ //#endregion
32
+ //#region lib/types/skill-reads.js
33
+ /**
34
+ * The skill names ONE session read, or `undefined` when its log is not readable.
35
+ *
36
+ * Two readers, in this order: the family's `evolutionReads` projection for a platform `Session`
37
+ * (0.2.x's live read — the deprecated synchronous log read is gone from production), then the
38
+ * STRUCTURAL accessor for a view that is not a `Session` at all. The tool path's exec view may be a
39
+ * bare stub, which is what this module exists for; a real Session always takes the first path.
40
+ *
41
+ * `undefined` is NOT an empty set: a caller that must decide (the tool path's read-before-write
42
+ * gate) can then keep its previous behavior instead of refusing every write in a composition whose
43
+ * session objects expose no log at all.
44
+ * @param ctx - a context of the runtime.
45
+ * @param session - the session whose reads are wanted; `undefined` when the call carries none.
46
+ * @returns the names read through a non-failed `skill` dispatch, or `undefined` when unreadable.
47
+ */
48
+ function sessionReadSkillNames(ctx, session) {
49
+ if (session === void 0) return void 0;
50
+ const projected = sessionReadNames(ctx, session);
51
+ if (projected !== void 0) return projected;
52
+ const events = session.readEvents?.();
53
+ return events === void 0 ? void 0 : collectReadSkillNames(events);
54
+ }
55
+ /**
56
+ * Skill support files ONE session read through a non-failed file tool (P2-27).
57
+ *
58
+ * platform-declaration anchor: `sessionProjections` is declared by
59
+ * `@deepseek-ai/dsh-session-projection` (its registry; capability-probed here).
60
+ * Same two readers as {@link sessionReadSkillNames}: the family projection first,
61
+ * then the structural log view. `undefined` means "no evidence", not "nothing was
62
+ * read" - the write gate then keeps its fail-open posture.
63
+ * @param ctx - a context of the runtime.
64
+ * @param session - the session whose reads are wanted.
65
+ * @param options - the skills root and the configured file-tool names.
66
+ * @returns skill -> set of skill-root-relative support paths.
67
+ */
68
+ function sessionReadSupportFiles(ctx, session, options) {
69
+ if (session === void 0) return void 0;
70
+ if (isProjectableSession(session)) {
71
+ const state = ctx.get("evolutionProjections")?.reads(session);
72
+ if (state !== void 0) {
73
+ const toolNames = options.toolNames ?? DEFAULT_SUPPORT_READ_TOOL_NAMES;
74
+ const reads = /* @__PURE__ */ new Map();
75
+ for (const entry of state.reads) {
76
+ if (entry.failed || typeof entry.file !== "string") continue;
77
+ if (entry.tool !== void 0 && !toolNames.includes(entry.tool)) continue;
78
+ const hit = supportFileReadFromPath(entry.file, { root: options.root });
79
+ if (hit === null) continue;
80
+ const set = reads.get(hit.skill) ?? /* @__PURE__ */ new Set();
81
+ set.add(hit.rel);
82
+ reads.set(hit.skill, set);
83
+ }
84
+ return reads;
85
+ }
86
+ }
87
+ const events = session.readEvents?.();
88
+ return events === void 0 ? void 0 : collectReadSupportFiles(events, {
89
+ toolNames: options.toolNames ?? DEFAULT_SUPPORT_READ_TOOL_NAMES,
90
+ root: options.root
91
+ });
92
+ }
93
+ /** Actions whose target must have been read first (create is authorship, so it is exempt). */
94
+ const READ_REQUIRED_ACTIONS = Object.freeze([
95
+ "edit",
96
+ "update",
97
+ "patch",
98
+ "delete",
99
+ "write_file",
100
+ "remove_file",
101
+ "restructure",
102
+ "extract"
103
+ ]);
104
+ /**
105
+ * Does this one op write a skill the caller never read?
106
+ *
107
+ * V6-26 (0.3.37): the validator normalizes a missing action to `patch`, so a missing action is a
108
+ * read-required write, never silently exempt.
109
+ * @param op - one skill operation (from a tool call or a review plan).
110
+ * @param readNames - names read this session, from {@link collectReadSkillNames}.
111
+ * @returns true when the op is a read-required write to an unread target.
112
+ */
113
+ function isUnreadWrite(op, readNames) {
114
+ if (!op.name) return false;
115
+ return READ_REQUIRED_ACTIONS.includes(op.action ?? "patch") && !readNames.has(op.name);
116
+ }
117
+ /**
118
+ * Drop mutating ops whose target was not read this session, in place.
119
+ *
120
+ * Covers the same mutating surface Hermes guards (edit/patch/write_file/remove_file), so a
121
+ * background review cannot blind-touch support files or edits of skills it never loaded.
122
+ * @param ops - the plan's ops; dropped entries are removed in place.
123
+ * @param readNames - names read this session.
124
+ * @returns the count of dropped ops, so the plan event can report them as rejected.
125
+ */
126
+ function filterUnreadSkillOps(ops, readNames) {
127
+ let dropped = 0;
128
+ for (let index = ops.length - 1; index >= 0; index -= 1) {
129
+ const op = ops[index];
130
+ if (!op) continue;
131
+ if (isUnreadWrite(op, readNames)) {
132
+ ops.splice(index, 1);
133
+ dropped += 1;
134
+ }
135
+ }
136
+ return dropped;
137
+ }
138
+ //#endregion
139
+ //#region lib/types/cost.js
140
+ /**
141
+ * Context-cost accounting for skill bodies (design §5.2).
142
+ *
143
+ * A raw character count is a poor budget: the same 100k characters cost very
144
+ * different amounts of context in Chinese-heavy prose and in English. The
145
+ * weighted unit makes the two comparable, and the token range exists only to
146
+ * make the load cost visible next to the character count — it is an ESTIMATE,
147
+ * never a measurement.
148
+ *
149
+ * Accounting basis: the ON-DISK form (`skillMdOnDisk()`, the same view the
150
+ * write limit uses), so a body that is exactly at the limit cannot read as
151
+ * over-limit here and pass there (the v37 P2-1 deadlock class).
152
+ */
153
+ /** Token weight of one CJK / kana / full-width code unit on the LIMIT basis —
154
+ * upstream's model-independent conversion is 2.75 chars/token for prose, and CJK
155
+ * prose is ~1 token per character (the conservative end of the 0.6–1.0 range the
156
+ * estimate side reports). Thresholds are compared on THIS basis so a borrowed
157
+ * character line keeps its meaning; the estimate range below reports the spread. */
158
+ const TOKEN_CJK_WEIGHT = 1;
159
+ /** Token weight of one non-CJK code unit on the LIMIT basis (1 / 2.75 ≈ 0.364). */
160
+ const TOKEN_ASCII_WEIGHT = 1 / UPSTREAM_LIMIT_CHARS_PER_TOKEN;
161
+ /** Token-per-unit bounds of the estimate range (CJK: 0.6–1.0, non-CJK: 1/4–1/3).
162
+ * The range is the 4-chars/token estimate family, so on ASCII-heavy bodies the
163
+ * LIMIT-basis `tokens` point can sit above `tokensHigh` (1/2.75 > 1/3): the two
164
+ * answer different questions and are never nested by construction. */
165
+ const COST_CJK_TOKEN_LOW = .6;
166
+ const COST_CJK_TOKEN_HIGH = 1;
167
+ const COST_ASCII_TOKEN_LOW = .25;
168
+ const COST_ASCII_TOKEN_HIGH = 1 / 3;
169
+ /** The token line a borrowed CHARACTER threshold draws for ONE body: 20k characters
170
+ * of THIS composition, expressed in the same tokens `bodyCost` counts. Comparing
171
+ * `tokens` against this line is deliberately equivalent to "chars >= line" — that
172
+ * equivalence is what keeps a borrowed line's textual effect identical — while the
173
+ * judgment itself, and every number reported, stays on the token scale.
174
+ * @param lineChars - the borrowed character line (whole-body characters).
175
+ * @param cost - the body's own cost breakdown.
176
+ * @returns the equivalent token line (0 when the body is empty). */
177
+ function tokenLineFor(lineChars, cost) {
178
+ if (cost.chars === 0) return 0;
179
+ return Math.round(lineChars * cost.tokens / cost.chars);
180
+ }
181
+ /** CJK ideographs, kana, full-width forms and CJK punctuation. */
182
+ const CJK_RE = /[\u3000-\u303f\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff\uff00-\uffef]/g;
183
+ /**
184
+ * Cost of one skill body.
185
+ * @param content - the body text as written (trailing whitespace is normalized
186
+ * away by the on-disk accounting, so callers need not pre-trim).
187
+ * @returns the cost breakdown; an empty body answers all-zero.
188
+ */
189
+ function bodyCost(content) {
190
+ const onDisk = skillMdOnDisk(content);
191
+ const cjk = [...onDisk.matchAll(CJK_RE)].length;
192
+ const chars = onDisk.length;
193
+ const ascii = chars - cjk;
194
+ return {
195
+ chars,
196
+ cjk,
197
+ ascii,
198
+ tokens: Math.round(cjk * 1 + ascii * TOKEN_ASCII_WEIGHT),
199
+ tokensLow: Math.round(cjk * COST_CJK_TOKEN_LOW + ascii * COST_ASCII_TOKEN_LOW),
200
+ tokensHigh: Math.round(cjk * 1 + ascii * COST_ASCII_TOKEN_HIGH)
201
+ };
202
+ }
203
+ //#endregion
204
+ //#region lib/types/skill-lint.js
205
+ const msg = (parts) => parts.map((p) => typeof p === "string" ? p : String(p)).join("");
206
+ /** One rule yields AT MOST one finding (contract §3). `body-oversize-2x` is the only rule whose
207
+ * severity can escalate a verdict to needs-restructure. */
208
+ const RULES = [
209
+ {
210
+ id: "unreadable-skill",
211
+ severity: "error",
212
+ run: (facts) => facts.readable && facts.dims.bodyChars !== null ? null : {
213
+ severity: "error",
214
+ rule: "unreadable-skill",
215
+ message: msg([facts.skillName, ": SKILL.md could not be read — no health claim is possible"]),
216
+ count: 1
217
+ }
218
+ },
219
+ {
220
+ id: "body-oversize-2x",
221
+ severity: "error",
222
+ run: (facts) => facts.overTwiceSoftLine ? {
223
+ severity: "error",
224
+ rule: "body-oversize-2x",
225
+ message: msg([
226
+ facts.skillName,
227
+ ": body is at or past twice the soft line (",
228
+ facts.softLineChars,
229
+ " chars); keeping the current skill is valid"
230
+ ]),
231
+ count: 1
232
+ } : null
233
+ },
234
+ {
235
+ id: "body-oversize",
236
+ severity: "warn",
237
+ run: (facts) => !facts.overTwiceSoftLine && facts.overSoftLine ? {
238
+ severity: "warn",
239
+ rule: "body-oversize",
240
+ message: msg([
241
+ facts.skillName,
242
+ ": body is at or above the soft line (",
243
+ facts.softLineChars,
244
+ " chars); keep is valid — size alone does not require a split"
245
+ ]),
246
+ count: 1
247
+ } : null
248
+ },
249
+ {
250
+ id: "stamp-density",
251
+ severity: "warn",
252
+ run: (facts) => {
253
+ const density = facts.dims.stampDensityPerKb;
254
+ const hits = facts.dims.stampHits;
255
+ if (density === null || hits === null || density < facts.stampLimitPerKb) return null;
256
+ return {
257
+ severity: "warn",
258
+ rule: "stamp-density",
259
+ message: msg([
260
+ facts.skillName,
261
+ ": stamp density ",
262
+ density.toFixed(1),
263
+ "/KB (rc/sha/date lines — log-like content)"
264
+ ]),
265
+ count: hits
266
+ };
267
+ }
268
+ },
269
+ {
270
+ id: "body-without-support",
271
+ severity: "warn",
272
+ run: (facts) => facts.dims.supportGroups === 0 && facts.dims.bodyChars !== null && facts.dims.bodyChars >= facts.softLineChars / 2 ? {
273
+ severity: "warn",
274
+ rule: "body-without-support",
275
+ message: msg([
276
+ facts.skillName,
277
+ ": large body (",
278
+ facts.dims.bodyChars,
279
+ " chars) with NO support files"
280
+ ]),
281
+ count: 1
282
+ } : null
283
+ },
284
+ {
285
+ id: "references-sprawl",
286
+ severity: "warn",
287
+ run: (facts) => {
288
+ const files = facts.dims.supportFiles;
289
+ if (files === null || files < 60) return null;
290
+ return {
291
+ severity: "warn",
292
+ rule: "references-sprawl",
293
+ message: msg([
294
+ facts.skillName,
295
+ ": ",
296
+ files,
297
+ " support files"
298
+ ]),
299
+ count: files
300
+ };
301
+ }
302
+ },
303
+ {
304
+ id: "scope-overloaded",
305
+ severity: "warn",
306
+ run: (facts) => {
307
+ const hits = facts.dims.hardCapHits;
308
+ const files = facts.dims.supportFiles;
309
+ if (hits === null || files === null || hits < facts.hardCapMinHits || files < 3) return null;
310
+ return {
311
+ severity: "warn",
312
+ rule: "scope-overloaded",
313
+ message: msg([
314
+ facts.skillName,
315
+ ": ",
316
+ hits,
317
+ " hard-cap hit(s) with ",
318
+ files,
319
+ " support files — remaining growth may be scope"
320
+ ]),
321
+ count: hits
322
+ };
323
+ }
324
+ },
325
+ {
326
+ id: "write-ghost",
327
+ severity: "warn",
328
+ run: (facts) => {
329
+ const patches = facts.dims.churnPatches;
330
+ const reads = facts.dims.churnReads;
331
+ if (patches === null || reads === null || patches < facts.churnMinPatches || reads > 0) return null;
332
+ return {
333
+ severity: "warn",
334
+ rule: "write-ghost",
335
+ message: msg([
336
+ facts.skillName,
337
+ ": ",
338
+ patches,
339
+ " patch(es), never read"
340
+ ]),
341
+ count: patches
342
+ };
343
+ }
344
+ }
345
+ ];
346
+ function lintSkill(facts) {
347
+ const out = [];
348
+ for (const rule of RULES) {
349
+ const hit = rule.run(facts);
350
+ if (hit !== null) out.push(hit);
351
+ }
352
+ return out;
353
+ }
354
+ /** What a write introduced, what got worse, what got fixed. A rule whose count grew (one site to
355
+ * nine) counts as worsened — comparing by rule name alone reported nothing. */
356
+ function diffFindings(before, after) {
357
+ const beforeByRule = new Map(before.map((f) => [f.rule, f]));
358
+ const afterByRule = new Map(after.map((f) => [f.rule, f]));
359
+ return {
360
+ introduced: after.filter((f) => !beforeByRule.has(f.rule)),
361
+ worsened: after.filter((f) => {
362
+ const old = beforeByRule.get(f.rule);
363
+ return old !== void 0 && f.count > old.count;
364
+ }),
365
+ resolved: before.filter((f) => !afterByRule.has(f.rule)).map((f) => f.rule)
366
+ };
367
+ }
368
+ //#endregion
369
+ //#region lib/types/evolution-events.js
370
+ /**
371
+ * Self-evolution event log (rc.68): an append-only sidecar under
372
+ * `$DSH_HOME/evolution/events.json` that is the single source of truth for
373
+ * the self-improvement loop. Feedback increments and learn actions share one
374
+ * ordered timeline (`seq` is the ordering key), so "feedback before/after a
375
+ * learn on target X" is answerable. The aggregate `feedback.json` is a
376
+ * rebuildable boot cache, never the truth.
377
+ *
378
+ * Usage events (C semantics, rc.73+): `type:'usage'` records are the
379
+ * OBSERVATION WINDOW ANCHOR — written once, when the library's first observed
380
+ * read (`view_count` 0 -> 1) happens. The anchor is the durable timeline record
381
+ * of that moment: the churn-suppression gate itself (`usageObserved()`) reads
382
+ * the usage SIDECAR's own first-view evidence, since reads were invisible to it
383
+ * pre-A2 and no sidecar record can reach `view_count > 0` without the same
384
+ * 0 -> 1 transition. `counts` on the event is a cumulative library-wide
385
+ * snapshot (skills/views/use/patches) at that moment, and `window.opened` pins
386
+ * the window start for the timeline. (V27 G3.3: `verify-event-pairing` requires
387
+ * every persisted type to have a production reader or a declared external
388
+ * contract — this one is the latter.)
389
+ *
390
+ * Rotation (rc.71, 007 design): when the active log reaches
391
+ * `EVENT_LOG_ROTATE_AT` the older half is split into an archive
392
+ * (`events-<lastArchivedSeq>.json`); the boot timeline merges active +
393
+ * archives and dedupes by seq (active copy wins), so the rotation crash window
394
+ * yields the identical timeline. Archival naming is STRICTLY numeric
395
+ * (`/^events-\d+\.json$/`) — user files under the same directory are never
396
+ * read as archives and never pruned (rc.72 G-2).
397
+ */
398
+ const EVENT_LOG_VERSION = 1;
399
+ /** Active-log split point (rc.71): when the active log reaches this many events
400
+ * the older half is rotated into an archive; the active stays bounded so a
401
+ * single append stays O(active) instead of O(total-history). Tunable default —
402
+ * callers may override per append (the tests use small values). */
403
+ const EVENT_LOG_ROTATE_AT = 4e3;
404
+ /** Number of archives retained (rc.71): older archives are pruned at rotation,
405
+ * mirroring retainReports. The horizon covers the loop-analysis window. */
406
+ const EVENT_LOG_RETAIN_ARCHIVES = 10;
407
+ /** Archive file prefix: `events-<lastArchivedSeq>.json`. The active file is
408
+ * `events.json` and never matches this glob. */
409
+ const EVENT_ARCHIVE_PREFIX = "events-";
410
+ /** Archive naming is strictly numeric: a user file such as `events-backup.json`
411
+ * under the same directory is neither read into the timeline nor pruned. */
412
+ const EVENT_ARCHIVE_RE = /^events-(\d+)\.json$/;
413
+ function eventsFile(home) {
414
+ return join(home, "evolution", "events.json");
415
+ }
416
+ /** I-5 (v18): one lightweight description of the durable event payload
417
+ * contract. The log is a FILE boundary (a host, a script or an older version
418
+ * can write it), so `appendEvolutionEvent` refuses a record no consumer can
419
+ * fold instead of persisting it and failing silently later. The process event
420
+ * bus stays unvalidated — that is a typed same-process boundary.
421
+ * @param event - the candidate event record.
422
+ * @returns a human-readable issue, or null when the record is well-formed.
423
+ */
424
+ function evolutionEventPayloadIssue(event) {
425
+ const type = event.type;
426
+ if (typeof type !== "string") return `unknown event type "${String(type)}"`;
427
+ switch (type) {
428
+ case "feedback":
429
+ if (event.kind !== "skill" && event.kind !== "session") return "feedback event requires kind skill|session";
430
+ if (event.rating !== "positive" && event.rating !== "negative") return "feedback event requires rating positive|negative";
431
+ if (typeof event.target !== "string" || event.target.trim() === "") return "feedback event requires a non-empty target";
432
+ return null;
433
+ case "maintain": return typeof event.runId === "string" ? null : "maintain event requires runId";
434
+ case "learn":
435
+ case "usage": return null;
436
+ case "hard-cap":
437
+ if (typeof event.target !== "string" || event.target.trim() === "") return "hard-cap event requires a non-empty target";
438
+ if (typeof event.bodyChars !== "number" || !Number.isFinite(event.bodyChars)) return "hard-cap event requires a finite bodyChars";
439
+ return null;
440
+ default: return `unknown event type "${type}"`;
441
+ }
442
+ }
443
+ function isEventRecord(event) {
444
+ const seq = event?.seq;
445
+ return typeof event === "object" && event !== null && typeof seq === "number" && Number.isFinite(seq);
446
+ }
447
+ /**
448
+ * Parse an event log body. A missing file, a whitespace-only file (rc.69:
449
+ * rebuildable, NOT malformed) or a corrupt one reads as empty; corrupt content
450
+ * is still refused on append, never overwritten.
451
+ *
452
+ * This reader is **v1-only** (F-338): a body carrying a `version` other than
453
+ * `EVENT_LOG_VERSION` is a future-format log this reader cannot interpret, so
454
+ * it reads as an EMPTY timeline rather than being mis-parsed as v1. The read
455
+ * side never overwrites it on its own — `appendEvolutionEvent` rejects a
456
+ * version mismatch up front and preserves the original bytes, so a newer log
457
+ * is never silently downgraded here.
458
+ *
459
+ * Per-entry normalization (rc.70 F-1): entries without a numeric `seq` are
460
+ * skipped here and dropped at the next append — valid entries survive, the
461
+ * damaged record is the only loss (self-heal semantics, matching the usage
462
+ * sidecar's per-field normalization on read).
463
+ */
464
+ /**
465
+ * Post-parse v1 gate shared by parseEvolutionEvents and appendEvolutionEvent
466
+ * (C-06, v10 audit: the append used to JSON.parse the same body a second time
467
+ * through parseEvolutionEvents — double parse cost per append). A null parse
468
+ * (missing/whitespace/unparsable body) reads as an empty timeline.
469
+ */
470
+ function v1EventRecords(parsed) {
471
+ if (parsed === null) return [];
472
+ if (parsed.version !== void 0 && parsed.version !== 1) return [];
473
+ if (!Array.isArray(parsed.events)) return [];
474
+ return parsed.events.filter(isEventRecord);
475
+ }
476
+ function parseEvolutionEvents(raw) {
477
+ if (raw === null || raw.trim() === "") return [];
478
+ try {
479
+ return v1EventRecords(JSON.parse(raw));
480
+ } catch {
481
+ return [];
482
+ }
483
+ }
484
+ /**
485
+ * List the numeric archives under the log's directory, sorted ascending by
486
+ * their last-archived seq. Single glob predicate for the timeline, the
487
+ * retention pass and the feedback migration check (rc.72 H-3).
488
+ */
489
+ async function listEventArchives(io, path) {
490
+ const dir = dirname(path);
491
+ return (await io.list(dir)).filter((name) => EVENT_ARCHIVE_RE.test(name)).sort((a, b) => {
492
+ return Number.parseInt(a.slice(7, a.length - 5), 10) - Number.parseInt(b.slice(7, b.length - 5), 10);
493
+ });
494
+ }
495
+ /**
496
+ * Append one event under the write lock (rc.68): `seq` = current max + 1
497
+ * computed inside the transact, so two processes appending concurrently never
498
+ * collide. A malformed log is refused (bytes preserved) and the append fails.
499
+ * Returns the assigned seq.
500
+ *
501
+ * Rotation (rc.71, 007 design): when the active log reaches `rotateAt`, the
502
+ * older half is copied into an archive inside the SAME transact (the archive
503
+ * path has its own lock, so no recursion) and the active is replaced with the
504
+ * newer half + the new event. seqs stay globally monotonic; a crash between
505
+ * archive write and active write leaves both copies, which the timeline merge
506
+ * dedupes by seq. An archive-write failure aborts the append (active keeps the
507
+ * full old content — no loss) and the caller's best-effort handling applies.
508
+ *
509
+ * rc.72 G-1: when the ACTIVE is missing/whitespace but archives exist (a
510
+ * deleted active, or B-2 self-heal), seq derivation consults the archive names
511
+ * — the active restarts AFTER the highest archived seq, never at 1, so a new
512
+ * event can never shadow an archived one in the seq-deduped timeline.
513
+ */
514
+ async function appendEvolutionEvent(io, path, event, rotateAt = EVENT_LOG_ROTATE_AT, fence) {
515
+ const issue = evolutionEventPayloadIssue(event);
516
+ if (issue !== null) throw new Error(`evolution event refused: ${issue}`);
517
+ let assigned = 0;
518
+ let refuseMessage = "";
519
+ let parsedBody = null;
520
+ const write = async () => {
521
+ await transactIo(io, path, async (current) => {
522
+ parsedBody = null;
523
+ refuseMessage = "";
524
+ assigned = 0;
525
+ if (current !== null && current.trim() !== "") {
526
+ let shape;
527
+ try {
528
+ shape = JSON.parse(current);
529
+ } catch {
530
+ return current;
531
+ }
532
+ parsedBody = shape;
533
+ if (shape.version !== void 0 && shape.version !== 1) {
534
+ const found = typeof shape.version === "number" || typeof shape.version === "string" ? String(shape.version) : "unknown";
535
+ const kind = typeof shape.version === "number" || typeof shape.version === "string" ? typeof shape.version : "unknown";
536
+ refuseMessage = `evolution event log version mismatch (expected version 1, got ${kind === "string" ? `"${found}"` : found} (${kind})) and was not touched`;
537
+ return current;
538
+ }
539
+ }
540
+ const rotated = await rotateIfDue(io, path, v1EventRecords(parsedBody), rotateAt);
541
+ if (!rotated.ok) {
542
+ refuseMessage = rotated.reason;
543
+ return current;
544
+ }
545
+ const events = rotated.events;
546
+ let maxSeq = events.reduce((max, entry) => Math.max(max, entry.seq), 0);
547
+ for (const name of await listEventArchives(io, path)) maxSeq = Math.max(maxSeq, Number.parseInt(name.slice(7, name.length - 5), 10));
548
+ const record = {
549
+ ...event,
550
+ seq: maxSeq + 1,
551
+ at: (/* @__PURE__ */ new Date()).toISOString()
552
+ };
553
+ assigned = record.seq;
554
+ return JSON.stringify({
555
+ version: 1,
556
+ events: [...events, record]
557
+ }, null, 2);
558
+ });
559
+ };
560
+ if (fence !== void 0) await fence.run(write);
561
+ else await write();
562
+ if (assigned === 0) throw new Error(`${refuseMessage || "evolution event log is malformed and was not touched"}: ${path}`);
563
+ return assigned;
564
+ }
565
+ /** The collision archive is mergeable only when this v1 writer can read it
566
+ * (P2-11): a foreign `version` (F-338) or a body without an `events` array is
567
+ * refused, so a merge can never downgrade it or empty it out.
568
+ * @param parsed - the parsed collision archive body.
569
+ * @returns the usable events, or null when the archive must not be rewritten. */
570
+ function mergeableCollisionEvents(parsed) {
571
+ if (parsed.version !== void 0 && parsed.version !== 1) return null;
572
+ if (!Array.isArray(parsed.events)) return null;
573
+ return parsed.events.filter(isEventRecord);
574
+ }
575
+ /**
576
+ * Split the active log at its midpoint when due: the older half is written to
577
+ * `events-<lastArchivedSeq>.json` (await — a failed archive write aborts the
578
+ * append so the active is never truncated without its copy), old archives are
579
+ * pruned, and the newer half is returned as the next active body. No-op when
580
+ * under the threshold; `rotateAt < 2` is a guarded no-op (rc.72 G-1: a
581
+ * one-event rotate would archive everything and restart seqs at 1).
582
+ */
583
+ async function rotateIfDue(io, path, events, rotateAt) {
584
+ if (!Number.isFinite(rotateAt) || rotateAt < 2 || events.length < rotateAt) return {
585
+ ok: true,
586
+ events
587
+ };
588
+ const mid = Math.ceil(events.length / 2);
589
+ const head = events.slice(0, mid);
590
+ const tail = events.slice(mid);
591
+ if (tail.length === 0) return {
592
+ ok: true,
593
+ events
594
+ };
595
+ const anchor = tail[0]?.seq ?? 0;
596
+ const archivePath = join(dirname(path), `${EVENT_ARCHIVE_PREFIX}${anchor - 1}.json`);
597
+ let archived = head;
598
+ let existing;
599
+ try {
600
+ existing = await io.readText(archivePath);
601
+ } catch (error) {
602
+ return {
603
+ ok: false,
604
+ reason: `evolution event archive collision at ${archivePath} could not be read (${error instanceof Error ? error.message : String(error)}) and was not touched`
605
+ };
606
+ }
607
+ if (existing !== null) {
608
+ let parsed = null;
609
+ try {
610
+ parsed = JSON.parse(existing);
611
+ } catch {
612
+ parsed = null;
613
+ }
614
+ if (parsed === null) {
615
+ const shiftPath = `${archivePath}.${Date.now()}.collide`;
616
+ await io.writeText(shiftPath, JSON.stringify({
617
+ version: 1,
618
+ events: head
619
+ }, null, 2));
620
+ console.warn(`evolution-events: rotation hit an unparsable archive collision — the rotated head band was preserved at ${shiftPath} but is OUTSIDE the logical timeline; inspect and merge it manually`);
621
+ await retainEventArchives(io, path);
622
+ await pruneCollideArchives(io, path);
623
+ return {
624
+ ok: true,
625
+ events: tail
626
+ };
627
+ }
628
+ const prior = mergeableCollisionEvents(parsed);
629
+ if (prior === null) return {
630
+ ok: false,
631
+ reason: `evolution event archive collision at ${archivePath} is not a readable version-1 archive (future version, or no "events" array) and was not touched`
632
+ };
633
+ const bySeq = new Map(prior.map((event) => [event.seq, event]));
634
+ for (const event of head) bySeq.set(event.seq, event);
635
+ archived = [...bySeq.values()].sort((a, b) => a.seq - b.seq);
636
+ }
637
+ await io.writeText(archivePath, JSON.stringify({
638
+ version: 1,
639
+ events: archived
640
+ }, null, 2));
641
+ await retainEventArchives(io, path);
642
+ return {
643
+ ok: true,
644
+ events: tail
645
+ };
646
+ }
647
+ /**
648
+ * Prune old event archives (rc.71): keep the newest `EVENT_LOG_RETAIN_ARCHIVES`.
649
+ * The name's numeric part is the last archived seq, so ordering is NUMERIC —
650
+ * lexicographic would rank `events-10` before `events-2`. Only strictly
651
+ * numeric names participate (rc.72 G-2: user files are never deleted).
652
+ * Best-effort per removal; exported for the retention test.
653
+ */
654
+ async function retainEventArchives(io, path) {
655
+ const dir = dirname(path);
656
+ const names = await listEventArchives(io, path);
657
+ const excess = names.slice(0, Math.max(0, names.length - 10));
658
+ for (const name of excess) await io.remove(join(dir, name)).catch(() => {});
659
+ }
660
+ /** v31 EVENTS-02: prune shift-aside collision files (`events-*.json.<ts>.collide`)
661
+ * after the same 7-day window the `.corrupt` sweep uses. They are write-once
662
+ * recovery artifacts no reader accepts; without a sweep they accumulated
663
+ * without bound across rollback episodes. No mtime probe → keep (fail-safe). */
664
+ const COLLIDE_AGE_MS = 10080 * 60 * 1e3;
665
+ async function pruneCollideArchives(io, path) {
666
+ const dir = dirname(path);
667
+ let names;
668
+ try {
669
+ names = await io.list(dir);
670
+ } catch {
671
+ return;
672
+ }
673
+ const now = Date.now();
674
+ for (const name of names) {
675
+ if (!name.endsWith(".collide") || !name.startsWith("events-")) continue;
676
+ const full = join(dir, name);
677
+ const stamp = name.match(/\.(\d{13})\.collide$/);
678
+ if (stamp && now - Number(stamp[1]) < COLLIDE_AGE_MS) continue;
679
+ if (!stamp) try {
680
+ const mtime = await io.mtime?.(full);
681
+ if (typeof mtime !== "number" || now - mtime < COLLIDE_AGE_MS) continue;
682
+ } catch {
683
+ continue;
684
+ }
685
+ await io.remove(full).catch(() => {});
686
+ }
687
+ }
688
+ /** Read the event log; a missing/whitespace-only file reads as empty, corrupt
689
+ * content is flagged (and refused on append). A well-formed future-version body
690
+ * is v1-incompatible: it reads as EMPTY and is now flagged malformed as well
691
+ * (C-events-dispatch-1, v43). F-338's own guarantees are untouched — the reader
692
+ * never mis-shapes a newer format and the append path refuses it up front, so
693
+ * the original bytes survive — while the flag reports what the old reader hid:
694
+ * every record that body holds is dropped from this read. */
695
+ async function readEvolutionEvents(io, path) {
696
+ let raw;
697
+ try {
698
+ raw = await io.readText(path);
699
+ } catch {
700
+ return {
701
+ events: [],
702
+ malformed: true
703
+ };
704
+ }
705
+ if (raw === null || raw.trim() === "") return {
706
+ events: [],
707
+ malformed: false
708
+ };
709
+ try {
710
+ const parsed = JSON.parse(raw);
711
+ if (parsed.version !== void 0 && parsed.version !== 1) return {
712
+ events: [],
713
+ malformed: true
714
+ };
715
+ if (!Array.isArray(parsed.events)) return {
716
+ events: [],
717
+ malformed: false
718
+ };
719
+ return {
720
+ events: parsed.events.filter(isEventRecord),
721
+ malformed: false
722
+ };
723
+ } catch {
724
+ return {
725
+ events: [],
726
+ malformed: true
727
+ };
728
+ }
729
+ }
730
+ /**
731
+ * Read the full timeline (rc.71): active log + all archives, merged by seq
732
+ * (active copy wins, duplicates only arise from the rotation crash window),
733
+ * sorted ascending. Per-file malformed flag as in `readEvolutionEvents`; a
734
+ * flagged ARCHIVE (unreadable, damaged, or a future-version body this reader
735
+ * cannot interpret) is SKIPPED — it never bricks the boot, the returned events
736
+ * simply LACK that seq band, and `malformed` is the only signal that they do
737
+ * (C-events-dispatch-1, v43: the flag is the consumer's contract; a truncated
738
+ * timeline must never be folded back as if it were complete).
739
+ */
740
+ async function readEvolutionTimeline(io, path, archives) {
741
+ const dir = dirname(path);
742
+ let malformed = false;
743
+ const bySeq = /* @__PURE__ */ new Map();
744
+ for (const name of archives ?? await listEventArchives(io, path)) {
745
+ const read = await readEvolutionEvents(io, join(dir, name));
746
+ if (read.malformed) malformed = true;
747
+ for (const event of read.events) bySeq.set(event.seq, event);
748
+ }
749
+ const active = await readEvolutionEvents(io, path);
750
+ if (active.malformed) malformed = true;
751
+ for (const event of active.events) bySeq.set(event.seq, event);
752
+ return {
753
+ events: [...bySeq.values()].sort((a, b) => a.seq - b.seq),
754
+ malformed
755
+ };
756
+ }
757
+ //#endregion
758
+ //#region lib/types/fuzzy-match.js
759
+ /**
760
+ * Fuzzy string matching and replacement for patch/restructure edits of skill files.
761
+ *
762
+ * Split out of skill-store.ts (S2-1): pure text functions with no store state.
763
+ * The store imports the scan, the budgets and the replace entry points directly;
764
+ * none of them is re-exported, so the package export surface is unchanged.
765
+ */
766
+ function fuzzyIndexOf(content, pattern, from = 0) {
767
+ const isSpace = (char) => char !== void 0 && /[ \t]/.test(char);
768
+ const escaped = (char) => {
769
+ if (char === "n") return "\n";
770
+ if (char === "t") return " ";
771
+ if (char === "r") return "\r";
772
+ return null;
773
+ };
774
+ for (let start = from; start < content.length; start += 1) {
775
+ let contentIndex = start;
776
+ let patternIndex = 0;
777
+ while (patternIndex < pattern.length && contentIndex < content.length) {
778
+ const patternChar = pattern[patternIndex];
779
+ const contentChar = content[contentIndex];
780
+ if (isSpace(patternChar)) {
781
+ while (patternIndex < pattern.length && isSpace(pattern[patternIndex])) patternIndex += 1;
782
+ while (contentIndex < content.length && isSpace(content[contentIndex])) contentIndex += 1;
783
+ continue;
784
+ }
785
+ const escapedChar = patternChar === "\\" ? escaped(pattern[patternIndex + 1]) : null;
786
+ if (escapedChar !== null && contentChar === escapedChar) {
787
+ patternIndex += 2;
788
+ contentIndex += 1;
789
+ continue;
790
+ }
791
+ if (patternChar === contentChar) {
792
+ contentIndex += 1;
793
+ patternIndex += 1;
794
+ continue;
795
+ }
796
+ break;
797
+ }
798
+ if (patternIndex === pattern.length) return [start, contentIndex];
799
+ }
800
+ return null;
801
+ }
802
+ /** V6-17 (0.3.37): the fuzzy-patch scan is O(n·m) with no input bound; a
803
+ * non-exact anchor past these budgets would block the event loop (measured
804
+ * ~6s at 20k×20k). Exact matches go through the fast `includes` path and stay
805
+ * allowed regardless of size. */
806
+ const FUZZY_MAX_PATTERN_CHARS = 4096;
807
+ const FUZZY_MAX_WORK = 8e6;
808
+ /** Trim leading whitespace of the first line and trailing whitespace of the last line. */
809
+ function trimPatternBoundaries(pattern) {
810
+ const from = pattern.search(/\S/);
811
+ const trimmed = from < 0 ? pattern : pattern.slice(from);
812
+ const trailing = trimmed.search(/\s+$/);
813
+ return trailing < 0 ? trimmed : trimmed.slice(0, trailing);
814
+ }
815
+ /** Replace only the fuzzy-matched span, preserving all surrounding bytes.
816
+ * V7-11 (0.3.44): the replaceAll loop accumulates the per-scan cost — the
817
+ * single-scan budget at the caller only bounded ONE fuzzyIndexOf, while an
818
+ * unbounded number of matches × O(n·m) each could still stall the loop.
819
+ * When the accumulated cost exceeds the budget the whole replace fails
820
+ * (null) instead of partially applying an arbitrary prefix. */
821
+ function fuzzyReplace(content, oldString, newString, replaceAll) {
822
+ let current = content;
823
+ let scanFrom = 0;
824
+ let totalWork = 0;
825
+ for (;;) {
826
+ totalWork += current.length * oldString.length;
827
+ if (totalWork > 8e6) return null;
828
+ const match = fuzzyIndexOf(current, oldString, scanFrom);
829
+ if (match === null) return current;
830
+ const [start, end] = match;
831
+ const next = current.slice(0, start) + newString + current.slice(end);
832
+ if (!replaceAll) return next;
833
+ current = next;
834
+ scanFrom = start + newString.length;
835
+ }
836
+ }
837
+ function fuzzyPatch(content, oldString, newString, replaceAll = false) {
838
+ if (oldString === "") return null;
839
+ if (content.includes(oldString)) return replaceAll ? content.split(oldString).join(newString) : content.replace(oldString, () => newString);
840
+ const boundary = trimPatternBoundaries(oldString);
841
+ if (boundary === "") return null;
842
+ if (boundary !== oldString) {
843
+ if (fuzzyIndexOf(content, boundary) !== null) return fuzzyReplace(content, boundary, newString, replaceAll);
844
+ }
845
+ if (fuzzyIndexOf(content, oldString) !== null) return fuzzyReplace(content, oldString, newString, replaceAll);
846
+ return null;
847
+ }
848
+ /** Deterministic section-extraction plan facts; the caller owns the IO and the append semantics. */
849
+ //#endregion
850
+ //#region lib/types/serial.js
851
+ /**
852
+ * A process-local serial task queue: each task starts only after the previous
853
+ * one settles (success or failure), so read-modify-write sequences that share
854
+ * one file never interleave inside this process. When the IO backend provides
855
+ * a cross-process transact lock, that is the first layer; the node backend does
856
+ * not, so this chain is its only serialization. (0.3.17 S2.8, T-1: the shape was
857
+ * duplicated in state-json and
858
+ * memory-files — one factory now).
859
+ */
860
+ function makeSerialQueue() {
861
+ let chain = Promise.resolve();
862
+ return (task) => {
863
+ const run = chain.then(task, task);
864
+ chain = run.then(() => void 0, () => void 0);
865
+ return run;
866
+ };
867
+ }
868
+ //#endregion
869
+ //#region lib/types/threats.js
870
+ /**
871
+ * Threat scanning for agent-authored memory and skill content.
872
+ *
873
+ * Ported as a small, dependency-free subset of Hermes Agent's
874
+ * `tools/threat_patterns.py` + hermes-claw `threats.ts`.
875
+ *
876
+ * Policy (P1-1, v19): a finding either BLOCKS the write or only REPORTS.
877
+ * Blocking is reserved for shapes with no legitimate use in stored knowledge
878
+ * (prompt-injection phrasing, credential exfiltration, the invisible-character
879
+ * smuggling core). Typography and presentation characters that are legitimate
880
+ * in ordinary prose — variation selectors (❤️), zero-width non-joiner, soft
881
+ * hyphen from PDF paste, Arabic letter mark, Mongolian vowel separator — are
882
+ * REPORT findings: they stay visible to operators and tests but never reject a
883
+ * write. Blocking them turned every emoji into a security event.
884
+ */
885
+ const FILLER = String.raw`(?:\w+\s+){0,8}`;
886
+ const PATTERNS = [
887
+ {
888
+ label: "prompt_injection_ignore",
889
+ category: "prompt_injection",
890
+ scope: "all",
891
+ regex: new RegExp(String.raw`ignore\s+${FILLER}(?:previous|above|prior|all)\s+${FILLER}instructions`, "i")
892
+ },
893
+ {
894
+ label: "disregard_rules",
895
+ category: "prompt_injection",
896
+ scope: "all",
897
+ regex: new RegExp(String.raw`disregard\s+${FILLER}(?:your|all|any)\s+${FILLER}(?:instructions|rules|guidelines)`, "i")
898
+ },
899
+ {
900
+ label: "system_prompt_override",
901
+ category: "prompt_injection",
902
+ scope: "all",
903
+ regex: /system\s+prompt\s+override/i
904
+ },
905
+ {
906
+ label: "bypass_restrictions",
907
+ category: "prompt_injection",
908
+ scope: "all",
909
+ regex: /act\s+as\s+(?:if|though)\s+(?:you\s+)?(?:have\s+no|don'?t\s+have)\s+(?:restrictions?|limits?|rules)/i
910
+ },
911
+ {
912
+ label: "new_system_prompt",
913
+ category: "prompt_injection",
914
+ scope: "strict",
915
+ regex: new RegExp(String.raw`new\s+${FILLER}system\s+${FILLER}prompt`, "i")
916
+ },
917
+ {
918
+ label: "forget_everything",
919
+ category: "prompt_injection",
920
+ scope: "strict",
921
+ regex: new RegExp(String.raw`forget\s+${FILLER}(?:everything|all)\s+${FILLER}(?:discussed|you\s+know)`, "i")
922
+ },
923
+ {
924
+ label: "role_hijack",
925
+ category: "role_hijacking",
926
+ scope: "context",
927
+ regex: /you\s+are\s+now\s+(?:a|an|the|acting|playing|pretending)/i
928
+ },
929
+ {
930
+ label: "fake_update",
931
+ category: "role_hijacking",
932
+ scope: "context",
933
+ regex: new RegExp(String.raw`you\s+have\s+been\s+${FILLER}(?:updated|upgraded|patched)\s+to`, "i")
934
+ },
935
+ {
936
+ label: "identity_override",
937
+ category: "role_hijacking",
938
+ scope: "context",
939
+ regex: /\bname\s+yourself\s+\w+/i
940
+ },
941
+ {
942
+ label: "remove_filters",
943
+ category: "role_hijacking",
944
+ scope: "context",
945
+ regex: /(?:respond|answer|reply)\s+without\s+(?:restrictions?|limitations?|filters?|safety)/i
946
+ },
947
+ {
948
+ label: "deception_hide",
949
+ category: "deception",
950
+ scope: "all",
951
+ regex: new RegExp(String.raw`do\s+not\s+${FILLER}tell\s+${FILLER}the\s+user`, "i")
952
+ },
953
+ {
954
+ label: "leak_system_prompt",
955
+ category: "deception",
956
+ scope: "context",
957
+ regex: new RegExp(String.raw`output\s+${FILLER}(?:system|initial)\s+prompt`, "i")
958
+ },
959
+ {
960
+ label: "context_exfil",
961
+ category: "exfiltration",
962
+ scope: "strict",
963
+ regex: /(?:include|output|print|share)\s+(?:the\s+)?(?:conversation|chat\s+history|previous\s+messages|(?:full|entire)\s+context)/i
964
+ },
965
+ {
966
+ label: "send_to_url",
967
+ category: "exfiltration",
968
+ scope: "strict",
969
+ regex: /(?:send|post|upload|transmit)\s+[\s\S]{0,512}?\s+(?:to|at)\s+https?:\/\//i
970
+ },
971
+ {
972
+ label: "exfil_curl",
973
+ category: "exfiltration",
974
+ scope: "all",
975
+ regex: /\bcurl\s+[\s\S]{0,512}?\$\{?\w*(?:KEY|TOKEN|SECRET|PASSWORD|CREDENTIAL|API)/i
976
+ },
977
+ {
978
+ label: "exfil_wget",
979
+ category: "exfiltration",
980
+ scope: "all",
981
+ regex: /\bwget\s+[\s\S]{0,512}?\$\{?\w*(?:KEY|TOKEN|SECRET|PASSWORD|CREDENTIAL|API)/i
982
+ },
983
+ {
984
+ label: "read_secrets",
985
+ category: "exfiltration",
986
+ scope: "all",
987
+ regex: /\bcat\s+[^\n]{0,512}(?:\.env(?!\w)(?!\.(?:[\w-]+\.)*(?:example|sample)(?=$|[\s"']))|(?:\bcredentials\b)|\.netrc|\.pgpass|\.npmrc|\.pypirc)/i
988
+ },
989
+ {
990
+ label: "ssh_backdoor",
991
+ category: "persistence",
992
+ scope: "strict",
993
+ regex: /\bauthorized_keys\b/i
994
+ },
995
+ {
996
+ label: "agent_config_mod",
997
+ category: "persistence",
998
+ scope: "strict",
999
+ regex: /(?:update|modify|edit|write|change|append|add\s+to)\s+(?:AGENTS\.md|CLAUDE\.md|\.cursorrules|\.clinerules)/i
1000
+ },
1001
+ {
1002
+ label: "hermes_env",
1003
+ category: "persistence",
1004
+ scope: "strict",
1005
+ regex: /\$?HOME\/\.hermes|~\/\.hermes|\.hermes\/\.env|%USERPROFILE%[\\/]\.hermes/i
1006
+ },
1007
+ {
1008
+ label: "c2_node_registration",
1009
+ category: "c2_promptware",
1010
+ scope: "context",
1011
+ regex: /register\s+(?:as\s+)?a?\s*node/i
1012
+ },
1013
+ {
1014
+ label: "c2_heartbeat",
1015
+ category: "c2_promptware",
1016
+ scope: "context",
1017
+ regex: /(?:heartbeats?|beacon|check[\s-]?in)\s+(?:to|with)/i
1018
+ },
1019
+ {
1020
+ label: "c2_task_pull",
1021
+ category: "c2_promptware",
1022
+ scope: "context",
1023
+ regex: /pull\s+(?:new\s+)?tasks?/i
1024
+ },
1025
+ {
1026
+ label: "known_c2_framework",
1027
+ category: "c2_promptware",
1028
+ scope: "context",
1029
+ regex: /\b(?:cobalt\s*strike|sliver|havoc|mythic|metasploit|brainworm)\b/i
1030
+ },
1031
+ {
1032
+ label: "hardcoded_secret",
1033
+ category: "hardcoded_secrets",
1034
+ scope: "strict",
1035
+ regex: /(?:api[_-]?key|token|secret|password)\s*[=:]\s*["'][a-z0-9+/=_-]{20,}["']/i
1036
+ },
1037
+ {
1038
+ label: "jwt_like_secret",
1039
+ category: "hardcoded_secrets",
1040
+ scope: "strict",
1041
+ regex: /\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/
1042
+ },
1043
+ {
1044
+ label: "private_key_block",
1045
+ category: "hardcoded_secrets",
1046
+ scope: "all",
1047
+ regex: /-----BEGIN\s+(?:(?:RSA|EC|DSA|OPENSSH|ENCRYPTED|PGP)\s+)?PRIVATE\s+KEY(?:\s+BLOCK)?-----/
1048
+ },
1049
+ {
1050
+ label: "prompt_injection_ignore_zh",
1051
+ category: "prompt_injection",
1052
+ scope: "all",
1053
+ regex: /(?:忽略|无视|抛开)[\s\S]{0,8}(?:之前|以上|上面|先前|以前)?[\s\S]{0,8}(?:所有|全部|任何)?[\s\S]{0,4}(?:指令|规则|设定|约束)/
1054
+ },
1055
+ {
1056
+ label: "deception_hide_zh",
1057
+ category: "deception",
1058
+ scope: "all",
1059
+ regex: /(?:不要|别|勿)(?:告诉|告知|透露)(?:给)?[\s\S]{0,6}(?:用户|任何人|主人|开发者)/
1060
+ },
1061
+ {
1062
+ label: "system_prompt_leak_zh",
1063
+ category: "deception",
1064
+ scope: "context",
1065
+ regex: /(?:泄露|输出|打印|透露|导出)[\s\S]{0,10}系统提示|系统提示[\s\S]{0,10}(?:泄露|透露|发送|导出)/
1066
+ },
1067
+ {
1068
+ label: "context_exfil_zh",
1069
+ category: "exfiltration",
1070
+ scope: "strict",
1071
+ regex: /(?:对话记录|聊天记录|全部上下文|完整上下文)[\s\S]{0,30}(?:发送|上传|传输|外传|泄露)[\s\S]{0,30}(?:到|至|给)/
1072
+ },
1073
+ {
1074
+ label: "secret_exfil_zh",
1075
+ category: "exfiltration",
1076
+ scope: "strict",
1077
+ regex: /(?:密钥|凭据|口令|密码|环境变量)[\s\S]{0,30}(?:发送|上传|传输|外传|泄露)[\s\S]{0,30}(?:到|至)\s*(?:https?:\/\/|[\w.-]+\.(?:com|net|org|io|cn|dev|xyz|ru)\b)/
1078
+ }
1079
+ ];
1080
+ const ZERO_WIDTH_CHARS = new RegExp(`[\\u034f\\u200b\\u2060\\u2061\\u2062\\u2063\\u2064\\u206a-\\u206f\\ufeff\\u{e0000}-\\u{e007f}]`, "u");
1081
+ const ZWJ_OUTSIDE_EMOJI = /(?<!\p{Extended_Pictographic})\u200d(?!\p{Extended_Pictographic})/u;
1082
+ const TYPOGRAPHY_CHARS = /[\u00ad\u061c\u180e\u200c\ufe00-\ufe0f]/;
1083
+ const BIDI_CHARS = /[\u202a-\u202e\u2066-\u2069]/;
1084
+ const FORMAT_CONTROL_CLASS = "\\p{Cf}\\p{Zl}\\p{Zp}\\u0000\\u2065\\ufff0-\\ufff8\\u{e0080}-\\u{e00ff}";
1085
+ const FORMAT_CONTROL_TEST = new RegExp(`[${FORMAT_CONTROL_CLASS}]`, "u");
1086
+ /** S0.4 (v37 P0-3): a format control the three finding sets above do NOT report.
1087
+ * S1-E3: the ZWJ exemption compares the real character. It used to read
1088
+ * `'\\u200d'` — a 6-character literal that never equals a code point — so the
1089
+ * branch was dead and every emoji ZWJ sequence (👨‍👩‍👧) raised the report-level
1090
+ * `unicode_format_control` finding the class comment above promises it will not. */
1091
+ function hasUnreportedFormatControl(text) {
1092
+ for (const character of text) {
1093
+ if (!FORMAT_CONTROL_TEST.test(character)) continue;
1094
+ if (ZERO_WIDTH_CHARS.test(character) || TYPOGRAPHY_CHARS.test(character) || BIDI_CHARS.test(character)) continue;
1095
+ if (character === "‍") continue;
1096
+ return true;
1097
+ }
1098
+ return false;
1099
+ }
1100
+ const SCOPE_ORDER = {
1101
+ all: 1,
1102
+ context: 2,
1103
+ strict: 3
1104
+ };
1105
+ const NO_SCAN_OPTIONS = {};
1106
+ /** Minimum window size for the full-coverage scan (V6-05, 0.3.35). With the
1107
+ * proportional half-window step below, the overlap is `ceil(w/2)` — only a
1108
+ * window at or above this floor keeps the overlap above the longest pattern
1109
+ * span (~530 chars: `curl [^\n]{0,512} ...`), so a match straddling a window
1110
+ * boundary is fully inside at least one window (E-12, 0.3.16). The clamp
1111
+ * falls back to the default for a smaller caller value instead of risking a
1112
+ * blind zone. */
1113
+ const PATTERN_OVERLAP = 4096;
1114
+ /**
1115
+ * Scan text at `scope`. Patterns are cumulative: `strict` includes all scopes.
1116
+ * `options.excludeLabels` removes matching patterns without changing `scope`.
1117
+ * `maxScanChars` is the WINDOW SIZE, not a total cap (E-12, 0.3.16): the whole
1118
+ * text is always scanned in overlapping windows, so content beyond 65,536
1119
+ * characters (skill files may run to 100,000) is no longer a blind zone.
1120
+ */
1121
+ function scanThreats(text, scope = "strict", maxScanChars = DEFAULT_THREAT_MAX_SCAN_CHARS, options = NO_SCAN_OPTIONS) {
1122
+ const windowSize = clampedNumber(maxScanChars, DEFAULT_THREAT_MAX_SCAN_CHARS, { min: 4097 });
1123
+ const findings = [];
1124
+ const excluded = new Set(options.excludeLabels ?? []);
1125
+ if ((ZERO_WIDTH_CHARS.test(text) || ZWJ_OUTSIDE_EMOJI.test(text)) && !excluded.has("unicode_zero_width")) findings.push({
1126
+ label: "unicode_zero_width",
1127
+ category: "unicode_obfuscation",
1128
+ scope: "all"
1129
+ });
1130
+ if (TYPOGRAPHY_CHARS.test(text) && !excluded.has("unicode_typography")) findings.push({
1131
+ label: "unicode_typography",
1132
+ category: "unicode_obfuscation",
1133
+ scope: "all",
1134
+ severity: "report"
1135
+ });
1136
+ if (BIDI_CHARS.test(text) && !excluded.has("unicode_bidi_override")) findings.push({
1137
+ label: "unicode_bidi_override",
1138
+ category: "unicode_obfuscation",
1139
+ scope: "all"
1140
+ });
1141
+ if (!excluded.has("unicode_format_control") && hasUnreportedFormatControl(text)) findings.push({
1142
+ label: "unicode_format_control",
1143
+ category: "unicode_obfuscation",
1144
+ scope: "all",
1145
+ severity: "report"
1146
+ });
1147
+ const normalized = text.normalize("NFKC");
1148
+ const SPACE_SPLITTERS = /[\u00ad\u061c\u180e\u200c\ufe00-\ufe0f]/gu;
1149
+ const OBFUSCATION_SPLITTERS = new RegExp(`[${FORMAT_CONTROL_CLASS}]`, "gu");
1150
+ const patternTexts = [normalized.replace(SPACE_SPLITTERS, " ").replace(OBFUSCATION_SPLITTERS, " "), normalized.replace(SPACE_SPLITTERS, "").replace(OBFUSCATION_SPLITTERS, "")];
1151
+ const windows = [];
1152
+ for (const patternText of patternTexts) if (patternText.length <= windowSize) windows.push(patternText);
1153
+ else {
1154
+ const step = Math.max(Math.floor(windowSize / 2), 1);
1155
+ for (let start = 0; start < patternText.length; start += step) windows.push(patternText.slice(start, start + windowSize));
1156
+ }
1157
+ const seen = /* @__PURE__ */ new Set();
1158
+ for (const window of windows) for (const pattern of PATTERNS) {
1159
+ if (SCOPE_ORDER[pattern.scope] > SCOPE_ORDER[scope]) continue;
1160
+ if (excluded.has(pattern.label)) continue;
1161
+ if (!pattern.regex.test(window)) continue;
1162
+ const key = `${pattern.label}|${pattern.scope}`;
1163
+ if (seen.has(key)) continue;
1164
+ seen.add(key);
1165
+ findings.push({
1166
+ label: pattern.label,
1167
+ category: pattern.category,
1168
+ scope: pattern.scope
1169
+ });
1170
+ }
1171
+ return findings;
1172
+ }
1173
+ /** Blocking policy (P1-1, v19): a finding blocks unless it is explicitly
1174
+ * `report`-only. Pattern findings carry no severity and therefore block as
1175
+ * before. */
1176
+ function evaluateThreat(text, scope = "strict", maxScanChars = DEFAULT_THREAT_MAX_SCAN_CHARS, options = NO_SCAN_OPTIONS) {
1177
+ const findings = scanThreats(text, scope, maxScanChars, options);
1178
+ return {
1179
+ blocked: findings.some((finding) => finding.severity !== "report"),
1180
+ findings
1181
+ };
1182
+ }
1183
+ /** User-facing block message for memory writes. */
1184
+ function scanMemoryThreats(text, maxScanChars = DEFAULT_THREAT_MAX_SCAN_CHARS, options = NO_SCAN_OPTIONS) {
1185
+ const { blocked, findings } = evaluateThreat(text, "strict", maxScanChars, options);
1186
+ if (!blocked) return null;
1187
+ const pattern = findings.find((f) => f.category !== "unicode_obfuscation");
1188
+ if (pattern) return `Blocked by security scan (${pattern.label}). Rephrase without instruction-like language.${THREAT_EXEMPTION_HINT}`;
1189
+ return `Blocked by security scan: invisible or potentially malicious Unicode detected.${THREAT_EXEMPTION_HINT}`;
1190
+ }
1191
+ /** User-facing block message for skill content writes. */
1192
+ function scanContentThreats(text, maxScanChars = DEFAULT_THREAT_MAX_SCAN_CHARS, options = NO_SCAN_OPTIONS) {
1193
+ const { blocked, findings } = evaluateThreat(text, "strict", maxScanChars, options);
1194
+ if (!blocked) return null;
1195
+ const pattern = findings.find((f) => f.category !== "unicode_obfuscation");
1196
+ if (pattern) return `Blocked by security scan (${pattern.label}). This content appears to contain potentially malicious instructions.${THREAT_EXEMPTION_HINT}`;
1197
+ return `Blocked by security scan: invisible or potentially malicious Unicode detected. This content appears to contain potentially malicious instructions.${THREAT_EXEMPTION_HINT}`;
1198
+ }
1199
+ /**
1200
+ * WD2 (0.3.56): the shared tail of every user-facing threat block — names the
1201
+ * deployable self-heal path so the model (or operator) can allowlist a
1202
+ * known-benign label. v20 (B-2) single source: the scan builders embed this
1203
+ * constant verbatim; do NOT re-word it per call site (the three former copies
1204
+ * — memory inline, content inline, and the dead `THREAT_EXEMPT_HINT` export,
1205
+ * whose docblock still claimed a store-side append that memory-store/skill-store
1206
+ * had already removed — had drifted apart). The evolution-threat guard channel
1207
+ * returns the scan message verbatim, so the hint rides along there too.
1208
+ */
1209
+ const THREAT_EXEMPTION_HINT = " A deployment that needs a specific label can exempt it via threatExemptLabels (see the README env/dial reference).";
1210
+ //#endregion
1211
+ //#region lib/types/review-channel.js
1212
+ /**
1213
+ * Family-internal mark for the review channel's INJECT delivery (v37 S2.2).
1214
+ *
1215
+ * With the default `reviewMode: 'inject'` the review prompt runs in the PARENT
1216
+ * session, so the parent model's own `skill_manage` calls carry no origin the
1217
+ * platform could attribute: `.pinned` and the `.hermes-managed` authorship mark
1218
+ * were skipped for exactly the autonomous writes they exist for. The delivery
1219
+ * marks the session here and the write path reads the mark.
1220
+ *
1221
+ * Window: after the review prompt, until the next REAL user message (a
1222
+ * `user/message` with `source.kind === 'user'` clears it; plugin-sourced notices
1223
+ * never do). Process-wide and keyed by session on purpose — the same
1224
+ * "restart is a fresh conversation boundary" discipline as the review plugin's
1225
+ * own per-session counters. This module is the ONE owner of the marker.
1226
+ * @module @lmzhen/dsh-evolution-core/review-channel
1227
+ */
1228
+ /** Session ids currently executing a review prompt, oldest delivery first. */
1229
+ const MARK_KEY = Symbol.for("dsh.evolution.review-channel.marked");
1230
+ const registry$1 = globalThis;
1231
+ const markedSessions = registry$1[MARK_KEY] ?? (registry$1[MARK_KEY] = /* @__PURE__ */ new Set());
1232
+ /**
1233
+ * Mark one session as running the review channel's prompt; idempotent, and
1234
+ * keyed by session so a mark can never leak into another session.
1235
+ * @param sessionId - the session the review prompt was delivered to.
1236
+ */
1237
+ function markReviewChannel(sessionId) {
1238
+ markedSessions.delete(sessionId);
1239
+ markedSessions.add(sessionId);
1240
+ }
1241
+ /**
1242
+ * Clear the mark: the session's next prompt is human input again.
1243
+ * @param sessionId - the session whose mark is dropped.
1244
+ */
1245
+ function clearReviewChannel(sessionId) {
1246
+ markedSessions.delete(sessionId);
1247
+ }
1248
+ /**
1249
+ * Whether this session's current prompt came from the review channel. An
1250
+ * execution without a session is never the review channel.
1251
+ * @param sessionId - the executing session id, when the caller has one.
1252
+ * @returns true only for a marked session.
1253
+ */
1254
+ function isReviewChannelSession(sessionId) {
1255
+ return sessionId !== void 0 && markedSessions.has(sessionId);
1256
+ }
1257
+ /**
1258
+ * Drop marks whose session is gone — a dead session cannot execute a write.
1259
+ * @param isAlive - liveness probe for one session id.
1260
+ * @returns the number of removed marks.
1261
+ */
1262
+ function sweepReviewChannelSessions(isAlive) {
1263
+ let removed = 0;
1264
+ for (const sessionId of [...markedSessions]) {
1265
+ if (isAlive(sessionId)) continue;
1266
+ markedSessions.delete(sessionId);
1267
+ removed += 1;
1268
+ }
1269
+ return removed;
1270
+ }
1271
+ //#endregion
1272
+ //#region lib/types/review-context.js
1273
+ /**
1274
+ * Plugin-local review execution context.
1275
+ *
1276
+ * This is deliberately not a platform API: the family review executor wraps one
1277
+ * bounded tool loop, and the write tools read the context to attribute writes as
1278
+ * background_review without relying on a Session header or a global mark.
1279
+ *
1280
+ * @module @lmzhen/dsh-evolution-core/review-context
1281
+ */
1282
+ const STORAGE_KEY = Symbol.for("dsh.evolution.review-context.storage");
1283
+ const registry = globalThis;
1284
+ const storage = registry[STORAGE_KEY] ?? (registry[STORAGE_KEY] = new AsyncLocalStorage());
1285
+ /**
1286
+ * Run one review tool loop under the review write context.
1287
+ * @param context - review/run identity.
1288
+ * @param task - loop body; nested tool executions inherit the context.
1289
+ * @returns the task's value.
1290
+ */
1291
+ function withReviewContext(context, task) {
1292
+ return storage.run(Object.freeze({ ...context }), task);
1293
+ }
1294
+ /**
1295
+ * The active review context, when the current async execution belongs to a review loop.
1296
+ * @returns the frozen context, or undefined outside a review loop.
1297
+ */
1298
+ function currentReviewContext() {
1299
+ return storage.getStore();
1300
+ }
1301
+ /**
1302
+ * Record a successful skill read in the CURRENT review run. A no-op outside a
1303
+ * review loop or when the run has no read set.
1304
+ * @param name - the skill name the review actually loaded.
1305
+ */
1306
+ function recordReviewRead(name) {
1307
+ const context = storage.getStore();
1308
+ if (context?.reads === void 0 || name.trim() === "") return;
1309
+ context.reads.add(name.trim());
1310
+ }
1311
+ //#endregion
1312
+ //#region lib/types/skill-health.js
1313
+ /**
1314
+ * Skill structure-health domain (rc.73 A1, 008 design): a SECOND assessment
1315
+ * dimension beside the six-factor usage quality — document hygiene, consumed
1316
+ * by the curator health view and the `/evolution skills health` command.
1317
+ *
1318
+ * PURE and DERIVED: nothing is persisted; every assessment is computed from
1319
+ * file facts at read time. The judgment split follows the original's
1320
+ * boundary/治理 layering — deterministic signals here, refinement proposals
1321
+ * stay in the review/curator judgment layer. Never become a 7th factor of
1322
+ * `computeQualityScores` (different dimension, different consumers).
1323
+ */
1324
+ const DEFAULT_HEALTH_THRESHOLDS = {
1325
+ softBodyChars: AUTHORING_SPLIT_LINE_CHARS,
1326
+ stampDensityPerKb: 2,
1327
+ churnMinPatches: 20,
1328
+ hardCapMinHits: 3
1329
+ };
1330
+ /**
1331
+ * Stamp regex shared by health assessment and the maintenance probe (single
1332
+ * source, 011). Two refinements over the naive form (F-320): the hex branch
1333
+ * requires at least one digit so coincidental all-letter English words
1334
+ * (`defaced`, `feedback`) are not counted as commit shas; the ISO branch
1335
+ * accepts a UTC `Z`, a numeric UTC offset (`+08:00`), or no timezone at all —
1336
+ * non-UTC timestamps used to escape detection (log-like content missed).
1337
+ *
1338
+ * Known boundary, recorded not fixed (C-22, v10 audit): the hex branch also
1339
+ * matches 7-40 char PURE-DIGIT strings (order numbers etc.), so stamp density
1340
+ * can be over-reported for such content. The misjudgment direction is "extra
1341
+ * stamp hits" only — never a miss — and no real incident exists; revisit only
1342
+ * if curator decisions are actually distorted (v10 deferral ledger).
1343
+ */
1344
+ 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");
1345
+ /**
1346
+ * Bodies below this size skip stamp-density assessment: a few dates or shas
1347
+ * in a short body are ordinary documentation, not log-like content. With the
1348
+ * 1KB density floor a 3-date sentence in a small skill measured 3.0/KB and
1349
+ * warned on a perfectly healthy body (audit 2026-08-31 X1).
1350
+ */
1351
+ const MIN_STAMP_BODY_CHARS = 2e3;
1352
+ /**
1353
+ * The findings for ONE body, computed by the engine that owns the judgement (G4).
1354
+ *
1355
+ * Deliberately a thin call into `assessStructureHealth`: a later consumer (the write receipt) needs
1356
+ * findings for a body it is about to store, and re-deriving the facts anywhere else would be a
1357
+ * SECOND judgement — the token-scale line, the /1024 stamp density and the soft/2 support threshold
1358
+ * all live in one place and must stay there.
1359
+ * @param skillName - the skill the body belongs to (used in messages).
1360
+ * @param content - the WHOLE SKILL.md text, frontmatter included (the engine's own convention).
1361
+ * @param supportGroups - non-empty support dirs; pass the real count, never a guess.
1362
+ * @param thresholds - the configured thresholds; defaults to the shipped ones.
1363
+ * @returns the findings, in rule order.
1364
+ */
1365
+ function lintBody(skillName, content, supportGroups, thresholds = DEFAULT_HEALTH_THRESHOLDS) {
1366
+ return assessStructureHealth({
1367
+ skillName,
1368
+ bodyChars: content.length,
1369
+ bodyText: content,
1370
+ supportGroups
1371
+ }, thresholds).findings;
1372
+ }
1373
+ function assessStructureHealth(snapshot, thresholds = DEFAULT_HEALTH_THRESHOLDS) {
1374
+ const dims = {
1375
+ bodyChars: snapshot.bodyChars,
1376
+ bodyTokens: Math.round(snapshot.bodyChars / UPSTREAM_LIMIT_CHARS_PER_TOKEN),
1377
+ stampDensityPerKb: null,
1378
+ stampHits: null,
1379
+ supportGroups: snapshot.supportGroups,
1380
+ supportFiles: snapshot.supportFiles ?? null,
1381
+ churnPatches: null,
1382
+ churnReads: null,
1383
+ hardCapHits: snapshot.hardCapHits ?? null
1384
+ };
1385
+ const text = snapshot.bodyText;
1386
+ const cost = typeof text === "string" && text.length > 0 ? bodyCost(text) : null;
1387
+ const lineTokens = cost === null ? null : tokenLineFor(thresholds.softBodyChars, cost);
1388
+ dims.bodyTokens = cost === null ? Math.round(snapshot.bodyChars / UPSTREAM_LIMIT_CHARS_PER_TOKEN) : cost.tokens;
1389
+ const overLine = cost === null || lineTokens === null ? snapshot.bodyChars >= thresholds.softBodyChars : cost.tokens >= lineTokens;
1390
+ const overTwice = cost === null || lineTokens === null ? snapshot.bodyChars >= thresholds.softBodyChars * 2 : cost.tokens >= lineTokens * 2;
1391
+ if (snapshot.bodyText && snapshot.bodyChars >= 2e3) {
1392
+ const kb = Math.max(1, snapshot.bodyChars / 1024);
1393
+ const stamps = (snapshot.bodyText.match(HEALTH_STAMP_RE) ?? []).length;
1394
+ dims.stampDensityPerKb = stamps / kb;
1395
+ dims.stampHits = stamps;
1396
+ }
1397
+ if (snapshot.patchCount !== void 0 && snapshot.readCount !== void 0) {
1398
+ dims.churnPatches = snapshot.patchCount;
1399
+ dims.churnReads = snapshot.readCount;
1400
+ }
1401
+ const findings = lintSkill({
1402
+ skillName: snapshot.skillName,
1403
+ dims,
1404
+ softLineChars: thresholds.softBodyChars,
1405
+ overSoftLine: overLine,
1406
+ overTwiceSoftLine: overTwice,
1407
+ stampLimitPerKb: thresholds.stampDensityPerKb,
1408
+ churnMinPatches: thresholds.churnMinPatches,
1409
+ hardCapMinHits: thresholds.hardCapMinHits,
1410
+ readable: true
1411
+ });
1412
+ return {
1413
+ verdict: findings.some((f) => f.rule === "body-oversize-2x") ? "needs-restructure" : findings.length > 0 ? "warn" : "healthy",
1414
+ dims,
1415
+ findings
1416
+ };
1417
+ }
1418
+ //#endregion
1419
+ 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 };