@lmzhen/dsh-evolution-core 0.54.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 (50) 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 +1 -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/signals.js +3 -2
  32. package/lib/types/skill-health.d.ts +8 -5
  33. package/lib/types/skill-health.js +27 -28
  34. package/lib/types/skill-history.d.ts +2 -2
  35. package/lib/types/skill-history.js +7 -7
  36. package/lib/types/skill-lint.d.ts +1 -1
  37. package/lib/types/skill-lint.js +4 -4
  38. package/lib/types/skill-stats.d.ts +3 -1
  39. package/lib/types/skill-stats.js +2 -0
  40. package/lib/types/skill-store.js +2 -1
  41. package/lib/types/text-budgets.d.ts +150 -0
  42. package/lib/types/text-budgets.js +65 -0
  43. package/lib/types/text-metrics.d.ts +88 -0
  44. package/lib/types/text-metrics.js +131 -0
  45. package/lib/{usage-B1qveKi9.js → usage-e34VZPmK.js} +2 -515
  46. package/lib/write.js +3 -2
  47. package/package.json +1 -1
  48. package/lib/mutations-DQXddSJd.js +0 -75
  49. package/lib/types/cost.d.ts +0 -63
  50. package/lib/types/cost.js +0 -67
package/lib/index.js CHANGED
@@ -1,19 +1,21 @@
1
1
  import { S as reportTime, _ as probeMtime, a as isProcessAlive, b as probeText, c as transactIo, d as isAbsent, f as isMissingPath, g as probeList, h as probeAbsent, i as isCommittedWarning, l as writeDurableTmp, m as isUnknown, n as atomicWriteFiles, o as nodeEvolutionIo, p as isPresent, r as evolutionIoAdapter, s as renameWithRetry, t as TransactionNotInvokedError, u as declaredReportStamp, v as probePresent, x as probeUnknown, y as probeReason } from "./io-GxghO3Ip.js";
2
2
  import { a as leaseFile, c as AuthorityBusyError, d as HomeAuthority, f as authorityHolder, i as LeaseStore, l as AuthorityOrderError, n as mutationLockFrom, o as HomeFence, p as leaseAsTreeLock, r as DEFAULT_LEASE_TTL_MS, s as HomeFenceError, t as MutationAuthority, u as AuthorityReentryError } from "./mutation-authority-DQfpXs1O.js";
3
3
  import { a as isFileShapedPath, i as KEEP_LINE_RE, n as DEFAULT_CITATION_REF_BUDGET, o as resolveCitations, r as HOOK_LINE_RE, s as scanBodyHooks, t as CITATION_SUPPORT_DIRS } from "./citations-CZKTUGQF.js";
4
- import { A as DEFAULT_SUBSTANTIVE_MIN_USER_CHARS, B as MAX_TIMER_DELAY_MS, C as DEFAULT_SKILL_CONTENT_CHARS, D as DEFAULT_STALE_AFTER_DAYS, E as DEFAULT_SKILL_VERSION_KEEP, F as FORBIDDEN_CONTROL_KEYS, G as SKILL_NAME_RE, H as PROTECTED_BUILTIN_SKILLS, I as MAX_DESCRIPTION_LENGTH, J as UPSTREAM_LIMIT_CHARS_PER_TOKEN, K as SUPPORT_DIRS, L as MAX_SKILL_CONTENT_CHARS, M as DEFAULT_USER_CHAR_LIMIT, N as ENTRY_DELIMITER, O as DEFAULT_SUBSTANTIVE_MIN_AGENT_CHARS, P as EVOLUTION_WRITE_TOOLS, R as MAX_SKILL_FILE_BYTES, S as DEFAULT_REVIEW_TIMEOUT_MS, T as DEFAULT_SKILL_REVIEW_TRIGGER, U as SKILLS_GUIDANCE_SECTION_ORDER, V as MEMORY_GUIDANCE_SECTION_ORDER, W as SKILL_ACTION_REQUIRED_FIELDS, _ as DEFAULT_MEMORY_CHAR_LIMIT, a as DEFAULT_SUPPORT_FILE_CHAR_POLICY, b as DEFAULT_REVIEW_MEMORY_INTERVAL, c as AUTHORING_DESCRIPTION_BAR, d as DEFAULT_ARCHIVE_AFTER_DAYS, f as DEFAULT_CONSOLIDATION_FAILURES, g as DEFAULT_CURATOR_REVIEW_MAX_TOKENS, h as DEFAULT_CURATOR_MODEL, i as DEFAULT_SKILL_LIMITS, j as DEFAULT_THREAT_MAX_SCAN_CHARS, k as DEFAULT_SUBSTANTIVE_MIN_TOOL_CALLS, l as AUTHORING_SPLIT_LINE_CHARS, m as DEFAULT_CURATOR_INTERVAL_HOURS, n as DEFAULT_CITATION_POLICY, o as POLICY_STAGE_DEFAULTS, p as DEFAULT_CURATOR_BOOT_GRACE_SECONDS, q as SUPPORT_SPRAWL_FILES, r as DEFAULT_REFERENCE_REWRITE_POLICY, s as policyStageLimits, t as DEFAULT_ARCHIVE_RETENTION_POLICY, u as CONTENT_SPLIT_HINT, v as DEFAULT_MIN_IDLE_HOURS, w as DEFAULT_SKILL_REVIEW_COMPLETION_MIN_TOOL_CALLS, x as DEFAULT_REVIEW_SKILL_INTERVAL, y as DEFAULT_PROBE_TIMEOUT_MS, z as MAX_SKILL_NAME_LENGTH } from "./limits-TD4Pv92Q.js";
4
+ import { A as DEFAULT_SUBSTANTIVE_MIN_AGENT_CHARS, B as MAX_SKILL_CONTENT_CHARS, C as DEFAULT_REVIEW_TIMEOUT_MS, D as DEFAULT_SKILL_VERSION_KEEP, E as DEFAULT_SKILL_REVIEW_TRIGGER, F as DEFAULT_USER_TOKENS, G as PROTECTED_BUILTIN_SKILLS, H as MAX_SKILL_NAME_LENGTH, I as ENTRY_DELIMITER, J as SKILL_NAME_RE, K as SKILLS_GUIDANCE_SECTION_ORDER, L as EVOLUTION_WRITE_TOOLS, M as DEFAULT_SUBSTANTIVE_MIN_USER_CHARS, N as DEFAULT_THREAT_MAX_SCAN_CHARS, O as DEFAULT_SOFT_BODY_TOKENS, P as DEFAULT_USER_CHAR_LIMIT, R as FORBIDDEN_CONTROL_KEYS, S as DEFAULT_REVIEW_SKILL_INTERVAL, T as DEFAULT_SKILL_REVIEW_COMPLETION_MIN_TOOL_CALLS, U as MAX_TIMER_DELAY_MS, V as MAX_SKILL_FILE_BYTES, W as MEMORY_GUIDANCE_SECTION_ORDER, X as SUPPORT_SPRAWL_FILES, Y as SUPPORT_DIRS, Z as UPSTREAM_LIMIT_CHARS_PER_TOKEN, _ as DEFAULT_MEMORY_CHAR_LIMIT, a as DEFAULT_SUPPORT_FILE_CHAR_POLICY, b as DEFAULT_PROBE_TIMEOUT_MS, c as AUTHORING_DESCRIPTION_BAR, d as DEFAULT_ARCHIVE_AFTER_DAYS, f as DEFAULT_CONSOLIDATION_FAILURES, g as DEFAULT_CURATOR_REVIEW_MAX_TOKENS, h as DEFAULT_CURATOR_MODEL, i as DEFAULT_SKILL_LIMITS, j as DEFAULT_SUBSTANTIVE_MIN_TOOL_CALLS, k as DEFAULT_STALE_AFTER_DAYS, l as AUTHORING_SPLIT_LINE_CHARS, m as DEFAULT_CURATOR_INTERVAL_HOURS, n as DEFAULT_CITATION_POLICY, o as POLICY_STAGE_DEFAULTS, p as DEFAULT_CURATOR_BOOT_GRACE_SECONDS, q as SKILL_ACTION_REQUIRED_FIELDS, r as DEFAULT_REFERENCE_REWRITE_POLICY, s as policyStageLimits, t as DEFAULT_ARCHIVE_RETENTION_POLICY, u as CONTENT_SPLIT_HINT, v as DEFAULT_MEMORY_TOKENS, w as DEFAULT_SKILL_CONTENT_CHARS, x as DEFAULT_REVIEW_MEMORY_INTERVAL, y as DEFAULT_MIN_IDLE_HOURS, z as MAX_DESCRIPTION_LENGTH } from "./limits-DBg3UMkw.js";
5
5
  import { _ as scopedPackageName, d as RESTRICTED_TOOLS_ROW_ID, f as RESTRICTOR_MODULE, g as scopeOfNearestManifest, l as MAINTAINER_PRESET_ID, p as REVIEWER_PRESET_ID, s as EVOLUTION_PRESET_IDS, u as RESTRICTED_PRESET_DISPLAY } from "./ensure-BLmEW0Ju.js";
6
- import { $ as DEFAULT_WRITE_CONFIRM_TIMEOUT_SECONDS, A as evolutionEventPayloadIssue, B as COST_ASCII_TOKEN_LOW, C as trimPatternBoundaries, D as EVENT_LOG_VERSION, E as EVENT_LOG_ROTATE_AT, F as retainEventArchives, G as bodyCost, H as COST_CJK_TOKEN_LOW, I as RULES, K as tokenLineFor, M as parseEvolutionEvents, N as readEvolutionEvents, O as appendEvolutionEvent, P as readEvolutionTimeline, Q as DEFAULT_WRITE_CONFIRM_MODE, R as lintSkill, S as fuzzyPatch, T as EVENT_LOG_RETAIN_ARCHIVES, U as TOKEN_ASCII_WEIGHT, V as COST_CJK_TOKEN_HIGH, W as TOKEN_CJK_WEIGHT, Y as isUnreadWrite, _ as scanMemoryThreats, b as FUZZY_MAX_PATTERN_CHARS, c as withReviewContext, d as markReviewChannel, et as authorityFrom, f as sweepReviewChannelSessions, g as scanContentThreats, h as evaluateThreat, i as assessStructureHealth, j as listEventArchives, k as eventsFile, l as clearReviewChannel, m as THREAT_EXEMPTION_HINT, o as currentReviewContext, p as PATTERN_OVERLAP, s as recordReviewRead, t as DEFAULT_HEALTH_THRESHOLDS, u as isReviewChannelSession, v as scanThreats, w as EVENT_ARCHIVE_PREFIX, x as FUZZY_MAX_WORK, y as makeSerialQueue, z as COST_ASCII_TOKEN_HIGH } from "./skill-health-BIpiPvw6.js";
6
+ import { A as retainEventArchives, C as appendEvolutionEvent, D as parseEvolutionEvents, E as listEventArchives, G as DEFAULT_WRITE_CONFIRM_MODE, H as isUnreadWrite, I as softBodyTokenBudget, K as DEFAULT_WRITE_CONFIRM_TIMEOUT_SECONDS, L as RULES, O as readEvolutionEvents, P as assessStructureHealth, S as EVENT_LOG_VERSION, T as evolutionEventPayloadIssue, _ as fuzzyPatch, a as isReviewChannelSession, b as EVENT_LOG_RETAIN_ARCHIVES, c as PATTERN_OVERLAP, d as scanContentThreats, f as scanMemoryThreats, g as FUZZY_MAX_WORK, h as FUZZY_MAX_PATTERN_CHARS, i as clearReviewChannel, j as DEFAULT_HEALTH_THRESHOLDS, k as readEvolutionTimeline, l as THREAT_EXEMPTION_HINT, m as makeSerialQueue, n as recordReviewRead, o as markReviewChannel, p as scanThreats, q as authorityFrom, r as withReviewContext, s as sweepReviewChannelSessions, t as currentReviewContext, u as evaluateThreat, v as trimPatternBoundaries, w as eventsFile, x as EVENT_LOG_ROTATE_AT, y as EVENT_ARCHIVE_PREFIX, z as lintSkill } from "./review-context-CXKwGGd8.js";
7
7
  import { i as HOST_LOCALES, n as errorText, r as errorTextIn, t as EVOLUTION_ERRORS } from "./errors-BxzLTVbS.js";
8
- import { A as dispatchKeyOf, C as PTC_DISPATCH_EVENT, D as assertDispatchPayload, E as ToolDispatchPayloadError, F as isSkillToolName, I as readDispatchSignal, L as skillReadNameOf, M as dispatchStepOf, N as foldToolDispatches, O as collectReadSkillNames, P as isSkillReadToolName, R as supportFileReadFromPath, S as NATIVE_RESULT_EVENT, T as ToolDispatchNormalizer, _ as isBookkeepingFrame, a as evolutionSignalsProjection, b as MODEL_SESSION_EVENT_TYPES, c as sessionLastEventTime, d as advanceReview, f as foldTurnEvent, g as evidenceKindIndex, h as observeEvent, i as evolutionReadsProjection, j as dispatchPathOf, k as collectReadSupportFiles, l as sessionReadNames, m as initialTurnFold, n as evolutionEvidenceProjection, o as isProjectableSession, p as foldTurnEvents, r as evolutionProjectionHistoryProjection, s as sessionEvidenceIndex, t as evolutionActivityProjection, u as sessionTurnSignals, v as DEFAULT_SUPPORT_READ_TOOL_NAMES, w as PTC_DISPATCH_START_EVENT, x as NATIVE_CALL_EVENT, y as DISPATCH_EVENT_TYPES, z as supportFileReadOf } from "./session-projection-ByNxQi9O.js";
9
- import { A as h2Sections, C as saveUsage, D as usageObserved, E as usageFile, G as supportRefs, J as planReferenceRewrite, K as applyReferenceRewrite, O as selectSections, S as saveSuppressedNames, T as updateSuppressedNames, W as externalRefs, Y as planRehoming, _ as loadUsage, a as applyCuratorMetaFields, b as normalizeUsageRecord, c as bumpUse, d as emptyRecord, f as foldCuratorFields, g as loadSuppressedNames, h as latestActivityAt, i as applyCuratorLifecycleFields, j as readingStats, k as displayBodyOf, l as bumpView, m as idleDays, n as SUPPRESSED_FILE_VERSION, o as bumpPatch, p as getRecord, q as describeReferenceRewrite, r as VIEW_WINDOW_DAYS, s as bumpSupportRead, t as MAX_SUPPORT_READ_PATHS, u as daysSinceIso, v as markAgentCreated, w as suppressedFile, x as recentViewCount, y as mutateUsage } from "./usage-B1qveKi9.js";
8
+ import { A as dispatchKeyOf, C as PTC_DISPATCH_EVENT, D as assertDispatchPayload, E as ToolDispatchPayloadError, F as isSkillToolName, I as readDispatchSignal, L as skillReadNameOf, M as dispatchStepOf, N as foldToolDispatches, O as collectReadSkillNames, P as isSkillReadToolName, R as supportFileReadFromPath, S as NATIVE_RESULT_EVENT, T as ToolDispatchNormalizer, _ as isBookkeepingFrame, a as evolutionSignalsProjection, b as MODEL_SESSION_EVENT_TYPES, c as sessionLastEventTime, d as advanceReview, f as foldTurnEvent, g as evidenceKindIndex, h as observeEvent, i as evolutionReadsProjection, j as dispatchPathOf, k as collectReadSupportFiles, l as sessionReadNames, m as initialTurnFold, n as evolutionEvidenceProjection, o as isProjectableSession, p as foldTurnEvents, r as evolutionProjectionHistoryProjection, s as sessionEvidenceIndex, t as evolutionActivityProjection, u as sessionTurnSignals, v as DEFAULT_SUPPORT_READ_TOOL_NAMES, w as PTC_DISPATCH_START_EVENT, x as NATIVE_CALL_EVENT, y as DISPATCH_EVENT_TYPES, z as supportFileReadOf } from "./session-projection-CbIKvDfJ.js";
9
+ import { a as measureUnit, i as measureText, n as conservativeTokenEstimator, o as truncateGraphemes, r as graphemeCount, s as utf8ByteLength, t as codePointCount } from "./text-metrics-CyJhxWBs.js";
10
+ import { A as h2Sections, C as saveUsage, D as usageObserved, E as usageFile, F as describeReferenceRewrite, I as planReferenceRewrite, L as planRehoming, M as externalRefs, N as supportRefs, O as selectSections, P as applyReferenceRewrite, S as saveSuppressedNames, T as updateSuppressedNames, _ as loadUsage, a as applyCuratorMetaFields, b as normalizeUsageRecord, c as bumpUse, d as emptyRecord, f as foldCuratorFields, g as loadSuppressedNames, h as latestActivityAt, i as applyCuratorLifecycleFields, j as readingStats, k as displayBodyOf, l as bumpView, m as idleDays, n as SUPPRESSED_FILE_VERSION, o as bumpPatch, p as getRecord, r as VIEW_WINDOW_DAYS, s as bumpSupportRead, t as MAX_SUPPORT_READ_PATHS, u as daysSinceIso, v as markAgentCreated, w as suppressedFile, x as recentViewCount, y as mutateUsage } from "./usage-e34VZPmK.js";
10
11
  import { n as isRecord, t as asRecord } from "./guards-3f02mnf2.js";
11
- import { T as ownerCandidatesFromSummaries, _ as readProposalReport, a as SUMMARY_DUPLICATE_HINT_THRESHOLD, b as proposalFromPlan, c as computePrefixClusters, d as nearDuplicateSummaries, f as projectionText, g as proposalReportName, h as proposalReportDir, i as QUALITY_WEIGHTS, l as computeQualityScores, m as readExternalSupport, n as DEDUP_SIMILARITY_THRESHOLD, o as affinity, p as vocabulary, r as LOW_QUALITY_THRESHOLD, s as computeDedupGroups, t as DEDUP_MAX_PAIR_COMPARISONS, u as identity, v as readProposalReports, w as findOwnerCandidate, y as writeProposalReport } from "./quality-BLc6UQQb.js";
12
+ import { a as mutationsFile, i as loadMutations, n as MUTATIONS_FILE_VERSION, o as recordMutation, r as contentHash, t as DEFAULT_MUTATION_CAP } from "./mutations-1wLISSrY.js";
13
+ import { T as ownerCandidatesFromSummaries, _ as readProposalReport, a as SUMMARY_DUPLICATE_HINT_THRESHOLD, b as proposalFromPlan, c as computePrefixClusters, d as nearDuplicateSummaries, f as projectionText, g as proposalReportName, h as proposalReportDir, i as QUALITY_WEIGHTS, l as computeQualityScores, m as readExternalSupport, n as DEDUP_SIMILARITY_THRESHOLD, o as affinity, p as vocabulary, r as LOW_QUALITY_THRESHOLD, s as computeDedupGroups, t as DEDUP_MAX_PAIR_COMPARISONS, u as identity, v as readProposalReports, w as findOwnerCandidate, y as writeProposalReport } from "./quality-DNUVRbUm.js";
12
14
  import { n as evolutionRoot, t as evolutionHome } from "./state-store-Jpa-iYIZ.js";
15
+ import "./skill-history-B-DyIedq.js";
13
16
  import { HOST_ROUTES, MAX_REQUEST_BODY_BYTES, hostSurface, json, methodNotAllowed, readJsonObject, registerHostRoutes } from "./http-routes.js";
14
17
  import { w as allowRowCollisions } from "./composition-CtNbVHq3.js";
15
18
  import { t as clampedNumber } from "./numeric-Dc53KQoe.js";
16
- import { a as mutationsFile, i as loadMutations, n as MUTATIONS_FILE_VERSION, o as recordMutation, r as contentHash, t as DEFAULT_MUTATION_CAP } from "./mutations-DQXddSJd.js";
17
19
  import { u as scopeOf, y as settingsPort } from "./platform-DyHnHUmQ.js";
18
20
  import { n as toolsPort } from "./tools-BrUswg8v.js";
19
21
  import { abortLink, createSubagentChannel as createSubagentKernel, createSubagentRun, probeChannelState, textOfValue, waitForSubagentEnd } from "./subagent/index.js";
@@ -319,127 +321,534 @@ async function runWriteGates(context) {
319
321
  return null;
320
322
  }
321
323
  //#endregion
322
- //#region lib/types/health-baseline.js
323
- function buildHealthBaseline(skills) {
324
- const values = {};
325
- for (const rule of RULES) values[rule.id] = {
326
- platformHits: 0,
327
- userHits: 0,
328
- userHitRate: 0
329
- };
330
- let user = 0;
331
- let platform = 0;
332
- for (const skill of skills) {
333
- if (skill.corpus === "user") user += 1;
334
- else platform += 1;
335
- for (const finding of lintSkill(skill.facts)) {
336
- const row = values[finding.rule];
337
- if (row === void 0) continue;
338
- if (skill.corpus === "user") row.userHits += 1;
339
- else row.platformHits += 1;
340
- }
324
+ //#region lib/types/drift-signals.js
325
+ /**
326
+ * Library-level drift signals for the maintenance subagent (design 011).
327
+ *
328
+ * Deterministic fact checks over a skill-library snapshot: domain drift
329
+ * (narrow names, near-duplicate groups, prefix clusters) and layer drift
330
+ * (log-like bodies, duplicate headings, overlong lines, missing support-file
331
+ * pointers, description over the authoring bar). Pure functions only — no IO,
332
+ * no LLM, no services. Thresholds are imported from their owning modules
333
+ * (skill-health / quality / skill-store), never duplicated.
334
+ *
335
+ * Distinct from `signals.ts` — the session-level review signal gate.
336
+ */
337
+ /** Physical line length at/above which a body line is reported overlong (011 §4). */
338
+ const DRIFT_MAX_LINE_CHARS = 1500;
339
+ /** Signal-set version: bump whenever ids/thresholds change (011 §7 version coupling). */
340
+ const DRIFT_SIGNALS_VERSION = "3";
341
+ /** Render-time nouns for the MAINTAIN_PROMPT placeholders (single vocabulary with the facts block). */
342
+ const DRIFT_SIGNAL_NOUNS = {
343
+ dedup_group: "近重复组",
344
+ prefix_cluster: "前缀聚类",
345
+ stamp_density: "stamp 密度",
346
+ body_size: "正文体量",
347
+ dup_heading: "重复标题",
348
+ overlong_line: "超长行",
349
+ pointer_missing: "缺失指针",
350
+ citation_resolution: "引用解析",
351
+ demand: "需求证据",
352
+ description_chars: "描述长度",
353
+ narrow_name: "窄名",
354
+ usage_observed: "使用观察",
355
+ quality_low: "质量分"
356
+ };
357
+ const NARROW_NAME_PATTERNS = [
358
+ {
359
+ label: "error-string",
360
+ re: /^(?:err|error|exception|traceback|warn|fail)(?:[-_][a-z0-9]+)+$/i
361
+ },
362
+ {
363
+ label: "pr-number",
364
+ re: /^(?:pr|issue)[-_]?\d{2,}$/i
365
+ },
366
+ {
367
+ label: "dated",
368
+ re: /\d{4}-\d{2}-\d{2}/
369
+ },
370
+ {
371
+ label: "session-verb",
372
+ re: /^(?:fix|debug|audit|salvage|diagnose|investigate)[-_][a-z0-9-]+$/i
341
373
  }
342
- for (const row of Object.values(values)) row.userHitRate = user === 0 ? 0 : row.userHits / user;
374
+ ];
375
+ /** Detect support files the body never references (by basename or relative path). */
376
+ function missingSupportPointers(body, supportFiles) {
377
+ return supportFiles.filter((path) => {
378
+ const base = path.split("/").pop() ?? path;
379
+ return base.length > 0 && !body.includes(base) && !body.includes(path);
380
+ });
381
+ }
382
+ /** Support files the body mentions WITHOUT the sanctioned hook form (design
383
+ * §5.6). Such a mention still counts as a pointer for `pointer_missing`, but
384
+ * only the hook form keeps the file discoverable after a move — detail only.
385
+ * A file carrying a `keep` marker is exempt: its mention IS the marker. */
386
+ function unhookedSupportPointers(body, supportFiles) {
387
+ const { targets, kept } = scanBodyHooks(body);
388
+ const hooked = new Set(targets);
389
+ return supportFiles.filter((path) => {
390
+ if (!isFileShapedPath(path)) return false;
391
+ const base = path.split("/").pop() ?? path;
392
+ if (kept.has(path) || base.length > 0 && kept.has(base)) return false;
393
+ return (base.length > 0 && body.includes(base) || body.includes(path)) && !hooked.has(path) && !hooked.has(base);
394
+ });
395
+ }
396
+ /** Support files with no readers, no citations and no `keep` marker whose owning
397
+ * skill has been idle for at least the lifecycle stale window. PROPOSAL INPUT
398
+ * only — nothing retires a file on its own — and an unmeasurable input (no age
399
+ * evidence, no citation scan) yields an empty list WITH its reason, never a
400
+ * silent "nothing qualifies".
401
+ * @param snapshot - the skill's drift snapshot.
402
+ * @param supportFiles - its enumerated support files, in listing order.
403
+ * @returns the candidates plus the status that explains an empty list.
404
+ */
405
+ function retirementReport(snapshot, supportFiles) {
406
+ const idle = snapshot.liveness?.idleDays;
407
+ if (idle === void 0) return {
408
+ candidates: [],
409
+ status: "no-age"
410
+ };
411
+ if (snapshot.citations === void 0) return {
412
+ candidates: [],
413
+ status: "unscanned"
414
+ };
415
+ if (idle < 30) return {
416
+ candidates: [],
417
+ status: "none"
418
+ };
419
+ const cited = /* @__PURE__ */ new Set();
420
+ for (const ref of snapshot.citations.refs) if (ref.kind === "citation" && ref.target !== null) cited.add(ref.target);
421
+ const { kept } = scanBodyHooks(snapshot.body);
422
+ const demand = snapshot.demand ?? {};
423
+ const candidates = supportFiles.filter((path) => isFileShapedPath(path) && (demand[path] ?? 0) === 0 && !cited.has(path) && !kept.has(path)).map((path) => ({
424
+ path,
425
+ idleDays: Math.floor(idle)
426
+ }));
343
427
  return {
344
- unit: "chars",
345
- scope: "references markdown file count",
346
- corpora: {
347
- user,
348
- platform
349
- },
350
- values
428
+ candidates,
429
+ status: candidates.length === 0 ? "none" : "listed"
351
430
  };
352
431
  }
353
- //#endregion
354
- //#region lib/types/gates.js
355
- /**
356
- * The control-plane protection sets, held once and queried everywhere
357
- * (decision B, rc.44 plan M2): the lifecycle engine, the scope view, the LLM
358
- * nomination gate and the control-plane consolidate all answer "is this name
359
- * off limits — and why" from the same instance, so the gate sets can never
360
- * drift apart the way the three pre-rc.46 implementations did.
361
- *
362
- * Scope boundary: a GateSet covers NAME-SET protections only. Marker-based
363
- * protections (pinned / bundled / hub-installed) are file markers resolved by
364
- * `SkillLibrary.writeProtection` / `deleteProtection` — they depend on the
365
- * filesystem and the write origin, not on a name list.
366
- * @module @lmzhen/dsh-evolution-core
367
- */
368
- var EvolutionGateSet = class {
369
- exclude;
370
- referenced;
371
- suppressed;
372
- constructor(inputs = {}) {
373
- this.exclude = inputs.exclude ?? /* @__PURE__ */ new Set();
374
- this.referenced = inputs.referenced ?? /* @__PURE__ */ new Set();
375
- this.suppressed = inputs.suppressed ?? /* @__PURE__ */ new Set();
432
+ /** Duplicate `## heading` occurrences: singleton results default to head of the file. */
433
+ function duplicateHeadings(body) {
434
+ const counts = /* @__PURE__ */ new Map();
435
+ for (const raw of body.split("\n")) {
436
+ const line = raw.endsWith("\r") ? raw.slice(0, -1) : raw;
437
+ const m = /^##\s+(.+)$/.exec(line);
438
+ if (m?.[1]) {
439
+ const heading = m[1].trim();
440
+ if (heading) counts.set(heading, (counts.get(heading) ?? 0) + 1);
441
+ }
376
442
  }
377
- /**
378
- * The first protection blocking this name, or null. Any hit blocks — the
379
- * order is diagnostic only, so a name in two sets reports the first.
380
- */
381
- blockReason(name) {
382
- if (this.exclude.has(name)) return "excluded";
383
- if (this.referenced.has(name)) return "referenced";
384
- if (this.suppressed.has(name)) return "suppressed";
385
- if (PROTECTED_BUILTIN_SKILLS.has(name)) return "protected-builtin";
386
- return null;
443
+ return [...counts.entries()].filter(([, count]) => count > 1).map(([heading, count]) => ({
444
+ heading,
445
+ count
446
+ }));
447
+ }
448
+ /** Physical lines over `max` graphemes: `{ lineNo, chars }`, 1-based line numbers. */
449
+ function overlongLines(body, max = DRIFT_MAX_LINE_CHARS) {
450
+ const out = [];
451
+ const lines = body.split("\n");
452
+ for (let index = 0; index < lines.length; index += 1) {
453
+ const raw = lines[index] ?? "";
454
+ const length = graphemeCount(raw.endsWith("\r") ? raw.slice(0, -1) : raw);
455
+ if (length > max) out.push({
456
+ lineNo: index + 1,
457
+ chars: length
458
+ });
387
459
  }
388
- isBlocked(name) {
389
- return this.blockReason(name) !== null;
460
+ return out;
461
+ }
462
+ /** Narrow-name shapes detected in a skill name (empty = none). */
463
+ function narrowNameMatches(name) {
464
+ return NARROW_NAME_PATTERNS.filter(({ re }) => re.test(name)).map(({ label }) => label);
465
+ }
466
+ function supportGroupCount(supportFiles) {
467
+ const groups = /* @__PURE__ */ new Set();
468
+ for (const path of supportFiles ?? []) {
469
+ const head = path.split("/")[0];
470
+ if (head) groups.add(head);
390
471
  }
391
- };
392
- /** Build a GateSet from the curator-style config field names. */
393
- function createGateSet(config) {
394
- return new EvolutionGateSet({
395
- exclude: config.excludeSkillNames,
396
- referenced: config.referencedSkillNames,
397
- suppressed: config.suppressedNames
398
- });
472
+ return groups.size;
399
473
  }
400
- //#endregion
401
- //#region lib/types/curator.js
402
- /**
403
- * Deterministic skill curator: active → stale → archived transitions.
404
- * Pure function with one deliberate side effect: records in the passed
405
- * `usage` map are MUTATED (state/archived_at) to carry the transition — the
406
- * caller owns the map and decides whether to clone first (dry-run) or persist
407
- * after. File moves are performed by SkillLibrary.
408
- */
409
- function buildCuratorRunReport(input) {
474
+ function sig(id, verdict, value, threshold, detail) {
410
475
  return {
411
- schemaVersion: 1,
412
- runId: input.runId,
413
- startedAt: input.startedAt,
414
- finishedAt: input.finishedAt,
415
- staleCandidates: [...input.staleCandidates],
416
- llmNominations: [...input.llmNominations],
417
- archiveCandidates: [...input.archiveCandidates],
418
- archived: [...input.archived],
419
- failed: [...input.failed],
420
- ...input.aborted === void 0 ? {} : { aborted: input.aborted },
421
- ...input.unattributed === void 0 || input.unattributed.length === 0 ? {} : { unattributed: [...input.unattributed] },
422
- ...input.consolidated === void 0 ? {} : { consolidated: [...input.consolidated] },
423
- ...input.snapshotPath === void 0 ? {} : { snapshotPath: input.snapshotPath },
424
- ...input.llmReviewEnabled === void 0 ? {} : { llmReviewEnabled: input.llmReviewEnabled },
425
- ...input.nominationsWarnings === void 0 ? {} : { nominationsWarnings: [...input.nominationsWarnings] },
426
- ...input.scanWarnings === void 0 ? {} : { scanWarnings: [...input.scanWarnings] },
427
- ...input.wouldPrune === void 0 ? {} : { wouldPrune: input.wouldPrune === null ? null : [...input.wouldPrune] }
476
+ id,
477
+ verdict,
478
+ value,
479
+ threshold,
480
+ detail
428
481
  };
429
482
  }
430
483
  /**
431
- * Render a curator run report as a compact human-readable markdown digest
432
- * (G6): run metadata first, then the notable sections (archived / failed /
433
- * stale candidates / LLM nominations).
484
+ * Compute all drift signals for a snapshot. Missing inputs (quality score,
485
+ * usage window) yield `unknown` — never a fabricated verdict.
434
486
  */
435
- function renderCuratorReportMarkdown(report) {
436
- const lines = [
437
- `# Curator run ${report.runId}`,
438
- "",
439
- `- **Started** ${report.startedAt}`,
440
- `- **Finished** ${report.finishedAt}`,
441
- `- **Stale candidates**: ${report.staleCandidates.length}`,
442
- `- **LLM nominations**: ${report.llmNominations.length}`,
487
+ function computeDriftSignals(snapshots) {
488
+ const library = [];
489
+ const names = snapshots.map((s) => s.name);
490
+ const dedup = computeDedupGroups({ contents: new Map(snapshots.map((s) => [s.name, s.body])) });
491
+ const dedupTruncation = dedup.truncated ? " (dedup scan truncated at the pair-comparison budget)" : "";
492
+ library.push(dedup.groups.length === 0 ? sig("dedup_group", "pass", `none${dedupTruncation}`, "size >= 2") : sig("dedup_group", "over", `${dedup.groups.map((group) => group.join(", ")).join(" | ")}${dedupTruncation}`, "size >= 2", `members=${dedup.groups.map((group) => group.join("|")).join(";")}`));
493
+ const clusters = computePrefixClusters(names);
494
+ library.push(clusters.length === 0 ? sig("prefix_cluster", "pass", "none", "size >= 2") : sig("prefix_cluster", "over", clusters.map((cluster) => cluster.members.join(", ")).join(" | "), "size >= 2", `key=${clusters.map((cluster) => cluster.key).join("|")}`));
495
+ const allProvided = snapshots.length > 0 && snapshots.every((s) => s.usageObserved !== null && s.usageObserved !== void 0);
496
+ library.push(!allProvided ? sig("usage_observed", "unknown", "not-observed", void 0, "usage window status missing") : snapshots.every((s) => s.usageObserved === true) ? sig("usage_observed", "pass", "observed") : sig("usage_observed", "pass", "unobserved"));
497
+ return {
498
+ library,
499
+ skills: snapshots.map((snapshot) => {
500
+ const signals = [];
501
+ const body = snapshot.body;
502
+ const supportFiles = snapshot.supportFiles ?? [];
503
+ const supportEnumerated = snapshot.supportFiles !== void 0;
504
+ const health = assessStructureHealth({
505
+ skillName: snapshot.name,
506
+ bodyChars: body.length,
507
+ bodyText: body,
508
+ supportGroups: supportGroupCount(supportFiles)
509
+ }, DEFAULT_HEALTH_THRESHOLDS);
510
+ const density = health.dims.stampDensityPerKb;
511
+ signals.push(density === null ? sig("stamp_density", "pass", "below-min-body") : sig("stamp_density", density >= DEFAULT_HEALTH_THRESHOLDS.stampDensityPerKb ? "over" : "pass", `${density.toFixed(2)}/KB`, `${DEFAULT_HEALTH_THRESHOLDS.stampDensityPerKb}/KB`));
512
+ const bodyTokens = health.dims.bodyTokens;
513
+ const tokenBudget = softBodyTokenBudget(DEFAULT_HEALTH_THRESHOLDS);
514
+ const overLine = bodyTokens >= tokenBudget;
515
+ signals.push(sig("body_size", overLine ? "over" : "pass", `${bodyTokens} tokens / ${body.length} chars`, `${tokenBudget} tokens`, `body=${(bodyTokens / tokenBudget).toFixed(1)}x${oversizeSupportNote(snapshot.supportChars)}`));
516
+ const dupes = duplicateHeadings(body);
517
+ signals.push(dupes.length === 0 ? sig("dup_heading", "pass", "none") : sig("dup_heading", "over", dupes.map((d) => `${d.heading}(${d.count})`).join(", "), "count >= 2"));
518
+ const long = overlongLines(body);
519
+ signals.push(long.length === 0 ? sig("overlong_line", "pass", "none") : sig("overlong_line", "over", long.map((l) => `${l.lineNo}:${l.chars}`).join(", "), `${DRIFT_MAX_LINE_CHARS}`));
520
+ const missing = supportEnumerated ? missingSupportPointers(body, supportFiles) : void 0;
521
+ const unhooked = supportEnumerated ? unhookedSupportPointers(body, supportFiles) : [];
522
+ const unhookedDetail = unhooked.length === 0 ? void 0 : `unhooked=${unhooked.length}: ${unhooked.slice(0, 5).join(", ")}`;
523
+ signals.push(!supportEnumerated ? sig("pointer_missing", "unknown", "not-enumerated", void 0, "support files not enumerated") : (missing ?? []).length === 0 ? sig("pointer_missing", "pass", "none", void 0, unhookedDetail) : sig("pointer_missing", "over", missing?.join(", ") ?? "", void 0, unhookedDetail));
524
+ signals.push(citationSignal(snapshot.citations));
525
+ signals.push(demandSignal(snapshot, supportFiles, supportEnumerated));
526
+ const narrow = narrowNameMatches(snapshot.name);
527
+ signals.push(narrow.length === 0 ? sig("narrow_name", "pass", "none") : sig("narrow_name", "over", narrow.join(", "), void 0, `name=${snapshot.name}`));
528
+ const description = snapshot.description;
529
+ const descriptionLength = description === void 0 ? 0 : graphemeCount(description);
530
+ signals.push(description === void 0 ? sig("description_chars", "unknown", "missing", `60`) : sig("description_chars", descriptionLength > 60 ? "over" : "pass", `${descriptionLength}`, `60`));
531
+ const quality = snapshot.quality;
532
+ signals.push(quality === null || quality === void 0 ? sig("quality_low", "unknown", "not-assessed") : sig("quality_low", quality < .3 ? "over" : "pass", quality.toFixed(2), `${LOW_QUALITY_THRESHOLD}`));
533
+ return {
534
+ name: snapshot.name,
535
+ signals,
536
+ ...snapshot.protected !== void 0 && snapshot.protected !== null ? { protected: snapshot.protected } : {},
537
+ ...snapshot.catalogInvalid !== void 0 ? { catalogInvalid: snapshot.catalogInvalid } : {}
538
+ };
539
+ })
540
+ };
541
+ }
542
+ /** Dangling-citation verdict: a partial scan is `unknown`, never a clean pass. */
543
+ function citationSignal(citations) {
544
+ if (citations === void 0) return sig("citation_resolution", "unknown", "not-scanned", void 0, "support-file list missing");
545
+ if (citations.truncated) return sig("citation_resolution", "unknown", `truncated at ${citations.refs.length} refs`, void 0, "partial scan — not a clean verdict");
546
+ const cited = citations.refs.filter((ref) => ref.kind === "citation");
547
+ if (citations.dangling.length > 0) {
548
+ const missing = citations.dangling.slice(0, 5).map((ref) => ref.target ?? ref.raw).join(", ");
549
+ return sig("citation_resolution", "over", `dangling=${citations.dangling.length}/${cited.length}`, "dangling=0", `missing: ${missing}`);
550
+ }
551
+ return sig("citation_resolution", "pass", `citations=${cited.length} foreign=${citations.foreign.length}${citations.unverified.length === 0 ? "" : ` unverified=${citations.unverified.length}`}`);
552
+ }
553
+ /** V4 (design §16.6): the report half of the support-file cap. Only files the
554
+ * assembler could PROVE large enough to be over the cap are namespaced here; an
555
+ * absent map claims nothing (unknown is not zero).
556
+ * @param supportChars - measured character counts, or undefined when unmeasured.
557
+ * @returns a detail suffix naming the oversize files, or an empty string.
558
+ */
559
+ function oversizeSupportNote(supportChars) {
560
+ if (supportChars === void 0) return "";
561
+ const oversize = Object.entries(supportChars).filter(([, chars]) => chars > MAX_SKILL_CONTENT_CHARS).sort((a, b) => b[1] - a[1]);
562
+ if (oversize.length === 0) return "";
563
+ const shown = oversize.slice(0, 3).map(([path, chars]) => `${path}(${chars})`);
564
+ return `; oversize support file(s): ${shown.join(", ")}${oversize.length > shown.length ? " …" : ""}`;
565
+ }
566
+ /** Render-time reason for an empty retirement list (design §5.6). */
567
+ const RETIREMENT_STATUS_TEXT = {
568
+ listed: "listed",
569
+ none: "none",
570
+ "no-age": "age unknown",
571
+ unscanned: "citations unscanned"
572
+ };
573
+ /** Cold-support-file verdict (design §5.5): zero reads are evidence only while
574
+ * the observation window is open and the file list is known. */
575
+ function demandSignal(snapshot, supportFiles, supportEnumerated) {
576
+ if (!supportEnumerated || supportFiles.length === 0) return sig("demand", "unknown", "not-enumerated", void 0, "support files not enumerated");
577
+ if (snapshot.usageObserved !== true) return sig("demand", "unknown", "window-closed", void 0, "no observed reads yet: zero is not evidence");
578
+ const demand = snapshot.demand ?? {};
579
+ const cold = supportFiles.filter((path) => (demand[path] ?? 0) === 0);
580
+ const retire = retirementReport(snapshot, supportFiles);
581
+ const retireDetail = retire.candidates.length === 0 ? `retire: ${RETIREMENT_STATUS_TEXT[retire.status]}` : `retire≥30d: ${retire.candidates.slice(0, 5).map((c) => `${c.path}(${c.idleDays}d)`).join(", ")}`;
582
+ if (cold.length === 0) return sig("demand", "pass", `${supportFiles.length} warm`, "cold=0", retireDetail);
583
+ const sample = cold.slice(0, 5).join(", ");
584
+ return sig("demand", "over", `cold=${cold.length}/${supportFiles.length}`, "cold=0", `never read: ${sample} · ${retireDetail}`);
585
+ }
586
+ /** Convenience: fetch one signal from an assessment or library list. */
587
+ function findDriftSignal(signals, id) {
588
+ return signals.find((signal) => signal.id === id);
589
+ }
590
+ //#endregion
591
+ //#region lib/types/text-budgets.js
592
+ /**
593
+ * Named text budgets: every character-based decision declares its axis, unit and
594
+ * severity here, so business code never invents a measurement or a unit inline.
595
+ *
596
+ * A budget is not a language profile. Storage/display/context/quality are
597
+ * different questions about the same string; the metric module answers all of
598
+ * them, and this table decides which answer each gate uses.
599
+ *
600
+ * @module @lmzhen/dsh-evolution-core
601
+ */
602
+ /** The default soft body token budget. */
603
+ const SOFT_BODY_TOKENS = DEFAULT_SOFT_BODY_TOKENS;
604
+ /** The derived token budgets for the old character memory limits. */
605
+ const MEMORY_TOKENS = DEFAULT_MEMORY_TOKENS;
606
+ const USER_TOKENS = DEFAULT_USER_TOKENS;
607
+ /**
608
+ * The family's named budgets.
609
+ *
610
+ * Context budgets are registered here before their wiring lands so the inventory
611
+ * and doctor have one authority; P2 is what makes them stop being dormant.
612
+ */
613
+ const TEXT_BUDGETS = {
614
+ skillBodyHard: {
615
+ id: "skill.body.hard",
616
+ axis: "storage",
617
+ unit: "codePoints",
618
+ limit: MAX_SKILL_CONTENT_CHARS,
619
+ severity: "hard"
620
+ },
621
+ skillFileBytes: {
622
+ id: "skill.file.bytes",
623
+ axis: "storage",
624
+ unit: "utf8Bytes",
625
+ limit: MAX_SKILL_FILE_BYTES,
626
+ severity: "hard"
627
+ },
628
+ skillName: {
629
+ id: "skill.name",
630
+ axis: "storage",
631
+ unit: "codePoints",
632
+ limit: 64,
633
+ severity: "hard"
634
+ },
635
+ skillDescription: {
636
+ id: "skill.description.hard",
637
+ axis: "display",
638
+ unit: "graphemes",
639
+ limit: MAX_DESCRIPTION_LENGTH,
640
+ severity: "hard"
641
+ },
642
+ skillDescriptionAuthoring: {
643
+ id: "skill.description.authoring",
644
+ axis: "display",
645
+ unit: "graphemes",
646
+ limit: 60,
647
+ severity: "soft"
648
+ },
649
+ skillSummary: {
650
+ id: "skill.summary",
651
+ axis: "display",
652
+ unit: "graphemes",
653
+ limit: 50,
654
+ severity: "hard"
655
+ },
656
+ feedbackNote: {
657
+ id: "feedback.note",
658
+ axis: "display",
659
+ unit: "graphemes",
660
+ limit: 20,
661
+ severity: "hard"
662
+ },
663
+ lineLength: {
664
+ id: "skill.line",
665
+ axis: "display",
666
+ unit: "graphemes",
667
+ limit: DRIFT_MAX_LINE_CHARS,
668
+ severity: "soft"
669
+ },
670
+ substantiveUser: {
671
+ id: "review.substantive.user",
672
+ axis: "display",
673
+ unit: "graphemes",
674
+ limit: 200,
675
+ severity: "soft"
676
+ },
677
+ substantiveAgent: {
678
+ id: "review.substantive.agent",
679
+ axis: "display",
680
+ unit: "graphemes",
681
+ limit: 500,
682
+ severity: "soft"
683
+ },
684
+ retentionFeedback: {
685
+ id: "history.retention-feedback",
686
+ axis: "display",
687
+ unit: "graphemes",
688
+ limit: 200,
689
+ severity: "report"
690
+ },
691
+ bodySoft: {
692
+ id: "skill.body.soft",
693
+ axis: "context",
694
+ unit: "tokens",
695
+ limit: SOFT_BODY_TOKENS,
696
+ severity: "soft"
697
+ },
698
+ memory: {
699
+ id: "memory.budget",
700
+ axis: "context",
701
+ unit: "tokens",
702
+ limit: MEMORY_TOKENS,
703
+ severity: "hard"
704
+ },
705
+ user: {
706
+ id: "user.budget",
707
+ axis: "context",
708
+ unit: "tokens",
709
+ limit: USER_TOKENS,
710
+ severity: "hard"
711
+ }
712
+ };
713
+ /**
714
+ * Compare one string against one named budget.
715
+ * @param text - the string to measure.
716
+ * @param budget - the budget to apply.
717
+ * @param estimator - optional token source for token budgets.
718
+ * @returns the measured value and the remaining allowance (negative when over).
719
+ */
720
+ function compareTextBudget(text, budget, estimator) {
721
+ const metrics = measureText(text, estimator);
722
+ const measured = budget.unit === "tokens" ? metrics.tokens.value : budget.unit === "utf8Bytes" ? metrics.utf8Bytes : budget.unit === "codePoints" ? metrics.codePoints : metrics.graphemes;
723
+ return {
724
+ budget,
725
+ value: measured,
726
+ over: measured > budget.limit,
727
+ remaining: budget.limit - measured
728
+ };
729
+ }
730
+ //#endregion
731
+ //#region lib/types/health-baseline.js
732
+ function buildHealthBaseline(skills) {
733
+ const values = {};
734
+ for (const rule of RULES) values[rule.id] = {
735
+ platformHits: 0,
736
+ userHits: 0,
737
+ userHitRate: 0
738
+ };
739
+ let user = 0;
740
+ let platform = 0;
741
+ for (const skill of skills) {
742
+ if (skill.corpus === "user") user += 1;
743
+ else platform += 1;
744
+ for (const finding of lintSkill(skill.facts)) {
745
+ const row = values[finding.rule];
746
+ if (row === void 0) continue;
747
+ if (skill.corpus === "user") row.userHits += 1;
748
+ else row.platformHits += 1;
749
+ }
750
+ }
751
+ for (const row of Object.values(values)) row.userHitRate = user === 0 ? 0 : row.userHits / user;
752
+ return {
753
+ unit: "chars",
754
+ scope: "references markdown file count",
755
+ corpora: {
756
+ user,
757
+ platform
758
+ },
759
+ values
760
+ };
761
+ }
762
+ //#endregion
763
+ //#region lib/types/gates.js
764
+ /**
765
+ * The control-plane protection sets, held once and queried everywhere
766
+ * (decision B, rc.44 plan M2): the lifecycle engine, the scope view, the LLM
767
+ * nomination gate and the control-plane consolidate all answer "is this name
768
+ * off limits — and why" from the same instance, so the gate sets can never
769
+ * drift apart the way the three pre-rc.46 implementations did.
770
+ *
771
+ * Scope boundary: a GateSet covers NAME-SET protections only. Marker-based
772
+ * protections (pinned / bundled / hub-installed) are file markers resolved by
773
+ * `SkillLibrary.writeProtection` / `deleteProtection` — they depend on the
774
+ * filesystem and the write origin, not on a name list.
775
+ * @module @lmzhen/dsh-evolution-core
776
+ */
777
+ var EvolutionGateSet = class {
778
+ exclude;
779
+ referenced;
780
+ suppressed;
781
+ constructor(inputs = {}) {
782
+ this.exclude = inputs.exclude ?? /* @__PURE__ */ new Set();
783
+ this.referenced = inputs.referenced ?? /* @__PURE__ */ new Set();
784
+ this.suppressed = inputs.suppressed ?? /* @__PURE__ */ new Set();
785
+ }
786
+ /**
787
+ * The first protection blocking this name, or null. Any hit blocks — the
788
+ * order is diagnostic only, so a name in two sets reports the first.
789
+ */
790
+ blockReason(name) {
791
+ if (this.exclude.has(name)) return "excluded";
792
+ if (this.referenced.has(name)) return "referenced";
793
+ if (this.suppressed.has(name)) return "suppressed";
794
+ if (PROTECTED_BUILTIN_SKILLS.has(name)) return "protected-builtin";
795
+ return null;
796
+ }
797
+ isBlocked(name) {
798
+ return this.blockReason(name) !== null;
799
+ }
800
+ };
801
+ /** Build a GateSet from the curator-style config field names. */
802
+ function createGateSet(config) {
803
+ return new EvolutionGateSet({
804
+ exclude: config.excludeSkillNames,
805
+ referenced: config.referencedSkillNames,
806
+ suppressed: config.suppressedNames
807
+ });
808
+ }
809
+ //#endregion
810
+ //#region lib/types/curator.js
811
+ /**
812
+ * Deterministic skill curator: active → stale → archived transitions.
813
+ * Pure function with one deliberate side effect: records in the passed
814
+ * `usage` map are MUTATED (state/archived_at) to carry the transition — the
815
+ * caller owns the map and decides whether to clone first (dry-run) or persist
816
+ * after. File moves are performed by SkillLibrary.
817
+ */
818
+ function buildCuratorRunReport(input) {
819
+ return {
820
+ schemaVersion: 1,
821
+ runId: input.runId,
822
+ startedAt: input.startedAt,
823
+ finishedAt: input.finishedAt,
824
+ staleCandidates: [...input.staleCandidates],
825
+ llmNominations: [...input.llmNominations],
826
+ archiveCandidates: [...input.archiveCandidates],
827
+ archived: [...input.archived],
828
+ failed: [...input.failed],
829
+ ...input.aborted === void 0 ? {} : { aborted: input.aborted },
830
+ ...input.unattributed === void 0 || input.unattributed.length === 0 ? {} : { unattributed: [...input.unattributed] },
831
+ ...input.consolidated === void 0 ? {} : { consolidated: [...input.consolidated] },
832
+ ...input.snapshotPath === void 0 ? {} : { snapshotPath: input.snapshotPath },
833
+ ...input.llmReviewEnabled === void 0 ? {} : { llmReviewEnabled: input.llmReviewEnabled },
834
+ ...input.nominationsWarnings === void 0 ? {} : { nominationsWarnings: [...input.nominationsWarnings] },
835
+ ...input.scanWarnings === void 0 ? {} : { scanWarnings: [...input.scanWarnings] },
836
+ ...input.wouldPrune === void 0 ? {} : { wouldPrune: input.wouldPrune === null ? null : [...input.wouldPrune] }
837
+ };
838
+ }
839
+ /**
840
+ * Render a curator run report as a compact human-readable markdown digest
841
+ * (G6): run metadata first, then the notable sections (archived / failed /
842
+ * stale candidates / LLM nominations).
843
+ */
844
+ function renderCuratorReportMarkdown(report) {
845
+ const lines = [
846
+ `# Curator run ${report.runId}`,
847
+ "",
848
+ `- **Started** ${report.startedAt}`,
849
+ `- **Finished** ${report.finishedAt}`,
850
+ `- **Stale candidates**: ${report.staleCandidates.length}`,
851
+ `- **LLM nominations**: ${report.llmNominations.length}`,
443
852
  `- **Archived**: ${report.archived.length}`,
444
853
  `- **Failed**: ${report.failed.length}`,
445
854
  ...report.aborted === void 0 ? [] : [`- **Aborted**: ${report.aborted}`],
@@ -761,6 +1170,14 @@ function previewEntries(entries) {
761
1170
  const more = entries.length > ERROR_PREVIEW_ENTRIES ? `\n (+${entries.length - ERROR_PREVIEW_ENTRIES} more)` : "";
762
1171
  return `\n\nCurrent entries (preview):\n${shown.join("\n")}${more}`;
763
1172
  }
1173
+ /** Count one entry list in both units; empty is zero in both. */
1174
+ function usageOf(entries) {
1175
+ const text = entries.join(ENTRY_DELIMITER);
1176
+ return {
1177
+ chars: text.length,
1178
+ tokens: text.length === 0 ? 0 : measureText(text).tokens.value
1179
+ };
1180
+ }
764
1181
  function memoryRoot(env = process.env) {
765
1182
  return join(evolutionRoot(env), "memories");
766
1183
  }
@@ -787,6 +1204,8 @@ function hasEntryDelimiter(content) {
787
1204
  var MemoryStore = class {
788
1205
  memoryLimit;
789
1206
  userLimit;
1207
+ memoryTokenLimit;
1208
+ userTokenLimit;
790
1209
  addDatePrefix;
791
1210
  root;
792
1211
  maxFailures;
@@ -805,8 +1224,10 @@ var MemoryStore = class {
805
1224
  constructor(options = {}) {
806
1225
  this.io = options.io ?? nodeEvolutionIo();
807
1226
  this.fence = options.fence;
808
- this.memoryLimit = options.memoryCharLimit ?? 2200;
809
- this.userLimit = options.userCharLimit ?? 1375;
1227
+ this.memoryTokenLimit = options.memoryTokenLimit;
1228
+ this.userTokenLimit = options.userTokenLimit;
1229
+ this.memoryLimit = options.memoryTokenLimit ?? options.memoryCharLimit ?? 2200;
1230
+ this.userLimit = options.userTokenLimit ?? options.userCharLimit ?? 1375;
810
1231
  this.addDatePrefix = options.addDatePrefix ?? false;
811
1232
  this.root = options.root ?? memoryRoot();
812
1233
  this.maxFailures = options.maxConsolidationFailures ?? 3;
@@ -825,6 +1246,39 @@ var MemoryStore = class {
825
1246
  limitFor(target) {
826
1247
  return target === "memory" ? this.memoryLimit : this.userLimit;
827
1248
  }
1249
+ /** Token budget when the target opted into token mode; undefined keeps legacy chars. */
1250
+ tokenLimitFor(target) {
1251
+ return target === "memory" ? this.memoryTokenLimit : this.userTokenLimit;
1252
+ }
1253
+ /** The value the active gate compares: tokens in token mode, UTF-16 chars otherwise. */
1254
+ judgedValue(target, usage) {
1255
+ return this.tokenLimitFor(target) === void 0 ? usage.chars : usage.tokens;
1256
+ }
1257
+ /** Unit noun for model-facing messages; legacy mode keeps its old wording. */
1258
+ unitFor(target) {
1259
+ return this.tokenLimitFor(target) === void 0 ? "chars" : "tokens";
1260
+ }
1261
+ /**
1262
+ * Byte ceiling for the oversized-read guard. It is NOT the token budget:
1263
+ * a token cannot be compared to bytes. Token mode uses a conservative byte
1264
+ * envelope so a canonical English/CJK file is never mistaken for corruption.
1265
+ */
1266
+ byteGuardFor(target) {
1267
+ const tokenLimit = this.tokenLimitFor(target);
1268
+ if (tokenLimit === void 0) return this.limitFor(target) * READ_GUARD_FACTOR;
1269
+ return Math.max(16 * 1024, tokenLimit * 4 * READ_GUARD_FACTOR);
1270
+ }
1271
+ /** Add the public dual-unit facts to one internal result. */
1272
+ decorateResult(target, result) {
1273
+ const usage = usageOf(result.entries);
1274
+ const tokenLimit = this.tokenLimitFor(target);
1275
+ return {
1276
+ ...result,
1277
+ chars: usage.chars,
1278
+ tokens: usage.tokens,
1279
+ ...tokenLimit === void 0 ? {} : { tokenLimit }
1280
+ };
1281
+ }
828
1282
  /** P2-1 (v18): the generated date prefix participates in duplicate detection
829
1283
  * only when THIS store writes it. With addDatePrefix=false a fact's own
830
1284
  * leading `## YYYY-MM-DD\n` is content, not a generated prefix. */
@@ -832,19 +1286,19 @@ var MemoryStore = class {
832
1286
  return this.addDatePrefix ? stripDatePrefix(entry) : entry;
833
1287
  }
834
1288
  /**
835
- * Read-guard probe: `{ size, limit }` when the on-disk file exceeds
836
- * `limit * READ_GUARD_FACTOR` bytes, `null` when it is absent, unknown
837
- * (backend without a size probe), under the bound, or the target has no
838
- * limit configured.
1289
+ * Read-guard probe: `{ size, byteLimit }` when the on-disk file exceeds the
1290
+ * target's byte ceiling, `null` when it is absent, unknown, under the bound,
1291
+ * or the target has no limit configured. The ceiling is bytes, never the
1292
+ * token/char budget itself.
839
1293
  */
840
1294
  async oversizedFile(target) {
841
1295
  const size = await this.io.size?.(fileFor(this.root, target));
842
1296
  if (size === null || size === void 0) return null;
843
- const limit = this.limitFor(target);
844
- if (limit <= 0) return null;
845
- return size > limit * READ_GUARD_FACTOR ? {
1297
+ if (this.limitFor(target) <= 0) return null;
1298
+ const byteLimit = this.byteGuardFor(target);
1299
+ return size > byteLimit ? {
846
1300
  size,
847
- limit
1301
+ byteLimit
848
1302
  } : null;
849
1303
  }
850
1304
  async read(target) {
@@ -877,14 +1331,15 @@ var MemoryStore = class {
877
1331
  }
878
1332
  /**
879
1333
  * StorageHint percentage must clamp at 100 like the render header: a drifted
880
- * entry can push chars past the limit, and "Storage at 125%" contradicts the
881
- * clamped usage indicator.
1334
+ * entry can push usage past the limit, and "Storage at 125%" contradicts the
1335
+ * clamped usage indicator. The percentage is computed in the ACTIVE unit.
882
1336
  */
883
- storageHint(target, chars) {
1337
+ storageHint(target, usage) {
884
1338
  const limit = this.limitFor(target);
885
1339
  if (limit <= 0) return "";
886
- const percent = Math.min(100, Math.floor(chars * 100 / limit));
887
- return percent >= 80 ? ` ⚠️ Storage at ${percent}% (${chars}/${limit} chars).` : "";
1340
+ const value = this.judgedValue(target, usage);
1341
+ const percent = Math.min(100, Math.floor(value * 100 / limit));
1342
+ return percent >= 80 ? ` ⚠️ Storage at ${percent}% (${value}/${limit} ${this.unitFor(target)}).` : "";
888
1343
  }
889
1344
  /**
890
1345
  * Best-effort raw-copy backup of the on-disk file to `<file>.bak` before a
@@ -928,7 +1383,7 @@ var MemoryStore = class {
928
1383
  const suffix = backup ? ` 已把备份保存到 ${basename(backup)}。` : "";
929
1384
  return {
930
1385
  ok: false,
931
- message: `记忆文件为 ${oversized.size} 字节(上限 ${oversized.limit * READ_GUARD_FACTOR})—— 跳过读取。${suffix} 请手动修复该文件后重试。`,
1386
+ message: `记忆文件为 ${oversized.size} 字节(上限 ${oversized.byteLimit})—— 跳过读取。${suffix} 请手动修复该文件后重试。`,
932
1387
  entries: [],
933
1388
  chars: 0,
934
1389
  limit: this.limitFor(target)
@@ -990,7 +1445,7 @@ var MemoryStore = class {
990
1445
  };
991
1446
  }
992
1447
  async add(target, facts) {
993
- return await this.serial(() => this.addChained(target, facts));
1448
+ return await this.serial(async () => this.decorateResult(target, await this.addChained(target, facts)));
994
1449
  }
995
1450
  async addChained(target, facts) {
996
1451
  if (!facts.trim()) return {
@@ -1049,31 +1504,35 @@ var MemoryStore = class {
1049
1504
  const entries = [...new Set(normalizeEntries(raw))];
1050
1505
  if (entries.some((entry) => this.dedupeKey(entry) === content)) {
1051
1506
  this.resetFailures();
1507
+ const usage = usageOf(entries);
1052
1508
  return {
1053
1509
  result: {
1054
1510
  ok: true,
1055
- message: `该条目已存在(未重复添加)。${this.storageHint(target, entries.join(ENTRY_DELIMITER).length)}`,
1511
+ message: `该条目已存在(未重复添加)。${this.storageHint(target, usage)}`,
1056
1512
  entries,
1057
- chars: entries.join(ENTRY_DELIMITER).length,
1513
+ chars: usage.chars,
1514
+ tokens: usage.tokens,
1058
1515
  limit: this.limitFor(target)
1059
1516
  },
1060
1517
  write: null
1061
1518
  };
1062
1519
  }
1063
1520
  const next = [...entries, prefixed];
1064
- const total = next.join(ENTRY_DELIMITER).length;
1521
+ const usage = usageOf(next);
1522
+ const total = this.judgedValue(target, usage);
1065
1523
  const addLimit = this.limitFor(target);
1066
1524
  if (addLimit > 0 && total > addLimit) return {
1067
- result: this.failure(target, `添加该条目会超过 ${addLimit} 字符上限。请先合并或删除过期条目,再重试。`, entries),
1525
+ result: this.failure(target, `添加该条目会超过 ${addLimit} ${this.unitFor(target)} 上限。请先合并或删除过期条目,再重试。`, entries),
1068
1526
  write: null
1069
1527
  };
1070
1528
  this.resetFailures();
1071
1529
  return {
1072
1530
  result: {
1073
1531
  ok: true,
1074
- message: `已添加条目。${this.storageHint(target, total)}`,
1532
+ message: `已添加条目。${this.storageHint(target, usage)}`,
1075
1533
  entries: next,
1076
- chars: total,
1534
+ chars: usage.chars,
1535
+ tokens: usage.tokens,
1077
1536
  limit: this.limitFor(target)
1078
1537
  },
1079
1538
  write: render(next)
@@ -1117,7 +1576,7 @@ var MemoryStore = class {
1117
1576
  const entries = normalizeEntries(raw);
1118
1577
  if (render(entries) !== raw) return "external";
1119
1578
  const limit = this.limitFor(target);
1120
- if (limit > 0 && entries.some((entry) => entry.length > limit)) return "over-limit";
1579
+ if (limit > 0 && entries.some((entry) => this.judgedValue(target, usageOf([entry])) > limit)) return "over-limit";
1121
1580
  return null;
1122
1581
  }
1123
1582
  /** External-drift predicate: canonical-form violations only (see
@@ -1148,11 +1607,14 @@ var MemoryStore = class {
1148
1607
  if (shrinkOnly) return null;
1149
1608
  const limit = this.limitFor(target);
1150
1609
  const entries = normalizeEntries(raw);
1610
+ const over = entries.filter((entry) => this.judgedValue(target, usageOf([entry])) > limit).length;
1611
+ const usage = usageOf(entries);
1151
1612
  return {
1152
1613
  ok: false,
1153
- message: `${entries.filter((entry) => entry.length > limit).length} 条记忆超过了配置的 ${target}CharLimit(${limit});它们是在更高上限下写入的。请提高上限或删除条目 —— 删除类操作仍然可用。`,
1614
+ message: `${over} 条记忆超过了配置的 ${this.tokenLimitFor(target) === void 0 ? target === "memory" ? "memoryCharLimit" : "userCharLimit" : `${target} tokens`}(${limit});它们是在更高上限下写入的。请提高上限或删除条目 —— 删除类操作仍然可用。`,
1154
1615
  entries,
1155
- chars: entries.join(ENTRY_DELIMITER).length,
1616
+ chars: usage.chars,
1617
+ tokens: usage.tokens,
1156
1618
  limit
1157
1619
  };
1158
1620
  }
@@ -1166,7 +1628,7 @@ var MemoryStore = class {
1166
1628
  };
1167
1629
  }
1168
1630
  async applyBatch(target, operations) {
1169
- return await this.serial(() => this.applyBatchChained(target, operations));
1631
+ return await this.serial(async () => this.decorateResult(target, await this.applyBatchChained(target, operations)));
1170
1632
  }
1171
1633
  async applyBatchChained(target, operations) {
1172
1634
  if (operations.length === 0) return {
@@ -1307,19 +1769,21 @@ var MemoryStore = class {
1307
1769
  working[matchIndex] = entryBody;
1308
1770
  }
1309
1771
  }
1310
- const total = working.join(ENTRY_DELIMITER).length;
1772
+ const usage = usageOf(working);
1773
+ const total = this.judgedValue(target, usage);
1311
1774
  const batchLimit = this.limitFor(target);
1312
1775
  if (batchLimit > 0 && total > batchLimit) return {
1313
- result: this.failure(target, `批处理结果(${total} 字符)超过 ${batchLimit} 上限。请在同一个批里再删除或缩短一些条目。`, entries),
1776
+ result: this.failure(target, `批处理结果(${total} ${this.unitFor(target)})超过 ${batchLimit} 上限。请在同一个批里再删除或缩短一些条目。`, entries),
1314
1777
  write: null
1315
1778
  };
1316
1779
  this.resetFailures();
1317
1780
  return {
1318
1781
  result: {
1319
1782
  ok: true,
1320
- message: `已应用 ${operations.length} 个操作。${this.storageHint(target, total)}`,
1783
+ message: `已应用 ${operations.length} 个操作。${this.storageHint(target, usage)}`,
1321
1784
  entries: working,
1322
- chars: total,
1785
+ chars: usage.chars,
1786
+ tokens: usage.tokens,
1323
1787
  limit: this.limitFor(target)
1324
1788
  },
1325
1789
  write: render(working)
@@ -1340,16 +1804,18 @@ var MemoryStore = class {
1340
1804
  ]]) {
1341
1805
  const oversized = entries.length === 0 ? await this.oversizedFile(target) : null;
1342
1806
  if (oversized) {
1343
- parts.push(`## ${label} — file skipped: ${oversized.size} bytes (limit ${oversized.limit * READ_GUARD_FACTOR}); not read`);
1807
+ parts.push(`## ${label} — file skipped: ${oversized.size} bytes (limit ${oversized.byteLimit}); not read`);
1344
1808
  continue;
1345
1809
  }
1346
1810
  const safe = entries.filter((entry) => !scanMemoryThreats(entry, void 0, this.threatScanOptions()));
1347
1811
  if (safe.length > 0) {
1348
1812
  const body = safe.join(ENTRY_DELIMITER);
1349
1813
  const limit = this.limitFor(target);
1814
+ const usage = usageOf(safe);
1815
+ const judged = this.judgedValue(target, usage);
1350
1816
  const note = safe.length === entries.length ? "" : ` (${entries.length - safe.length} threat-matched entries filtered)`;
1351
- const usage = limit > 0 ? ` [${Math.min(100, Math.floor(body.length * 100 / limit))}% — ${body.length}/${limit} chars]` : "";
1352
- parts.push(`## ${label} (${safe.length} entries)${usage}${note}\n${body}`);
1817
+ const usageText = limit > 0 ? ` [${Math.min(100, Math.floor(judged * 100 / limit))}% — ${judged}/${limit} ${this.unitFor(target)}]` : "";
1818
+ parts.push(`## ${label} (${safe.length} entries)${usageText}${note}\n${body}`);
1353
1819
  } else if (entries.length > 0) parts.push(`## ${label} — ${entries.length} entries withheld by the security scan; none injected`);
1354
1820
  }
1355
1821
  return parts.join("\n\n");
@@ -1561,7 +2027,7 @@ A. 域·碎片化
1561
2027
  - A3 {signal:prefix_cluster}=over:判簇内是否同伞;非同伞→notes 提域划分观察,不强制建伞。
1562
2028
 
1563
2029
  B. 层·分层错位
1564
- - B1 {signal:stamp_density}(阈值 {signal:stamp_density.threshold})或 {signal:body_size}(阈值 {signal:body_size.threshold})=over:按**三问判据**判锚/残留——① 该编号/时间戳是否被库内其他文件引用?② 除"何时产生/为何存在"外是否还承载信息?③ 删除是否影响任何跨文档检索?(①是且③是→锚;否则→残留候选,人审)。锚→允许保留 + needs_human + semantic_reasoning 写三问结果;**锚不使用 is_override**(is_override 仅用于 §7 申诉;锚是 B1 的正常裁决路径);残留→restructure 建议(movable headings 逐字引用)。**锚≠可读:单行 >4000 字符即使在锚类也必须拆分。** **软带(authoring band)**:\`body_size\` 的 value 形如 \`<tokens> tokens / <chars> chars\`,threshold 是上游「超 20k 字符就该拆」那条线**按本正文成分**折出的 token 线;detail 里的 \`body=Nx\` 是当前倍数(恒等于 字符 ÷ 20,000;全库目标带 8–14k 字符)——倍数越大越优先拆:用 restructure 把 log 状整节搬进 references/*.md 并留钩子;**不要靠删证据来降成本**。
2030
+ - B1 {signal:stamp_density}(阈值 {signal:stamp_density.threshold})或 {signal:body_size}(阈值 {signal:body_size.threshold})=over:按**三问判据**判锚/残留——① 该编号/时间戳是否被库内其他文件引用?② 除"何时产生/为何存在"外是否还承载信息?③ 删除是否影响任何跨文档检索?(①是且③是→锚;否则→残留候选,人审)。锚→允许保留 + needs_human + semantic_reasoning 写三问结果;**锚不使用 is_override**(is_override 仅用于 §7 申诉;锚是 B1 的正常裁决路径);残留→restructure 建议(movable headings 逐字引用)。**锚≠可读:单行 >4000 字符即使在锚类也必须拆分。** **软带(authoring band)**:\`body_size\` 的 value 形如 \`<tokens> tokens / <chars> chars\`,threshold 是**固定 token 预算**(当前默认 7,273;不再按正文成分折算);detail 里的 \`body=Nx\` 是 \`估算 tokens ÷ 7,273\`,不是字符数除以 20,000——倍数越大越优先拆。参考:中文约 7.3k 字符、英文约 21.8k 字符触及默认线。用 restructure 把 log 状整节搬进 references/*.md 并留钩子;**不要靠删证据来降成本**。
1565
2031
  - B2 {signal:pointer_missing}=over:读支持文件后判性质——可复用模式→上移正文;会话专属实录→保留+补指针;形态=patch 指引。**未读内容仅凭文件名 → conf≤0.4 且措辞"先人工确认再执行"。** **缺失指针=支持文件存在、正文无引用(单向语义),finding 表述勿反向。** detail 里的 \`unhooked=N\` 是**被正文提及但不成钩子形态**的文件:它们不算缺失(verdict 不变),但搬迁后正文只剩裸文件名,注意力难以命中——指引是把该行改成 \`- <症状或问句> → references/x.md\`。
1566
2032
  - B3 {signal:dup_heading}=over:删除多余标题行(保留一份),patch 指引。
1567
2033
  - B4 {signal:overlong_line}=over:>1500 拆行;>4000 判定可读性危机(内容合法也拆);patch 指引。**finding 必须给全量口径:共 N 行超限,其中 >4000 的逐行列出。**
@@ -2728,404 +3194,139 @@ function claimInstance(home, key, owner) {
2728
3194
  if (current === void 0 || current === owner) {
2729
3195
  claims.set(id, owner);
2730
3196
  return {
2731
- granted: true,
2732
- key: id,
2733
- holder: owner
2734
- };
2735
- }
2736
- return {
2737
- granted: false,
2738
- key: id,
2739
- holder: current
2740
- };
2741
- }
2742
- /** Release only the claim `owner` took — never another instance's. */
2743
- function releaseInstance(home, key, owner) {
2744
- const id = instanceClaimKey(home, key);
2745
- if (claims.get(id) === owner) claims.delete(id);
2746
- }
2747
- /** The current holder of `key` at `home`, IN THIS PROCESS, or undefined
2748
- * (which also covers "another process holds it" — v43 FLOW2-1). */
2749
- function instanceHolder(home, key) {
2750
- return claims.get(instanceClaimKey(home, key));
2751
- }
2752
- //#endregion
2753
- //#region lib/types/write-inventory.js
2754
- /**
2755
- * B3 / G4 (0.3.78): the persisted-write inventory — WHICH file the family
2756
- * writes, WHO writes it, and WHAT keeps two writers apart.
2757
- *
2758
- * The table lives in `persisted-write-inventory.json` at the package root so
2759
- * the TypeScript side, the architecture gate (`verify-arch-guards` rule N20)
2760
- * and the regression specs read ONE file (the row-overrides.json pattern).
2761
- *
2762
- * "What keeps two writers apart" has exactly three answers in this family:
2763
- * - `transact` — the IO backend's cross-process write lock (transactIo);
2764
- * - `write-lock` — the per-target `<path>.lock` protocol of the skill tree;
2765
- * - `instance-claim` — the per-home single-instance claim (instance-scope.ts),
2766
- * for a writer whose sweeps cannot be expressed as one locked file.
2767
- * A site that answers with NONE of them is the "two instances, one file" class:
2768
- * a per-instance serial queue looks like serialization and is not.
2769
- * @module @lmzhen/dsh-evolution-core/src/write-inventory
2770
- */
2771
- const SITES_URL = new URL("../persisted-write-inventory.json", import.meta.url);
2772
- const SERIALIZATIONS = [
2773
- "transact",
2774
- "write-lock",
2775
- "instance-claim",
2776
- "platform-file-lock"
2777
- ];
2778
- /** Parse + validate the table. A malformed table throws at import: a table the
2779
- * gate cannot read must never degrade into "no declared write sites". */
2780
- function parseTable(raw) {
2781
- if (raw === null || typeof raw !== "object" || Array.isArray(raw)) throw new Error("evolution-core: persisted-write-inventory.json must be an object with { symbols, sites }");
2782
- const table = raw;
2783
- if (table.symbols === null || typeof table.symbols !== "object" || Array.isArray(table.symbols)) throw new Error("evolution-core: persisted-write-inventory.json needs a symbols legend (the roots every path is written against)");
2784
- for (const [symbol, entry] of Object.entries(table.symbols)) {
2785
- const problems = [];
2786
- if (!symbol.startsWith("<") || !symbol.endsWith(">")) problems.push("symbol name (must be <name>)");
2787
- if (entry === null || typeof entry !== "object") problems.push("entry");
2788
- else {
2789
- const symbolEntry = entry;
2790
- if (typeof symbolEntry.resolver !== "string" || symbolEntry.resolver === "") problems.push("resolver");
2791
- if (symbolEntry.segments !== void 0 && (!Array.isArray(symbolEntry.segments) || symbolEntry.segments.some((segment) => typeof segment !== "string"))) problems.push("segments");
2792
- }
2793
- if (problems.length > 0) throw new Error(`evolution-core: persisted-write-inventory.json symbol ${symbol} is malformed (missing/invalid: ${problems.join(", ")})`);
2794
- }
2795
- if (!Array.isArray(table.sites)) throw new Error("evolution-core: persisted-write-inventory.json needs a sites array");
2796
- const sites = [];
2797
- for (const [index, entry] of table.sites.entries()) {
2798
- const site = entry;
2799
- const problems = [];
2800
- if (typeof site.id !== "string" || site.id === "") problems.push("id");
2801
- if (typeof site.path !== "string" || site.path === "") problems.push("path");
2802
- if (typeof site.writer !== "string" || site.writer === "") problems.push("writer");
2803
- if (typeof site.marker !== "string" || site.marker === "") problems.push("marker");
2804
- if (typeof site.serializedBy !== "string" || !SERIALIZATIONS.includes(site.serializedBy)) problems.push("serializedBy");
2805
- if (site.serializedBy === "instance-claim" && typeof site.instance !== "string") problems.push("instance");
2806
- if (!Array.isArray(site.state)) problems.push("state");
2807
- if (problems.length > 0) throw new Error(`evolution-core: persisted-write-inventory.json entry ${index} is malformed (missing/invalid: ${problems.join(", ")})`);
2808
- sites.push({
2809
- id: site.id,
2810
- path: site.path,
2811
- writer: site.writer,
2812
- serializedBy: site.serializedBy,
2813
- marker: site.marker,
2814
- ...typeof site.instance === "string" ? { instance: site.instance } : {},
2815
- state: site.state,
2816
- note: typeof site.note === "string" ? site.note : ""
2817
- });
2818
- }
2819
- if (new Set(sites.map((site) => site.id)).size !== sites.length) throw new Error("evolution-core: persisted-write-inventory.json declares duplicate site ids");
2820
- return {
2821
- symbols: table.symbols,
2822
- sites
2823
- };
2824
- }
2825
- /** Instance keys held by writer services — the single source shared by the
2826
- * claim site and the inventory row that declares it (rule N20 checks the row's
2827
- * `instance` names one of these). */
2828
- const INSTANCE_KEYS = {
2829
- /** The per-home curator: report writing + the retention sweep. */
2830
- curator: "evolution-curator" };
2831
- let cachedSites;
2832
- /**
2833
- * The declared persisted write sites, in file order.
2834
- *
2835
- * v43 audit (S2-3 / P1-10): this used to be a module-scope readFileSync plus
2836
- * parse, so an unshipped asset threw AT IMPORT — one absent file took the whole
2837
- * family's load down (0.3.79 shipped a tarball without this asset and every
2838
- * package failed to load). The read is lazy now: importing the package never
2839
- * fails on this asset, while the first caller still gets a loud, descriptive
2840
- * failure instead of an empty table ("no declared write sites" would silently
2841
- * disable rule N20).
2842
- * @internal S2.4 (PLAN 2026-09-16): no production caller — the arch guard
2843
- * reads the JSON asset directly; the tests are the only in-tree consumers.
2844
- * @returns the sites, in file order.
2845
- */
2846
- function persistedWriteSites() {
2847
- if (cachedSites !== void 0) return cachedSites;
2848
- let raw;
2849
- try {
2850
- raw = readFileSync(fileURLToPath(SITES_URL), "utf8");
2851
- } catch (error) {
2852
- const cause = error instanceof Error ? error.message : String(error);
2853
- throw new Error(`evolution-core: persisted-write-inventory.json is unreadable (${cause}) — the package asset is missing or was not shipped; the write-inventory rules cannot be evaluated without it`);
2854
- }
2855
- const table = parseTable(JSON.parse(raw));
2856
- cachedSites = table.sites;
2857
- return table.sites;
2858
- }
2859
- //#endregion
2860
- //#region lib/types/scope.js
2861
- function callingScope(ctx, held) {
2862
- if (held !== void 0) return held;
2863
- return scopeOf(ctx);
2864
- }
2865
- //#endregion
2866
- //#region lib/types/drift-signals.js
2867
- /**
2868
- * Library-level drift signals for the maintenance subagent (design 011).
2869
- *
2870
- * Deterministic fact checks over a skill-library snapshot: domain drift
2871
- * (narrow names, near-duplicate groups, prefix clusters) and layer drift
2872
- * (log-like bodies, duplicate headings, overlong lines, missing support-file
2873
- * pointers, description over the authoring bar). Pure functions only — no IO,
2874
- * no LLM, no services. Thresholds are imported from their owning modules
2875
- * (skill-health / quality / skill-store), never duplicated.
2876
- *
2877
- * Distinct from `signals.ts` — the session-level review signal gate.
2878
- */
2879
- /** Physical line length at/above which a body line is reported overlong (011 §4). */
2880
- const DRIFT_MAX_LINE_CHARS = 1500;
2881
- /** Signal-set version: bump whenever ids/thresholds change (011 §7 version coupling). */
2882
- const DRIFT_SIGNALS_VERSION = "3";
2883
- /** Render-time nouns for the MAINTAIN_PROMPT placeholders (single vocabulary with the facts block). */
2884
- const DRIFT_SIGNAL_NOUNS = {
2885
- dedup_group: "近重复组",
2886
- prefix_cluster: "前缀聚类",
2887
- stamp_density: "stamp 密度",
2888
- body_size: "正文体量",
2889
- dup_heading: "重复标题",
2890
- overlong_line: "超长行",
2891
- pointer_missing: "缺失指针",
2892
- citation_resolution: "引用解析",
2893
- demand: "需求证据",
2894
- description_chars: "描述长度",
2895
- narrow_name: "窄名",
2896
- usage_observed: "使用观察",
2897
- quality_low: "质量分"
2898
- };
2899
- const NARROW_NAME_PATTERNS = [
2900
- {
2901
- label: "error-string",
2902
- re: /^(?:err|error|exception|traceback|warn|fail)(?:[-_][a-z0-9]+)+$/i
2903
- },
2904
- {
2905
- label: "pr-number",
2906
- re: /^(?:pr|issue)[-_]?\d{2,}$/i
2907
- },
2908
- {
2909
- label: "dated",
2910
- re: /\d{4}-\d{2}-\d{2}/
2911
- },
2912
- {
2913
- label: "session-verb",
2914
- re: /^(?:fix|debug|audit|salvage|diagnose|investigate)[-_][a-z0-9-]+$/i
2915
- }
2916
- ];
2917
- /** Detect support files the body never references (by basename or relative path). */
2918
- function missingSupportPointers(body, supportFiles) {
2919
- return supportFiles.filter((path) => {
2920
- const base = path.split("/").pop() ?? path;
2921
- return base.length > 0 && !body.includes(base) && !body.includes(path);
2922
- });
2923
- }
2924
- /** Support files the body mentions WITHOUT the sanctioned hook form (design
2925
- * §5.6). Such a mention still counts as a pointer for `pointer_missing`, but
2926
- * only the hook form keeps the file discoverable after a move — detail only.
2927
- * A file carrying a `keep` marker is exempt: its mention IS the marker. */
2928
- function unhookedSupportPointers(body, supportFiles) {
2929
- const { targets, kept } = scanBodyHooks(body);
2930
- const hooked = new Set(targets);
2931
- return supportFiles.filter((path) => {
2932
- if (!isFileShapedPath(path)) return false;
2933
- const base = path.split("/").pop() ?? path;
2934
- if (kept.has(path) || base.length > 0 && kept.has(base)) return false;
2935
- return (base.length > 0 && body.includes(base) || body.includes(path)) && !hooked.has(path) && !hooked.has(base);
2936
- });
2937
- }
2938
- /** Support files with no readers, no citations and no `keep` marker whose owning
2939
- * skill has been idle for at least the lifecycle stale window. PROPOSAL INPUT
2940
- * only — nothing retires a file on its own — and an unmeasurable input (no age
2941
- * evidence, no citation scan) yields an empty list WITH its reason, never a
2942
- * silent "nothing qualifies".
2943
- * @param snapshot - the skill's drift snapshot.
2944
- * @param supportFiles - its enumerated support files, in listing order.
2945
- * @returns the candidates plus the status that explains an empty list.
2946
- */
2947
- function retirementReport(snapshot, supportFiles) {
2948
- const idle = snapshot.liveness?.idleDays;
2949
- if (idle === void 0) return {
2950
- candidates: [],
2951
- status: "no-age"
2952
- };
2953
- if (snapshot.citations === void 0) return {
2954
- candidates: [],
2955
- status: "unscanned"
2956
- };
2957
- if (idle < 30) return {
2958
- candidates: [],
2959
- status: "none"
2960
- };
2961
- const cited = /* @__PURE__ */ new Set();
2962
- for (const ref of snapshot.citations.refs) if (ref.kind === "citation" && ref.target !== null) cited.add(ref.target);
2963
- const { kept } = scanBodyHooks(snapshot.body);
2964
- const demand = snapshot.demand ?? {};
2965
- const candidates = supportFiles.filter((path) => isFileShapedPath(path) && (demand[path] ?? 0) === 0 && !cited.has(path) && !kept.has(path)).map((path) => ({
2966
- path,
2967
- idleDays: Math.floor(idle)
2968
- }));
2969
- return {
2970
- candidates,
2971
- status: candidates.length === 0 ? "none" : "listed"
2972
- };
2973
- }
2974
- /** Duplicate `## heading` occurrences: singleton results default to head of the file. */
2975
- function duplicateHeadings(body) {
2976
- const counts = /* @__PURE__ */ new Map();
2977
- for (const raw of body.split("\n")) {
2978
- const line = raw.endsWith("\r") ? raw.slice(0, -1) : raw;
2979
- const m = /^##\s+(.+)$/.exec(line);
2980
- if (m?.[1]) {
2981
- const heading = m[1].trim();
2982
- if (heading) counts.set(heading, (counts.get(heading) ?? 0) + 1);
2983
- }
2984
- }
2985
- return [...counts.entries()].filter(([, count]) => count > 1).map(([heading, count]) => ({
2986
- heading,
2987
- count
2988
- }));
2989
- }
2990
- /** Physical lines over `max` characters: `{ lineNo, chars }`, 1-based line numbers. */
2991
- function overlongLines(body, max = DRIFT_MAX_LINE_CHARS) {
2992
- const out = [];
2993
- const lines = body.split("\n");
2994
- for (let index = 0; index < lines.length; index += 1) {
2995
- const raw = lines[index] ?? "";
2996
- const length = raw.endsWith("\r") ? raw.length - 1 : raw.length;
2997
- if (length > max) out.push({
2998
- lineNo: index + 1,
2999
- chars: length
3000
- });
3001
- }
3002
- return out;
3003
- }
3004
- /** Narrow-name shapes detected in a skill name (empty = none). */
3005
- function narrowNameMatches(name) {
3006
- return NARROW_NAME_PATTERNS.filter(({ re }) => re.test(name)).map(({ label }) => label);
3007
- }
3008
- function supportGroupCount(supportFiles) {
3009
- const groups = /* @__PURE__ */ new Set();
3010
- for (const path of supportFiles ?? []) {
3011
- const head = path.split("/")[0];
3012
- if (head) groups.add(head);
3197
+ granted: true,
3198
+ key: id,
3199
+ holder: owner
3200
+ };
3013
3201
  }
3014
- return groups.size;
3015
- }
3016
- function sig(id, verdict, value, threshold, detail) {
3017
3202
  return {
3018
- id,
3019
- verdict,
3020
- value,
3021
- threshold,
3022
- detail
3203
+ granted: false,
3204
+ key: id,
3205
+ holder: current
3023
3206
  };
3024
3207
  }
3208
+ /** Release only the claim `owner` took — never another instance's. */
3209
+ function releaseInstance(home, key, owner) {
3210
+ const id = instanceClaimKey(home, key);
3211
+ if (claims.get(id) === owner) claims.delete(id);
3212
+ }
3213
+ /** The current holder of `key` at `home`, IN THIS PROCESS, or undefined
3214
+ * (which also covers "another process holds it" — v43 FLOW2-1). */
3215
+ function instanceHolder(home, key) {
3216
+ return claims.get(instanceClaimKey(home, key));
3217
+ }
3218
+ //#endregion
3219
+ //#region lib/types/write-inventory.js
3025
3220
  /**
3026
- * Compute all drift signals for a snapshot. Missing inputs (quality score,
3027
- * usage window) yield `unknown` — never a fabricated verdict.
3221
+ * B3 / G4 (0.3.78): the persisted-write inventory — WHICH file the family
3222
+ * writes, WHO writes it, and WHAT keeps two writers apart.
3223
+ *
3224
+ * The table lives in `persisted-write-inventory.json` at the package root so
3225
+ * the TypeScript side, the architecture gate (`verify-arch-guards` rule N20)
3226
+ * and the regression specs read ONE file (the row-overrides.json pattern).
3227
+ *
3228
+ * "What keeps two writers apart" has exactly three answers in this family:
3229
+ * - `transact` — the IO backend's cross-process write lock (transactIo);
3230
+ * - `write-lock` — the per-target `<path>.lock` protocol of the skill tree;
3231
+ * - `instance-claim` — the per-home single-instance claim (instance-scope.ts),
3232
+ * for a writer whose sweeps cannot be expressed as one locked file.
3233
+ * A site that answers with NONE of them is the "two instances, one file" class:
3234
+ * a per-instance serial queue looks like serialization and is not.
3235
+ * @module @lmzhen/dsh-evolution-core/src/write-inventory
3028
3236
  */
3029
- function computeDriftSignals(snapshots) {
3030
- const library = [];
3031
- const names = snapshots.map((s) => s.name);
3032
- const dedup = computeDedupGroups({ contents: new Map(snapshots.map((s) => [s.name, s.body])) });
3033
- const dedupTruncation = dedup.truncated ? " (dedup scan truncated at the pair-comparison budget)" : "";
3034
- library.push(dedup.groups.length === 0 ? sig("dedup_group", "pass", `none${dedupTruncation}`, "size >= 2") : sig("dedup_group", "over", `${dedup.groups.map((group) => group.join(", ")).join(" | ")}${dedupTruncation}`, "size >= 2", `members=${dedup.groups.map((group) => group.join("|")).join(";")}`));
3035
- const clusters = computePrefixClusters(names);
3036
- library.push(clusters.length === 0 ? sig("prefix_cluster", "pass", "none", "size >= 2") : sig("prefix_cluster", "over", clusters.map((cluster) => cluster.members.join(", ")).join(" | "), "size >= 2", `key=${clusters.map((cluster) => cluster.key).join("|")}`));
3037
- const allProvided = snapshots.length > 0 && snapshots.every((s) => s.usageObserved !== null && s.usageObserved !== void 0);
3038
- library.push(!allProvided ? sig("usage_observed", "unknown", "not-observed", void 0, "usage window status missing") : snapshots.every((s) => s.usageObserved === true) ? sig("usage_observed", "pass", "observed") : sig("usage_observed", "pass", "unobserved"));
3237
+ const SITES_URL = new URL("../persisted-write-inventory.json", import.meta.url);
3238
+ const SERIALIZATIONS = [
3239
+ "transact",
3240
+ "write-lock",
3241
+ "instance-claim",
3242
+ "platform-file-lock"
3243
+ ];
3244
+ /** Parse + validate the table. A malformed table throws at import: a table the
3245
+ * gate cannot read must never degrade into "no declared write sites". */
3246
+ function parseTable(raw) {
3247
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw)) throw new Error("evolution-core: persisted-write-inventory.json must be an object with { symbols, sites }");
3248
+ const table = raw;
3249
+ if (table.symbols === null || typeof table.symbols !== "object" || Array.isArray(table.symbols)) throw new Error("evolution-core: persisted-write-inventory.json needs a symbols legend (the roots every path is written against)");
3250
+ for (const [symbol, entry] of Object.entries(table.symbols)) {
3251
+ const problems = [];
3252
+ if (!symbol.startsWith("<") || !symbol.endsWith(">")) problems.push("symbol name (must be <name>)");
3253
+ if (entry === null || typeof entry !== "object") problems.push("entry");
3254
+ else {
3255
+ const symbolEntry = entry;
3256
+ if (typeof symbolEntry.resolver !== "string" || symbolEntry.resolver === "") problems.push("resolver");
3257
+ if (symbolEntry.segments !== void 0 && (!Array.isArray(symbolEntry.segments) || symbolEntry.segments.some((segment) => typeof segment !== "string"))) problems.push("segments");
3258
+ }
3259
+ if (problems.length > 0) throw new Error(`evolution-core: persisted-write-inventory.json symbol ${symbol} is malformed (missing/invalid: ${problems.join(", ")})`);
3260
+ }
3261
+ if (!Array.isArray(table.sites)) throw new Error("evolution-core: persisted-write-inventory.json needs a sites array");
3262
+ const sites = [];
3263
+ for (const [index, entry] of table.sites.entries()) {
3264
+ const site = entry;
3265
+ const problems = [];
3266
+ if (typeof site.id !== "string" || site.id === "") problems.push("id");
3267
+ if (typeof site.path !== "string" || site.path === "") problems.push("path");
3268
+ if (typeof site.writer !== "string" || site.writer === "") problems.push("writer");
3269
+ if (typeof site.marker !== "string" || site.marker === "") problems.push("marker");
3270
+ if (typeof site.serializedBy !== "string" || !SERIALIZATIONS.includes(site.serializedBy)) problems.push("serializedBy");
3271
+ if (site.serializedBy === "instance-claim" && typeof site.instance !== "string") problems.push("instance");
3272
+ if (!Array.isArray(site.state)) problems.push("state");
3273
+ if (problems.length > 0) throw new Error(`evolution-core: persisted-write-inventory.json entry ${index} is malformed (missing/invalid: ${problems.join(", ")})`);
3274
+ sites.push({
3275
+ id: site.id,
3276
+ path: site.path,
3277
+ writer: site.writer,
3278
+ serializedBy: site.serializedBy,
3279
+ marker: site.marker,
3280
+ ...typeof site.instance === "string" ? { instance: site.instance } : {},
3281
+ state: site.state,
3282
+ note: typeof site.note === "string" ? site.note : ""
3283
+ });
3284
+ }
3285
+ if (new Set(sites.map((site) => site.id)).size !== sites.length) throw new Error("evolution-core: persisted-write-inventory.json declares duplicate site ids");
3039
3286
  return {
3040
- library,
3041
- skills: snapshots.map((snapshot) => {
3042
- const signals = [];
3043
- const body = snapshot.body;
3044
- const supportFiles = snapshot.supportFiles ?? [];
3045
- const supportEnumerated = snapshot.supportFiles !== void 0;
3046
- const density = assessStructureHealth({
3047
- skillName: snapshot.name,
3048
- bodyChars: body.length,
3049
- bodyText: body,
3050
- supportGroups: supportGroupCount(supportFiles)
3051
- }, DEFAULT_HEALTH_THRESHOLDS).dims.stampDensityPerKb;
3052
- signals.push(density === null ? sig("stamp_density", "pass", "below-min-body") : sig("stamp_density", density >= DEFAULT_HEALTH_THRESHOLDS.stampDensityPerKb ? "over" : "pass", `${density.toFixed(2)}/KB`, `${DEFAULT_HEALTH_THRESHOLDS.stampDensityPerKb}/KB`));
3053
- const cost = snapshot.cost;
3054
- const lineTokens = cost === void 0 ? null : tokenLineFor(DEFAULT_HEALTH_THRESHOLDS.softBodyChars, cost);
3055
- const overLine = cost === void 0 || lineTokens === null ? body.length >= DEFAULT_HEALTH_THRESHOLDS.softBodyChars : cost.tokens >= lineTokens;
3056
- signals.push(sig("body_size", overLine ? "over" : "pass", cost === void 0 ? `${body.length}` : `${cost.tokens} tokens / ${body.length} chars`, cost === void 0 || lineTokens === null ? `${DEFAULT_HEALTH_THRESHOLDS.softBodyChars}` : `line=${lineTokens} tokens (${DEFAULT_HEALTH_THRESHOLDS.softBodyChars} chars)`, cost === void 0 ? void 0 : `estimate range ${cost.tokensLow}-${cost.tokensHigh} tokens (4 chars/token basis); cjk=${cost.cjk}${lineTokens === null ? "" : `; line=${lineTokens}, body=${(cost.tokens / lineTokens).toFixed(1)}x`}${oversizeSupportNote(snapshot.supportChars)}`));
3057
- const dupes = duplicateHeadings(body);
3058
- signals.push(dupes.length === 0 ? sig("dup_heading", "pass", "none") : sig("dup_heading", "over", dupes.map((d) => `${d.heading}(${d.count})`).join(", "), "count >= 2"));
3059
- const long = overlongLines(body);
3060
- signals.push(long.length === 0 ? sig("overlong_line", "pass", "none") : sig("overlong_line", "over", long.map((l) => `${l.lineNo}:${l.chars}`).join(", "), `${DRIFT_MAX_LINE_CHARS}`));
3061
- const missing = supportEnumerated ? missingSupportPointers(body, supportFiles) : void 0;
3062
- const unhooked = supportEnumerated ? unhookedSupportPointers(body, supportFiles) : [];
3063
- const unhookedDetail = unhooked.length === 0 ? void 0 : `unhooked=${unhooked.length}: ${unhooked.slice(0, 5).join(", ")}`;
3064
- signals.push(!supportEnumerated ? sig("pointer_missing", "unknown", "not-enumerated", void 0, "support files not enumerated") : (missing ?? []).length === 0 ? sig("pointer_missing", "pass", "none", void 0, unhookedDetail) : sig("pointer_missing", "over", missing?.join(", ") ?? "", void 0, unhookedDetail));
3065
- signals.push(citationSignal(snapshot.citations));
3066
- signals.push(demandSignal(snapshot, supportFiles, supportEnumerated));
3067
- const narrow = narrowNameMatches(snapshot.name);
3068
- signals.push(narrow.length === 0 ? sig("narrow_name", "pass", "none") : sig("narrow_name", "over", narrow.join(", "), void 0, `name=${snapshot.name}`));
3069
- const description = snapshot.description;
3070
- signals.push(description === void 0 ? sig("description_chars", "unknown", "missing", `60`) : sig("description_chars", description.length > 60 ? "over" : "pass", `${description.length}`, `60`));
3071
- const quality = snapshot.quality;
3072
- signals.push(quality === null || quality === void 0 ? sig("quality_low", "unknown", "not-assessed") : sig("quality_low", quality < .3 ? "over" : "pass", quality.toFixed(2), `${LOW_QUALITY_THRESHOLD}`));
3073
- return {
3074
- name: snapshot.name,
3075
- signals,
3076
- ...snapshot.protected !== void 0 && snapshot.protected !== null ? { protected: snapshot.protected } : {},
3077
- ...snapshot.catalogInvalid !== void 0 ? { catalogInvalid: snapshot.catalogInvalid } : {}
3078
- };
3079
- })
3287
+ symbols: table.symbols,
3288
+ sites
3080
3289
  };
3081
3290
  }
3082
- /** Dangling-citation verdict: a partial scan is `unknown`, never a clean pass. */
3083
- function citationSignal(citations) {
3084
- if (citations === void 0) return sig("citation_resolution", "unknown", "not-scanned", void 0, "support-file list missing");
3085
- if (citations.truncated) return sig("citation_resolution", "unknown", `truncated at ${citations.refs.length} refs`, void 0, "partial scan — not a clean verdict");
3086
- const cited = citations.refs.filter((ref) => ref.kind === "citation");
3087
- if (citations.dangling.length > 0) {
3088
- const missing = citations.dangling.slice(0, 5).map((ref) => ref.target ?? ref.raw).join(", ");
3089
- return sig("citation_resolution", "over", `dangling=${citations.dangling.length}/${cited.length}`, "dangling=0", `missing: ${missing}`);
3090
- }
3091
- return sig("citation_resolution", "pass", `citations=${cited.length} foreign=${citations.foreign.length}${citations.unverified.length === 0 ? "" : ` unverified=${citations.unverified.length}`}`);
3092
- }
3093
- /** V4 (design §16.6): the report half of the support-file cap. Only files the
3094
- * assembler could PROVE large enough to be over the cap are namespaced here; an
3095
- * absent map claims nothing (unknown is not zero).
3096
- * @param supportChars - measured character counts, or undefined when unmeasured.
3097
- * @returns a detail suffix naming the oversize files, or an empty string.
3291
+ /** Instance keys held by writer services — the single source shared by the
3292
+ * claim site and the inventory row that declares it (rule N20 checks the row's
3293
+ * `instance` names one of these). */
3294
+ const INSTANCE_KEYS = {
3295
+ /** The per-home curator: report writing + the retention sweep. */
3296
+ curator: "evolution-curator" };
3297
+ let cachedSites;
3298
+ /**
3299
+ * The declared persisted write sites, in file order.
3300
+ *
3301
+ * v43 audit (S2-3 / P1-10): this used to be a module-scope readFileSync plus
3302
+ * parse, so an unshipped asset threw AT IMPORT — one absent file took the whole
3303
+ * family's load down (0.3.79 shipped a tarball without this asset and every
3304
+ * package failed to load). The read is lazy now: importing the package never
3305
+ * fails on this asset, while the first caller still gets a loud, descriptive
3306
+ * failure instead of an empty table ("no declared write sites" would silently
3307
+ * disable rule N20).
3308
+ * @internal S2.4 (PLAN 2026-09-16): no production caller — the arch guard
3309
+ * reads the JSON asset directly; the tests are the only in-tree consumers.
3310
+ * @returns the sites, in file order.
3098
3311
  */
3099
- function oversizeSupportNote(supportChars) {
3100
- if (supportChars === void 0) return "";
3101
- const oversize = Object.entries(supportChars).filter(([, chars]) => chars > MAX_SKILL_CONTENT_CHARS).sort((a, b) => b[1] - a[1]);
3102
- if (oversize.length === 0) return "";
3103
- const shown = oversize.slice(0, 3).map(([path, chars]) => `${path}(${chars})`);
3104
- return `; oversize support file(s): ${shown.join(", ")}${oversize.length > shown.length ? " …" : ""}`;
3105
- }
3106
- /** Render-time reason for an empty retirement list (design §5.6). */
3107
- const RETIREMENT_STATUS_TEXT = {
3108
- listed: "listed",
3109
- none: "none",
3110
- "no-age": "age unknown",
3111
- unscanned: "citations unscanned"
3112
- };
3113
- /** Cold-support-file verdict (design §5.5): zero reads are evidence only while
3114
- * the observation window is open and the file list is known. */
3115
- function demandSignal(snapshot, supportFiles, supportEnumerated) {
3116
- if (!supportEnumerated || supportFiles.length === 0) return sig("demand", "unknown", "not-enumerated", void 0, "support files not enumerated");
3117
- if (snapshot.usageObserved !== true) return sig("demand", "unknown", "window-closed", void 0, "no observed reads yet: zero is not evidence");
3118
- const demand = snapshot.demand ?? {};
3119
- const cold = supportFiles.filter((path) => (demand[path] ?? 0) === 0);
3120
- const retire = retirementReport(snapshot, supportFiles);
3121
- const retireDetail = retire.candidates.length === 0 ? `retire: ${RETIREMENT_STATUS_TEXT[retire.status]}` : `retire≥30d: ${retire.candidates.slice(0, 5).map((c) => `${c.path}(${c.idleDays}d)`).join(", ")}`;
3122
- if (cold.length === 0) return sig("demand", "pass", `${supportFiles.length} warm`, "cold=0", retireDetail);
3123
- const sample = cold.slice(0, 5).join(", ");
3124
- return sig("demand", "over", `cold=${cold.length}/${supportFiles.length}`, "cold=0", `never read: ${sample} · ${retireDetail}`);
3312
+ function persistedWriteSites() {
3313
+ if (cachedSites !== void 0) return cachedSites;
3314
+ let raw;
3315
+ try {
3316
+ raw = readFileSync(fileURLToPath(SITES_URL), "utf8");
3317
+ } catch (error) {
3318
+ const cause = error instanceof Error ? error.message : String(error);
3319
+ throw new Error(`evolution-core: persisted-write-inventory.json is unreadable (${cause}) — the package asset is missing or was not shipped; the write-inventory rules cannot be evaluated without it`);
3320
+ }
3321
+ const table = parseTable(JSON.parse(raw));
3322
+ cachedSites = table.sites;
3323
+ return table.sites;
3125
3324
  }
3126
- /** Convenience: fetch one signal from an assessment or library list. */
3127
- function findDriftSignal(signals, id) {
3128
- return signals.find((signal) => signal.id === id);
3325
+ //#endregion
3326
+ //#region lib/types/scope.js
3327
+ function callingScope(ctx, held) {
3328
+ if (held !== void 0) return held;
3329
+ return scopeOf(ctx);
3129
3330
  }
3130
3331
  //#endregion
3131
3332
  //#region lib/types/store-ledger.js
@@ -3836,9 +4037,9 @@ const PARAM_EXPOSURE = Object.freeze([
3836
4037
  owner: "memory-files",
3837
4038
  applies: "live",
3838
4039
  docAnchor: "PARAMETERS.md#memory",
3839
- summary: "Character budget the memory store enforces for MEMORY.md.",
3840
- label: "记忆库上限",
3841
- hint: "长期记忆文件(MEMORY.md)最多多少字符。",
4040
+ summary: "Legacy character budget for MEMORY.md; only an explicit legacy override, otherwise the token budget governs.",
4041
+ label: "记忆库字符上限(旧)",
4042
+ hint: "旧口径:长期记忆文件最多多少字符。设置后按字符模式工作;未设置时按 token 预算。",
3842
4043
  control: "number",
3843
4044
  unit: "字符",
3844
4045
  values: "",
@@ -3852,14 +4053,46 @@ const PARAM_EXPOSURE = Object.freeze([
3852
4053
  owner: "memory-files",
3853
4054
  applies: "live",
3854
4055
  docAnchor: "PARAMETERS.md#memory",
3855
- summary: "Character budget the memory store enforces for USER.md.",
3856
- label: "用户画像上限",
3857
- hint: "用户画像文件(USER.md)最多多少字符。",
4056
+ summary: "Legacy character budget for USER.md; only an explicit legacy override, otherwise the token budget governs.",
4057
+ label: "用户画像字符上限(旧)",
4058
+ hint: "旧口径:用户画像文件最多多少字符。设置后按字符模式工作;未设置时按 token 预算。",
3858
4059
  control: "number",
3859
4060
  unit: "字符",
3860
4061
  values: "",
3861
4062
  card: "memory-files"
3862
4063
  },
4064
+ {
4065
+ id: "memoryTokens",
4066
+ group: "memory",
4067
+ tier: "E3",
4068
+ authority: "cordis",
4069
+ owner: "memory-files",
4070
+ applies: "live",
4071
+ docAnchor: "PARAMETERS.md#memory",
4072
+ summary: "Estimated token budget for MEMORY.md; the default is derived from the old 2200-character limit.",
4073
+ label: "记忆库 token 上限",
4074
+ hint: "长期记忆按估算 token 计;默认 800,约等于旧英文 2200 字符的上下文成本。",
4075
+ control: "number",
4076
+ unit: "token",
4077
+ values: "",
4078
+ card: "memory-files"
4079
+ },
4080
+ {
4081
+ id: "userTokens",
4082
+ group: "memory",
4083
+ tier: "E3",
4084
+ authority: "cordis",
4085
+ owner: "memory-files",
4086
+ applies: "live",
4087
+ docAnchor: "PARAMETERS.md#memory",
4088
+ summary: "Estimated token budget for USER.md; the default is derived from the old 1375-character limit.",
4089
+ label: "用户画像 token 上限",
4090
+ hint: "用户画像按估算 token 计;默认 500,约等于旧英文 1375 字符的上下文成本。",
4091
+ control: "number",
4092
+ unit: "token",
4093
+ values: "",
4094
+ card: "memory-files"
4095
+ },
3863
4096
  {
3864
4097
  id: "memoryEnabled",
3865
4098
  group: "memory",
@@ -4059,6 +4292,22 @@ const PARAM_EXPOSURE = Object.freeze([
4059
4292
  values: "",
4060
4293
  card: "evolution-curator"
4061
4294
  },
4295
+ {
4296
+ id: "healthSoftBodyTokens",
4297
+ group: "curator",
4298
+ tier: "E3",
4299
+ authority: "cordis",
4300
+ owner: "evolution-curator",
4301
+ applies: "live",
4302
+ docAnchor: "PARAMETERS.md#curator",
4303
+ summary: "Estimated body token line the health view judges against.",
4304
+ label: "正文长度参考(token)",
4305
+ hint: "技能正文超过多少估算 token 算偏长(只用于健康提示);中文约 7.3k 字符、英文约 21.8k 字符触发默认 7,273。",
4306
+ control: "number",
4307
+ unit: "token",
4308
+ values: "",
4309
+ card: "evolution-curator"
4310
+ },
4062
4311
  {
4063
4312
  id: "healthSoftBodyChars",
4064
4313
  group: "curator",
@@ -4067,9 +4316,9 @@ const PARAM_EXPOSURE = Object.freeze([
4067
4316
  owner: "evolution-curator",
4068
4317
  applies: "live",
4069
4318
  docAnchor: "PARAMETERS.md#curator",
4070
- summary: "Body character line the health view judges against.",
4071
- label: "正文长度参考值",
4072
- hint: "技能正文超过多少字符算偏长(只用于健康提示)。",
4319
+ summary: "Legacy body character line; converted once to healthSoftBodyTokens when no token value is set.",
4320
+ label: "正文长度参考(旧字符)",
4321
+ hint: "旧口径:技能正文超过多少字符算偏长。设置后按 2.75 字符/token 换算;未设置时按 token 预算。",
4073
4322
  control: "number",
4074
4323
  unit: "字符",
4075
4324
  values: "",
@@ -5271,4 +5520,4 @@ function classifySessionEvent(event) {
5271
5520
  return MODEL_EVENT_TYPES.has(type) ? "model" : "unknown";
5272
5521
  }
5273
5522
  //#endregion
5274
- export { AUTHORING_DESCRIPTION_BAR, AUTHORING_SPLIT_LINE_CHARS, AuthorityBusyError, AuthorityOrderError, AuthorityReentryError, CITATION_SUPPORT_DIRS, COMBINED_REVIEW_PROMPT, COMPLETION_SKILL_REVIEW_PROMPT, CONTENT_SPLIT_HINT, COST_ASCII_TOKEN_HIGH, COST_ASCII_TOKEN_LOW, COST_CJK_TOKEN_HIGH, COST_CJK_TOKEN_LOW, CURATOR_DRY_RUN_BANNER, CURATOR_PROMPT, DEDUP_MAX_PAIR_COMPARISONS, DEDUP_SIMILARITY_THRESHOLD, DEFAULT_ARCHIVE_AFTER_DAYS, DEFAULT_ARCHIVE_RETENTION_POLICY, DEFAULT_CITATION_POLICY, DEFAULT_CITATION_REF_BUDGET, DEFAULT_CONSOLIDATION_FAILURES, DEFAULT_CURATOR_BOOT_GRACE_SECONDS, DEFAULT_CURATOR_INTERVAL_HOURS, DEFAULT_CURATOR_MODEL, DEFAULT_CURATOR_REVIEW_MAX_TOKENS, DEFAULT_LEASE_TTL_MS, DEFAULT_MEMORY_CHAR_LIMIT, DEFAULT_MIN_IDLE_HOURS, DEFAULT_MUTATION_CAP, DEFAULT_PROBE_TIMEOUT_MS, DEFAULT_REFERENCE_REWRITE_POLICY, DEFAULT_REVIEW_MEMORY_INTERVAL, DEFAULT_REVIEW_SKILL_INTERVAL, DEFAULT_REVIEW_TIMEOUT_MS, DEFAULT_RUN_RECORDS, DEFAULT_SKILL_CONTENT_CHARS, DEFAULT_SKILL_LIMITS, DEFAULT_SKILL_REVIEW_COMPLETION_MIN_TOOL_CALLS, DEFAULT_SKILL_REVIEW_TRIGGER, DEFAULT_SKILL_VERSION_KEEP, DEFAULT_STALE_AFTER_DAYS, DEFAULT_SUBSTANTIVE_MIN_AGENT_CHARS, DEFAULT_SUBSTANTIVE_MIN_TOOL_CALLS, DEFAULT_SUBSTANTIVE_MIN_USER_CHARS, DEFAULT_SUPPORT_FILE_CHAR_POLICY, DEFAULT_SUPPORT_READ_TOOL_NAMES, DEFAULT_THREAT_MAX_SCAN_CHARS, DEFAULT_USER_CHAR_LIMIT, DEFAULT_WRITE_CONFIRM_MODE, DEFAULT_WRITE_CONFIRM_TIMEOUT_SECONDS, DIAGNOSTICS_FACT_KEYS, DIAGNOSTICS_RUNTIME_KEYS, DIAGNOSTICS_VIEW_SCHEMA_VERSION, DISPATCH_EVENT_TYPES, DRIFT_MAX_LINE_CHARS, DRIFT_SIGNALS_VERSION, DRIFT_SIGNAL_NOUNS, DSH_AUTHORING_STANDARDS, ENTRY_DELIMITER, EVENT_ARCHIVE_PREFIX, EVENT_LOG_RETAIN_ARCHIVES, EVENT_LOG_ROTATE_AT, EVENT_LOG_VERSION, EVOLUTION_ERRORS, EVOLUTION_PRESET_IDS, EVOLUTION_WRITE_TOOLS, EvolutionGateSet, FAMILY_SESSION_TOOL_NAMES, FORBIDDEN_CONTROL_KEYS, FUZZY_MAX_PATTERN_CHARS, FUZZY_MAX_WORK, GOVERNANCE_PROMPT_TEMPLATE, HOOK_LINE_RE, HOST_LOCALES, HOST_ROUTES, HomeAuthority, HomeFence, HomeFenceError, INJECT_COMBINED_REVIEW_PROMPT, INJECT_COMPLETION_SKILL_REVIEW_PROMPT, INJECT_MEMORY_REVIEW_PROMPT, INJECT_SKILL_REVIEW_PROMPT, INSTANCE_KEYS, KEEP_LINE_RE, LONG_RUNS, LOW_QUALITY_THRESHOLD, LeaseStore, MAINTAINER_PRESET_ID, MAINTAIN_OUTPUT_INSTRUCTION, MAINTAIN_PROMPT, MAX_DESCRIPTION_LENGTH, MAX_REQUEST_BODY_BYTES, MAX_SKILL_CONTENT_CHARS, MAX_SKILL_FILE_BYTES, MAX_SKILL_NAME_LENGTH, MAX_SUPPORT_READ_PATHS, MAX_TIMER_DELAY_MS, MEMORY_GUIDANCE_SECTION_ORDER, MEMORY_REVIEW_PROMPT, MODEL_SESSION_EVENT_TYPES, MUTATIONS_FILE_VERSION, MemoryStore, MutationAuthority, NAMESPACE_MIGRATIONS, NATIVE_CALL_EVENT, NATIVE_RESULT_EVENT, PARAM_ALIASES, PARAM_EXPOSURE, PARAM_GROUP_LABELS, PARAM_NAMESPACES, PATTERN_OVERLAP, PLATFORM_LINE, PLATFORM_SERVICE_PROBES, POLICY_STAGE_DEFAULTS, PROMPT_BUNDLE, PROMPT_BUNDLE_ID, PROMPT_BUNDLE_VERSION, PROTECTED_BUILTIN_SKILLS, PTC_DISPATCH_EVENT, PTC_DISPATCH_START_EVENT, QUALITY_WEIGHTS, RESTRICTED_PRESET_DISPLAY, RESTRICTED_TOOLS_ROW_ID, RESTRICTOR_MODULE, REVIEWER_PRESET_ID, RUNS_SCHEMA_VERSION, SKILLS_GUIDANCE, SKILLS_GUIDANCE_SECTION_ORDER, SKILL_ACTION_REQUIRED_FIELDS, SKILL_NAME_RE, SKILL_REVIEW_PROMPT, STORE_LEDGER, SUMMARY_DUPLICATE_HINT_THRESHOLD, SUPPORT_DIRS, SUPPORT_SPRAWL_FILES, SUPPRESSED_FILE_VERSION, THREAT_EXEMPTION_HINT, TOKEN_ASCII_WEIGHT, TOKEN_CJK_WEIGHT, ToolDispatchNormalizer, ToolDispatchPayloadError, TransactionNotInvokedError, UPSTREAM_LIMIT_CHARS_PER_TOKEN, VIEW_WINDOW_DAYS, abortLink, absentHostServices, advanceReview, affinity, allowRowCollisions, appendEvolutionEvent, applyCuratorLifecycleFields, applyCuratorMetaFields, applyNamespaceMigration, applyReferenceRewrite, asRecord, assertDispatchPayload, atomicWriteFiles, authorityFrom, authorityHolder, backupsReachability, bodyCost, buildCuratorRunReport, buildHealthBaseline, buildLearnPrompt, bumpPatch, bumpSupportRead, bumpUse, bumpView, callingScope, claimInstance, clampOnce, clampedNumber, classifyNamespaceMigration, classifySessionEvent, clearReviewChannel, collectReadSkillNames, collectReadSupportFiles, computeDedupGroups, computeDriftSignals, computeLifecycleTransitions, computePrefixClusters, computeQualityScores, computeScopeView, contentHash, createGateSet, createSubagentKernel as createSubagentChannel, createSubagentKernel, createSubagentRun, currentReviewContext, daysSinceIso, declaredReportStamp, describeReferenceRewrite, dispatchKeyOf, dispatchPathOf, dispatchStepOf, displayBodyOf, duplicateHeadings, emptyRecord, errorText, errorTextIn, evaluateThreat, eventsFile, evidenceKindIndex, evolutionActivityProjection, evolutionEventPayloadIssue, evolutionEvidenceProjection, evolutionHome, evolutionIoAdapter, evolutionProjectionHistoryProjection, evolutionReadsProjection, evolutionRoot, evolutionSignalsProjection, externalRefs, findDriftSignal, findOwnerCandidate, foldCuratorFields, foldToolDispatches, foldTurnEvent, foldTurnEvents, fuzzyPatch, getRecord, h2Sections, historyReachability, hostSurface, identity, idleDays, initialTurnFold, instanceClaimKey, instanceHolder, isAbsent, isBookkeepingFrame, isCommittedWarning, isDeprecatedParamId, isFileShapedPath, isMissingPath, isPresent, isProcessAlive, isProjectableSession, isRecord, isReviewChannelSession, isSkillReadToolName, isSkillToolName, isUnknown, json, latestActivityAt, leaseAsTreeLock, leaseFile, lifecycleCandidate, listEventArchives, liveBool, liveNumber, loadMutations, loadSuppressedNames, loadUsage, makeSerialQueue, markAgentCreated, markReviewChannel, memoryRoot, methodNotAllowed, missingSupportPointers, mutateUsage, mutationLockFrom, mutationsFile, narrowNameMatches, nearDuplicateSummaries, newRunRegistry, nodeEvolutionIo, normalizeUsageRecord, observeEvent, overlongLines, ownerCandidatesFromSummaries, paramRowId, paramSettingsId, parseCuratorNominations, parseEvolutionEvents, payloadText, persistedWriteSites, pickWithPolicy, planNamespaceMigration, planReferenceRewrite, planRehoming, policyStageLimits, probeAbsent, probeChannelState, probeList, probeMtime, probePresent, probeReason, probeText, probeUnknown, projectionText, proposalFromPlan, proposalReportDir, proposalReportName, protectedSkillNamesOf, readDispatchSignal, readEvolutionEvents, readEvolutionTimeline, readExternalSupport, readJsonObject, readNumberParam, readParam, readProposalReport, readProposalReports, readingStats, recentViewCount, recordMutation, recordReviewRead, redactSecrets, referencedBlobs, registerHostRoutes, releaseInstance, renameWithRetry, renderCuratorReportMarkdown, reportTime, reportsReachability, reportsSweepLockTarget, resolveCitations, resolveParamId, retainEventArchives, retirementReport, reviewPrompt, runWriteGates, runsFile, saveSuppressedNames, saveUsage, scanBodyHooks, scanContentThreats, scanMemoryThreats, scanThreats, scopeOfNearestManifest, scopedPackageName, scopedProbeReport, selectSections, sessionAudited, sessionEvidenceIndex, sessionLastEventTime, sessionReadNames, sessionSeesFamilyTools, sessionTurnSignals, skillReadNameOf, skillWriteGateContext, supportFileReadFromPath, supportFileReadOf, supportRefs, suppressedFile, sweepReports, sweepReviewChannelSessions, textOfValue, tokenLineFor, transactIo, trimPatternBoundaries, unhookedSupportPointers, unwrapLive, updateSuppressedNames, usageFile, usageObserved, userSetKeys, verifyPromptBundle, vocabulary, waitForSubagentEnd, withReviewContext, withTreeWrite, writeDurableTmp, writeProposalReport };
5523
+ export { AUTHORING_DESCRIPTION_BAR, AUTHORING_SPLIT_LINE_CHARS, AuthorityBusyError, AuthorityOrderError, AuthorityReentryError, CITATION_SUPPORT_DIRS, COMBINED_REVIEW_PROMPT, COMPLETION_SKILL_REVIEW_PROMPT, CONTENT_SPLIT_HINT, CURATOR_DRY_RUN_BANNER, CURATOR_PROMPT, DEDUP_MAX_PAIR_COMPARISONS, DEDUP_SIMILARITY_THRESHOLD, DEFAULT_ARCHIVE_AFTER_DAYS, DEFAULT_ARCHIVE_RETENTION_POLICY, DEFAULT_CITATION_POLICY, DEFAULT_CITATION_REF_BUDGET, DEFAULT_CONSOLIDATION_FAILURES, DEFAULT_CURATOR_BOOT_GRACE_SECONDS, DEFAULT_CURATOR_INTERVAL_HOURS, DEFAULT_CURATOR_MODEL, DEFAULT_CURATOR_REVIEW_MAX_TOKENS, DEFAULT_LEASE_TTL_MS, DEFAULT_MEMORY_CHAR_LIMIT, DEFAULT_MEMORY_TOKENS, DEFAULT_MIN_IDLE_HOURS, DEFAULT_MUTATION_CAP, DEFAULT_PROBE_TIMEOUT_MS, DEFAULT_REFERENCE_REWRITE_POLICY, DEFAULT_REVIEW_MEMORY_INTERVAL, DEFAULT_REVIEW_SKILL_INTERVAL, DEFAULT_REVIEW_TIMEOUT_MS, DEFAULT_RUN_RECORDS, DEFAULT_SKILL_CONTENT_CHARS, DEFAULT_SKILL_LIMITS, DEFAULT_SKILL_REVIEW_COMPLETION_MIN_TOOL_CALLS, DEFAULT_SKILL_REVIEW_TRIGGER, DEFAULT_SKILL_VERSION_KEEP, DEFAULT_SOFT_BODY_TOKENS, DEFAULT_STALE_AFTER_DAYS, DEFAULT_SUBSTANTIVE_MIN_AGENT_CHARS, DEFAULT_SUBSTANTIVE_MIN_TOOL_CALLS, DEFAULT_SUBSTANTIVE_MIN_USER_CHARS, DEFAULT_SUPPORT_FILE_CHAR_POLICY, DEFAULT_SUPPORT_READ_TOOL_NAMES, DEFAULT_THREAT_MAX_SCAN_CHARS, DEFAULT_USER_CHAR_LIMIT, DEFAULT_USER_TOKENS, DEFAULT_WRITE_CONFIRM_MODE, DEFAULT_WRITE_CONFIRM_TIMEOUT_SECONDS, DIAGNOSTICS_FACT_KEYS, DIAGNOSTICS_RUNTIME_KEYS, DIAGNOSTICS_VIEW_SCHEMA_VERSION, DISPATCH_EVENT_TYPES, DRIFT_MAX_LINE_CHARS, DRIFT_SIGNALS_VERSION, DRIFT_SIGNAL_NOUNS, DSH_AUTHORING_STANDARDS, ENTRY_DELIMITER, EVENT_ARCHIVE_PREFIX, EVENT_LOG_RETAIN_ARCHIVES, EVENT_LOG_ROTATE_AT, EVENT_LOG_VERSION, EVOLUTION_ERRORS, EVOLUTION_PRESET_IDS, EVOLUTION_WRITE_TOOLS, EvolutionGateSet, FAMILY_SESSION_TOOL_NAMES, FORBIDDEN_CONTROL_KEYS, FUZZY_MAX_PATTERN_CHARS, FUZZY_MAX_WORK, GOVERNANCE_PROMPT_TEMPLATE, HOOK_LINE_RE, HOST_LOCALES, HOST_ROUTES, HomeAuthority, HomeFence, HomeFenceError, INJECT_COMBINED_REVIEW_PROMPT, INJECT_COMPLETION_SKILL_REVIEW_PROMPT, INJECT_MEMORY_REVIEW_PROMPT, INJECT_SKILL_REVIEW_PROMPT, INSTANCE_KEYS, KEEP_LINE_RE, LONG_RUNS, LOW_QUALITY_THRESHOLD, LeaseStore, MAINTAINER_PRESET_ID, MAINTAIN_OUTPUT_INSTRUCTION, MAINTAIN_PROMPT, MAX_DESCRIPTION_LENGTH, MAX_REQUEST_BODY_BYTES, MAX_SKILL_CONTENT_CHARS, MAX_SKILL_FILE_BYTES, MAX_SKILL_NAME_LENGTH, MAX_SUPPORT_READ_PATHS, MAX_TIMER_DELAY_MS, MEMORY_GUIDANCE_SECTION_ORDER, MEMORY_REVIEW_PROMPT, MEMORY_TOKENS, MODEL_SESSION_EVENT_TYPES, MUTATIONS_FILE_VERSION, MemoryStore, MutationAuthority, NAMESPACE_MIGRATIONS, NATIVE_CALL_EVENT, NATIVE_RESULT_EVENT, PARAM_ALIASES, PARAM_EXPOSURE, PARAM_GROUP_LABELS, PARAM_NAMESPACES, PATTERN_OVERLAP, PLATFORM_LINE, PLATFORM_SERVICE_PROBES, POLICY_STAGE_DEFAULTS, PROMPT_BUNDLE, PROMPT_BUNDLE_ID, PROMPT_BUNDLE_VERSION, PROTECTED_BUILTIN_SKILLS, PTC_DISPATCH_EVENT, PTC_DISPATCH_START_EVENT, QUALITY_WEIGHTS, RESTRICTED_PRESET_DISPLAY, RESTRICTED_TOOLS_ROW_ID, RESTRICTOR_MODULE, REVIEWER_PRESET_ID, RUNS_SCHEMA_VERSION, SKILLS_GUIDANCE, SKILLS_GUIDANCE_SECTION_ORDER, SKILL_ACTION_REQUIRED_FIELDS, SKILL_NAME_RE, SKILL_REVIEW_PROMPT, SOFT_BODY_TOKENS, STORE_LEDGER, SUMMARY_DUPLICATE_HINT_THRESHOLD, SUPPORT_DIRS, SUPPORT_SPRAWL_FILES, SUPPRESSED_FILE_VERSION, TEXT_BUDGETS, THREAT_EXEMPTION_HINT, ToolDispatchNormalizer, ToolDispatchPayloadError, TransactionNotInvokedError, UPSTREAM_LIMIT_CHARS_PER_TOKEN, USER_TOKENS, VIEW_WINDOW_DAYS, abortLink, absentHostServices, advanceReview, affinity, allowRowCollisions, appendEvolutionEvent, applyCuratorLifecycleFields, applyCuratorMetaFields, applyNamespaceMigration, applyReferenceRewrite, asRecord, assertDispatchPayload, atomicWriteFiles, authorityFrom, authorityHolder, backupsReachability, buildCuratorRunReport, buildHealthBaseline, buildLearnPrompt, bumpPatch, bumpSupportRead, bumpUse, bumpView, callingScope, claimInstance, clampOnce, clampedNumber, classifyNamespaceMigration, classifySessionEvent, clearReviewChannel, codePointCount, collectReadSkillNames, collectReadSupportFiles, compareTextBudget, computeDedupGroups, computeDriftSignals, computeLifecycleTransitions, computePrefixClusters, computeQualityScores, computeScopeView, conservativeTokenEstimator, contentHash, createGateSet, createSubagentKernel as createSubagentChannel, createSubagentKernel, createSubagentRun, currentReviewContext, daysSinceIso, declaredReportStamp, describeReferenceRewrite, dispatchKeyOf, dispatchPathOf, dispatchStepOf, displayBodyOf, duplicateHeadings, emptyRecord, errorText, errorTextIn, evaluateThreat, eventsFile, evidenceKindIndex, evolutionActivityProjection, evolutionEventPayloadIssue, evolutionEvidenceProjection, evolutionHome, evolutionIoAdapter, evolutionProjectionHistoryProjection, evolutionReadsProjection, evolutionRoot, evolutionSignalsProjection, externalRefs, findDriftSignal, findOwnerCandidate, foldCuratorFields, foldToolDispatches, foldTurnEvent, foldTurnEvents, fuzzyPatch, getRecord, graphemeCount, h2Sections, historyReachability, hostSurface, identity, idleDays, initialTurnFold, instanceClaimKey, instanceHolder, isAbsent, isBookkeepingFrame, isCommittedWarning, isDeprecatedParamId, isFileShapedPath, isMissingPath, isPresent, isProcessAlive, isProjectableSession, isRecord, isReviewChannelSession, isSkillReadToolName, isSkillToolName, isUnknown, json, latestActivityAt, leaseAsTreeLock, leaseFile, lifecycleCandidate, listEventArchives, liveBool, liveNumber, loadMutations, loadSuppressedNames, loadUsage, makeSerialQueue, markAgentCreated, markReviewChannel, measureText, measureUnit, memoryRoot, methodNotAllowed, missingSupportPointers, mutateUsage, mutationLockFrom, mutationsFile, narrowNameMatches, nearDuplicateSummaries, newRunRegistry, nodeEvolutionIo, normalizeUsageRecord, observeEvent, overlongLines, ownerCandidatesFromSummaries, paramRowId, paramSettingsId, parseCuratorNominations, parseEvolutionEvents, payloadText, persistedWriteSites, pickWithPolicy, planNamespaceMigration, planReferenceRewrite, planRehoming, policyStageLimits, probeAbsent, probeChannelState, probeList, probeMtime, probePresent, probeReason, probeText, probeUnknown, projectionText, proposalFromPlan, proposalReportDir, proposalReportName, protectedSkillNamesOf, readDispatchSignal, readEvolutionEvents, readEvolutionTimeline, readExternalSupport, readJsonObject, readNumberParam, readParam, readProposalReport, readProposalReports, readingStats, recentViewCount, recordMutation, recordReviewRead, redactSecrets, referencedBlobs, registerHostRoutes, releaseInstance, renameWithRetry, renderCuratorReportMarkdown, reportTime, reportsReachability, reportsSweepLockTarget, resolveCitations, resolveParamId, retainEventArchives, retirementReport, reviewPrompt, runWriteGates, runsFile, saveSuppressedNames, saveUsage, scanBodyHooks, scanContentThreats, scanMemoryThreats, scanThreats, scopeOfNearestManifest, scopedPackageName, scopedProbeReport, selectSections, sessionAudited, sessionEvidenceIndex, sessionLastEventTime, sessionReadNames, sessionSeesFamilyTools, sessionTurnSignals, skillReadNameOf, skillWriteGateContext, supportFileReadFromPath, supportFileReadOf, supportRefs, suppressedFile, sweepReports, sweepReviewChannelSessions, textOfValue, transactIo, trimPatternBoundaries, truncateGraphemes, unhookedSupportPointers, unwrapLive, updateSuppressedNames, usageFile, usageObserved, userSetKeys, utf8ByteLength, verifyPromptBundle, vocabulary, waitForSubagentEnd, withReviewContext, withTreeWrite, writeDurableTmp, writeProposalReport };