@lmzhen/dsh-evolution-core 0.48.0 → 0.50.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 (97) hide show
  1. package/lib/authority-plugin.js +2 -1
  2. package/lib/citations-CZKTUGQF.js +198 -0
  3. package/lib/composition/index.js +2 -2
  4. package/lib/{composition-Cqjbho0t.js → composition-DA8XPfMc.js} +1 -1
  5. package/lib/connection-DAJy7Xjm.js +28 -0
  6. package/lib/{ensure-CAjLGd9f.js → ensure-Bx4ksgJk.js} +15 -5
  7. package/lib/errors.js +2 -0
  8. package/lib/extract-plan-Bru3c9ec.js +271 -0
  9. package/lib/extract.js +240 -0
  10. package/lib/http-routes.js +27 -7
  11. package/lib/index.js +41 -822
  12. package/lib/{numeric-D8js3sqC.js → limits-C9jfvxBl.js} +1 -43
  13. package/lib/{mutation-authority-l57R626O.js → mutation-authority-DQfpXs1O.js} +2 -54
  14. package/lib/numeric-Dc53KQoe.js +43 -0
  15. package/lib/platform/index.js +4 -3
  16. package/lib/platform-DyHnHUmQ.js +251 -0
  17. package/lib/policy.js +3 -2
  18. package/lib/quality-WAU6YatF.js +554 -0
  19. package/lib/restrictor.js +1 -1
  20. package/lib/result.js +33 -0
  21. package/lib/runtime/plugin.js +97 -43
  22. package/lib/{session-projection-DSXnUNZG.js → session-projection-ByNxQi9O.js} +2 -198
  23. package/lib/skill-health-Bl-MdXZ4.js +1409 -0
  24. package/lib/skills.js +7 -4
  25. package/lib/state-store-Jpa-iYIZ.js +54 -0
  26. package/lib/subagent/index.js +214 -176
  27. package/lib/{tools-DzcNFex2.js → tools-BrUswg8v.js} +3 -1
  28. package/lib/types/composition/ensure.js +21 -7
  29. package/lib/types/extract-plan.d.ts +2 -0
  30. package/lib/types/extract.d.ts +12 -0
  31. package/lib/types/extract.js +12 -0
  32. package/lib/types/http-routes.js +32 -9
  33. package/lib/types/index.d.ts +0 -3
  34. package/lib/types/index.js +0 -3
  35. package/lib/types/long-runs.d.ts +0 -5
  36. package/lib/types/long-runs.js +0 -7
  37. package/lib/types/opt-in.js +4 -3
  38. package/lib/types/params.js +2 -1
  39. package/lib/types/platform/agents.d.ts +32 -0
  40. package/lib/types/platform/agents.js +26 -0
  41. package/lib/types/platform/commands.d.ts +14 -0
  42. package/lib/types/platform/commands.js +9 -0
  43. package/lib/types/platform/connection.d.ts +26 -0
  44. package/lib/types/platform/connection.js +27 -0
  45. package/lib/types/platform/index.d.ts +26 -0
  46. package/lib/types/platform/index.js +13 -0
  47. package/lib/types/platform/llm.d.ts +3 -1
  48. package/lib/types/platform/llm.js +1 -0
  49. package/lib/types/platform/platformView.d.ts +21 -0
  50. package/lib/types/platform/platformView.js +29 -0
  51. package/lib/types/platform/profileContext.d.ts +16 -0
  52. package/lib/types/platform/profileContext.js +14 -0
  53. package/lib/types/platform/sessionQuery.d.ts +14 -0
  54. package/lib/types/platform/sessionQuery.js +9 -0
  55. package/lib/types/platform/settings.d.ts +22 -0
  56. package/lib/types/platform/settings.js +14 -0
  57. package/lib/types/platform/skills.d.ts +16 -0
  58. package/lib/types/platform/skills.js +9 -0
  59. package/lib/types/platform/storageDomain.d.ts +13 -0
  60. package/lib/types/platform/storageDomain.js +9 -0
  61. package/lib/types/platform/subagents.d.ts +25 -0
  62. package/lib/types/platform/subagents.js +17 -0
  63. package/lib/types/platform/systemPrompt.d.ts +16 -0
  64. package/lib/types/platform/systemPrompt.js +13 -0
  65. package/lib/types/platform/tools.d.ts +4 -0
  66. package/lib/types/platform/tools.js +2 -0
  67. package/lib/types/platform/userQuestions.d.ts +33 -0
  68. package/lib/types/platform/userQuestions.js +9 -0
  69. package/lib/types/platform/workingDirectory.d.ts +14 -0
  70. package/lib/types/platform/workingDirectory.js +9 -0
  71. package/lib/types/platform-line.generated.d.ts +5 -5
  72. package/lib/types/platform-line.generated.js +5 -5
  73. package/lib/types/platform-services.js +3 -0
  74. package/lib/types/result.d.ts +35 -0
  75. package/lib/types/result.js +25 -0
  76. package/lib/types/runtime/llm.d.ts +2 -2
  77. package/lib/types/runtime/llm.js +5 -8
  78. package/lib/types/runtime/platform.d.ts +37 -4
  79. package/lib/types/runtime/platform.js +40 -5
  80. package/lib/types/runtime/projections.d.ts +9 -4
  81. package/lib/types/runtime/projections.js +64 -28
  82. package/lib/types/subagent/channel.d.ts +1 -3
  83. package/lib/types/subagent/channel.js +2 -332
  84. package/lib/types/subagent/index.d.ts +2 -0
  85. package/lib/types/subagent/index.js +2 -0
  86. package/lib/types/subagent/kernel.d.ts +4 -0
  87. package/lib/types/subagent/kernel.js +234 -0
  88. package/lib/types/subagent/readiness.js +5 -7
  89. package/lib/types/subagent/run.d.ts +53 -0
  90. package/lib/types/subagent/run.js +125 -0
  91. package/lib/types/subagent/types.d.ts +2 -2
  92. package/lib/types/write-inventory.d.ts +0 -11
  93. package/lib/types/write-inventory.js +0 -16
  94. package/lib/usage-DdjIBAkm.js +1252 -0
  95. package/package.json +37 -25
  96. package/lib/platform-Cc9cNt5j.js +0 -111
  97. package/lib/skill-health-DP8z9TPf.js +0 -2923
@@ -0,0 +1,554 @@
1
+ import { b as probeText, g as probeList, m as isUnknown, p as isPresent } from "./io-GxghO3Ip.js";
2
+ import { H as externalRefs, O as h2Sections, m as latestActivityAt } from "./usage-DdjIBAkm.js";
3
+ import { t as evolutionHome } from "./state-store-Jpa-iYIZ.js";
4
+ import { readFile, realpath, stat } from "node:fs/promises";
5
+ import { basename, isAbsolute, join, relative, resolve } from "node:path";
6
+ import { createHash } from "node:crypto";
7
+ //#region lib/types/owner-resolver.js
8
+ /**
9
+ * Project the current library listing into owner candidates.
10
+ *
11
+ * The source is excluded; a skill with an empty description is named in
12
+ * excluded rather than silently dropped. Protected candidates remain visible
13
+ * (so a caller can explain why it refused), but are marked for the writer's
14
+ * protection gate. Headings reuse h2Sections; no second heading scanner.
15
+ * @param source - skill being extracted from.
16
+ * @param summaries - SkillLibrary.list({ withContent: true, withFrontmatter: true }).
17
+ * @returns stable-name-ordered candidates plus explicit exclusions.
18
+ */
19
+ function ownerCandidatesFromSummaries(source, summaries) {
20
+ const normalized = source.trim();
21
+ const candidates = [];
22
+ const excluded = [];
23
+ for (const summary of summaries) {
24
+ if (summary.name === normalized) {
25
+ excluded.push({
26
+ name: summary.name,
27
+ reason: "source"
28
+ });
29
+ continue;
30
+ }
31
+ if (summary.description.trim() === "") {
32
+ excluded.push({
33
+ name: summary.name,
34
+ reason: "unreadable"
35
+ });
36
+ continue;
37
+ }
38
+ candidates.push({
39
+ name: summary.name,
40
+ description: summary.description,
41
+ ...summary.whenToUse === void 0 ? {} : { whenToUse: summary.whenToUse },
42
+ headings: h2Sections(summary.content ?? "").map((section) => section.title),
43
+ protectedBy: summary.protectedBy,
44
+ protectionUnknown: summary.protectionUnknown,
45
+ managed: summary.managed
46
+ });
47
+ }
48
+ candidates.sort((left, right) => left.name.localeCompare(right.name));
49
+ excluded.sort((left, right) => left.name.localeCompare(right.name));
50
+ return {
51
+ source: normalized,
52
+ candidates,
53
+ excluded
54
+ };
55
+ }
56
+ /**
57
+ * Find one named candidate in a lookup.
58
+ * @param lookup - projection from ownerCandidatesFromSummaries.
59
+ * @param name - exact skill name.
60
+ * @returns the candidate, or undefined when absent.
61
+ */
62
+ function findOwnerCandidate(lookup, name) {
63
+ return lookup.candidates.find((candidate) => candidate.name === name);
64
+ }
65
+ //#endregion
66
+ //#region lib/types/extract-prompt.js
67
+ /**
68
+ * The frozen semantic prompt for skill extraction. One constant, consumed by
69
+ * explicit extract agents and tests; it is deliberately not part of the review
70
+ * prompt bundle, and no review path injects it.
71
+ */
72
+ const EXTRACT_PROMPT_VERSION = "v1";
73
+ const EXTRACT_PROMPT_V1 = `Inspect the source skill, its linked support files, and the candidate owners
74
+ in the library. A part of the skill (one or more sections) is a separate
75
+ capability when it has its own trigger and outcome, can be used without the
76
+ parent context, and leaves the parent coherent. If it is separate and a
77
+ class-level owner covers it, extract that part. If no owner covers it, report
78
+ the owner gap and name the class-level owner that would be needed. If it mixes
79
+ a reusable capability with parent-specific facts, return mixed and name only
80
+ the reusable part. Otherwise keep it. Keep, extract, mixed, and owner-gap are
81
+ all valid outcomes; no split is required.`;
82
+ const EXTRACT_PROMPT_HASH = createHash("sha256").update(EXTRACT_PROMPT_V1, "utf8").digest("hex");
83
+ //#endregion
84
+ //#region lib/types/proposal-view.js
85
+ /**
86
+ * Project a pure ExtractPlan into the proposal record every read-only surface consumes.
87
+ *
88
+ * This is a projection, not a second evaluator: it keeps the plan's owner decision,
89
+ * support closure and warnings. It never writes and never invents coverage.
90
+ * @param plan - plan produced by planExtract.
91
+ * @param provenance - run id and timestamp for the proposing pass.
92
+ * @returns a proposal with status proposed.
93
+ */
94
+ function proposalFromPlan(plan, provenance) {
95
+ return {
96
+ version: 1,
97
+ id: "extract-" + provenance.runId + "-" + plan.source,
98
+ source: plan.source,
99
+ outcome: plan.outcome,
100
+ parts: plan.parts.map((part) => ({
101
+ heading: part.heading,
102
+ anchor: part.anchor,
103
+ reason: part.sourceText.slice(0, 160)
104
+ })),
105
+ owner: plan.owner,
106
+ support: plan.support,
107
+ residual: plan.residual,
108
+ warnings: plan.warnings,
109
+ provenance: {
110
+ promptVersion: "v1",
111
+ promptHash: EXTRACT_PROMPT_HASH,
112
+ runId: provenance.runId,
113
+ at: provenance.at ?? Date.now()
114
+ },
115
+ status: "proposed"
116
+ };
117
+ }
118
+ //#endregion
119
+ //#region lib/types/proposal-report.js
120
+ /** Directory for the one proposal lane; reports are retention-swept with the other run reports. */
121
+ function proposalReportDir() {
122
+ return join(evolutionHome(), "reports");
123
+ }
124
+ /** Stable report filename for one proposal; the id may carry path separators. */
125
+ function proposalReportName(proposal) {
126
+ return "extract-proposal-" + encodeURIComponent(proposal.id) + ".json";
127
+ }
128
+ /**
129
+ * Persist one proposal as a report. Best-effort: a failed write never blocks the extract.
130
+ * @param io - evolution IO seam.
131
+ * @param proposal - proposal to persist.
132
+ * @param dir - reports directory (tests pass a temp dir).
133
+ * @returns the written path.
134
+ */
135
+ async function writeProposalReport(io, proposal, dir = proposalReportDir()) {
136
+ const path = join(dir, proposalReportName(proposal));
137
+ await io.writeText(path, JSON.stringify(proposal));
138
+ return path;
139
+ }
140
+ function isProposal(value) {
141
+ if (value === null || typeof value !== "object") return false;
142
+ const candidate = value;
143
+ return candidate.version === 1 && typeof candidate.id === "string" && typeof candidate.source === "string" && (candidate.outcome === "keep" || candidate.outcome === "extract" || candidate.outcome === "mixed" || candidate.outcome === "owner-gap");
144
+ }
145
+ /**
146
+ * Read the newest proposals. Missing/unreadable reports are skipped, never guessed.
147
+ * @param io - evolution IO seam.
148
+ * @param dir - reports directory.
149
+ * @param limit - newest rows to return.
150
+ * @returns valid proposals, newest filename first.
151
+ */
152
+ async function readProposalReport(io, id, dir = proposalReportDir()) {
153
+ const raw = await probeText(io, join(dir, proposalReportName({ id })));
154
+ if (!isPresent(raw)) return null;
155
+ try {
156
+ const parsed = JSON.parse(raw.value);
157
+ return isProposal(parsed) ? parsed : null;
158
+ } catch {
159
+ return null;
160
+ }
161
+ }
162
+ async function readProposalReports(io, dir = proposalReportDir(), limit = 10) {
163
+ const listed = await probeList(io, dir);
164
+ if (isUnknown(listed) || !isPresent(listed)) return [];
165
+ const names = listed.value.filter((name) => name.startsWith("extract-proposal-") && name.endsWith(".json"));
166
+ names.sort((a, b) => b.localeCompare(a));
167
+ const proposals = [];
168
+ for (const name of names.slice(0, limit)) {
169
+ const raw = await probeText(io, join(dir, name));
170
+ if (!isPresent(raw)) continue;
171
+ let parsed;
172
+ try {
173
+ parsed = JSON.parse(raw.value);
174
+ } catch {
175
+ continue;
176
+ }
177
+ if (isProposal(parsed)) proposals.push(parsed);
178
+ }
179
+ return proposals;
180
+ }
181
+ //#endregion
182
+ //#region lib/types/external-support.js
183
+ const MAX_FILE_BYTES = 1024 * 1024;
184
+ const MAX_TOTAL_BYTES = 4 * 1024 * 1024;
185
+ function targetPathFor(ref) {
186
+ let value = ref.replace(/^\/+/, "");
187
+ while (value.startsWith("../")) value = value.slice(3);
188
+ const support = value.match(/(?:^|\/)(references|templates|scripts|assets)\/(.+)$/);
189
+ if (support !== null) return support[1] + "/" + support[2];
190
+ return "references/" + basename(value);
191
+ }
192
+ function annotate(content, originalPath) {
193
+ const note = "external source: " + originalPath;
194
+ const extension = originalPath.slice(originalPath.lastIndexOf(".")).toLowerCase();
195
+ if (extension === ".md") return "<!-- " + note + " -->\n\n" + content;
196
+ const prefix = extension === ".py" || extension === ".sh" || extension === ".rb" ? "# " : "// ";
197
+ if (extension === ".js" || extension === ".mjs" || extension === ".cjs" || extension === ".ts" || extension === ".tsx" || extension === ".py" || extension === ".sh" || extension === ".rb") {
198
+ if (content.startsWith("#!")) {
199
+ const end = content.indexOf(String.fromCharCode(10));
200
+ if (end >= 0) return content.slice(0, end + 1) + prefix + note + String.fromCharCode(10) + content.slice(end + 1);
201
+ }
202
+ return prefix + note + String.fromCharCode(10) + content;
203
+ }
204
+ return content;
205
+ }
206
+ function inside(root, candidate) {
207
+ const rel = relative(root, candidate);
208
+ return rel === "" || !rel.startsWith("..") && !isAbsolute(rel);
209
+ }
210
+ /**
211
+ * Read and annotate external support files under one explicit root. The caller owns
212
+ * the root choice; this module only enforces containment, target-path safety, size
213
+ * limits and determinism.
214
+ * @param body - selected source markdown body.
215
+ * @param sourceDir - source skill directory.
216
+ * @param allowedRoot - canonical root external files must stay under.
217
+ * @param targetFiles - existing target support paths.
218
+ * @returns resolved external entries, or a refusal.
219
+ */
220
+ async function readExternalSupport(body, sourceDir, allowedRoot, targetFiles) {
221
+ const refs = externalRefs(body);
222
+ if (refs.length === 0) return {
223
+ ok: true,
224
+ files: []
225
+ };
226
+ let root;
227
+ try {
228
+ root = await realpath(allowedRoot);
229
+ } catch {
230
+ return {
231
+ ok: false,
232
+ message: "external support 根目录不可读:" + allowedRoot
233
+ };
234
+ }
235
+ const files = [];
236
+ const targets = new Set(targetFiles);
237
+ let total = 0;
238
+ for (const ref of refs) {
239
+ const candidate = isAbsolute(ref) ? resolve(ref) : resolve(sourceDir, ref);
240
+ let canonical;
241
+ try {
242
+ canonical = await realpath(candidate);
243
+ } catch {
244
+ return {
245
+ ok: false,
246
+ message: "external support 文件不存在:" + ref
247
+ };
248
+ }
249
+ if (!inside(root, canonical)) return {
250
+ ok: false,
251
+ message: "external support 越界:" + ref
252
+ };
253
+ const info = await stat(canonical);
254
+ if (!info.isFile()) return {
255
+ ok: false,
256
+ message: "external support 不是普通文件:" + ref
257
+ };
258
+ if (info.size > MAX_FILE_BYTES) return {
259
+ ok: false,
260
+ message: "external support 超过单文件上限:" + ref
261
+ };
262
+ total += info.size;
263
+ if (total > MAX_TOTAL_BYTES) return {
264
+ ok: false,
265
+ message: "external support 超过总上限:" + ref
266
+ };
267
+ const targetPath = targetPathFor(ref);
268
+ if (targets.has(targetPath)) return {
269
+ ok: false,
270
+ message: "external support 目标冲突:" + targetPath
271
+ };
272
+ targets.add(targetPath);
273
+ const annotated = annotate(await readFile(canonical, "utf8"), canonical);
274
+ files.push({
275
+ ref,
276
+ originalPath: canonical,
277
+ targetPath,
278
+ content: annotated,
279
+ sha256: createHash("sha256").update(annotated).digest("hex"),
280
+ provenance: "external:" + canonical
281
+ });
282
+ }
283
+ return {
284
+ ok: true,
285
+ files
286
+ };
287
+ }
288
+ //#endregion
289
+ //#region lib/types/quality.js
290
+ /**
291
+ * Quality scoring and near-duplicate detection for the curated skill library.
292
+ *
293
+ * Pure functions over data inputs so the scoring policy is unit-testable and
294
+ * the same math feeds the usage sidecar, the `skill_manage review` surface and
295
+ * the learning graph. Weights follow the Hermes/hermes-claw six-factor model;
296
+ * mutation maturity is a documented DSH approximation (single per-month patch
297
+ * trend ratio replaces the claw timestamp-trend formula, since DSH usage
298
+ * records only carry the last patched timestamp).
299
+ *
300
+ * Batch C (2026-09-27): the similarity half of this module is now TWO NAMED
301
+ * QUESTIONS plus a declared projection — {@link identity} ("is it the same
302
+ * text?") and {@link affinity} ("how much vocabulary do these two share?") asked
303
+ * over {@link projectionText}. Callers name the question and the projection
304
+ * instead of growing a fourth unnamed ruler (design §3C / §1 I2).
305
+ * @module @lmzhen/dsh-evolution-core
306
+ */
307
+ const QUALITY_WEIGHTS = {
308
+ usageFrequency: .25,
309
+ stability: .2,
310
+ recency: .2,
311
+ references: .1,
312
+ mutationMaturity: .2,
313
+ richness: .05
314
+ };
315
+ /** Score below which a skill is flagged for review. */
316
+ const LOW_QUALITY_THRESHOLD = .3;
317
+ function clamp01(value) {
318
+ return Math.max(0, Math.min(1, value));
319
+ }
320
+ function daysBetween(from, now) {
321
+ const t = Date.parse(from);
322
+ if (!Number.isFinite(t)) return 0;
323
+ return Math.max(0, (now.getTime() - t) / 864e5);
324
+ }
325
+ function computeQualityScores(input) {
326
+ const now = input.now ?? /* @__PURE__ */ new Date();
327
+ const scores = /* @__PURE__ */ new Map();
328
+ for (const [name, record] of input.usage) {
329
+ const ageDays = Math.max(1, daysBetween(record.created_at, now));
330
+ const idleDays = daysBetween(latestActivityAt(record) ?? record.created_at, now);
331
+ const patchCount = record.patch_count;
332
+ const loadCount = record.use_count + record.view_count;
333
+ const usageFrequency = clamp01(loadCount / ageDays);
334
+ const stability = loadCount === 0 ? 1 : clamp01(1 - patchCount / loadCount);
335
+ const recency = idleDays < 30 ? 1 : clamp01(1 - (idleDays - 30) / 150);
336
+ const references = clamp01((input.referenceCounts?.get(name) ?? 0) / 3);
337
+ const mutationMaturity = patchCount === 0 ? .3 : patchCount === 1 ? .4 : clamp01((patchCount - 1) / Math.max(1, ageDays / 30));
338
+ const richness = clamp01((input.supportDirs?.get(name) ?? 0) * .175);
339
+ const factors = {
340
+ usageFrequency,
341
+ stability,
342
+ recency,
343
+ references,
344
+ mutationMaturity,
345
+ richness
346
+ };
347
+ const score = usageFrequency * QUALITY_WEIGHTS.usageFrequency + stability * QUALITY_WEIGHTS.stability + recency * QUALITY_WEIGHTS.recency + references * QUALITY_WEIGHTS.references + mutationMaturity * QUALITY_WEIGHTS.mutationMaturity + richness * QUALITY_WEIGHTS.richness;
348
+ scores.set(name, {
349
+ score,
350
+ factors,
351
+ warn: score < LOW_QUALITY_THRESHOLD
352
+ });
353
+ }
354
+ return scores;
355
+ }
356
+ function normalize(content) {
357
+ return content.toLowerCase().replace(/\s+/g, " ").trim();
358
+ }
359
+ /** Named similarity question 1 — "is it the same text?" — as a normalized
360
+ * content hash: case- and whitespace-insensitive, so two texts that differ only
361
+ * in formatting are the SAME text here. Invariant under which projection the
362
+ * caller read the text from.
363
+ *
364
+ * C-26 (v10 audit): NOT named `contentHash` — mutations.ts exports a
365
+ * contentHash of RAW bytes, this one hashes the NORMALIZED text for dedup
366
+ * grouping. Same helper as that rename, now a named question. */
367
+ function identity(text) {
368
+ return createHash("sha256").update(normalize(text)).digest("hex");
369
+ }
370
+ /**
371
+ * The declared projection: WHICH text a comparison weighs.
372
+ *
373
+ * `body` is the library-wide scan's projection (whole SKILL.md, read by the
374
+ * caller). `summary` is name + description in one string — the projection a
375
+ * listing already publishes (`SkillSummary` carries both fields, and a body is
376
+ * attached only when the caller asks for it) — so a summary comparison never
377
+ * reads a body OF ITS OWN: the create-time hint is fed by the listing pass the
378
+ * tool already pays for its frontmatter, and calls no read of its own.
379
+ */
380
+ function projectionText(projection, input) {
381
+ switch (projection) {
382
+ case "body": return input.content ?? "";
383
+ case "summary": return `${input.name ?? ""} ${input.description ?? ""}`;
384
+ }
385
+ }
386
+ /** The comparable vocabulary of one text: lowercase alphanumeric runs, plus
387
+ * whole CJK runs (a Chinese description tokenizes by punctuation, not by word —
388
+ * deliberately: the ruler is one home, and a real tokenizer is a different
389
+ * question than "do these two share vocabulary?"). */
390
+ function vocabulary(text) {
391
+ return new Set(normalize(text).split(/[^a-z0-9\u4e00-\u9fff]+/).filter(Boolean));
392
+ }
393
+ /** Named similarity question 2 — "how much vocabulary do these two share?" —
394
+ * Jaccard over two {@link vocabulary} sets, 0 (nothing in common, or either side
395
+ * empty) to 1 (identical vocabulary). Set-based on purpose: the bulk scan
396
+ * memoizes each name's set once and only the comparisons are budgeted. */
397
+ function affinity(a, b) {
398
+ if (a.size === 0 || b.size === 0) return 0;
399
+ let intersection = 0;
400
+ for (const token of a) if (b.has(token)) intersection += 1;
401
+ return intersection / (a.size + b.size - intersection);
402
+ }
403
+ /** The `affinity` level at which two bodies are treated as the same skill
404
+ * (design §3C: the default is unchanged at 0.95 — it is now a NAME, because the
405
+ * docblock below has linked it since PLAN-R2 while the code carried a bare
406
+ * literal). Callers may still pass their own level. */
407
+ const DEDUP_SIMILARITY_THRESHOLD = .95;
408
+ /** PLAN-R2 P2-8 (2026-09-16): default cap on two-name comparisons in
409
+ * {@link computeDedupGroups}. A 2000-skill library is ~2M pairs; the old
410
+ * unbounded two-two Jaccard ran seconds to tens of seconds per
411
+ * review/`dedup_group` probe. 250k comparisons bounds that to well under a
412
+ * second while staying far above every real library's pair count. Only
413
+ * pairwise comparisons are budgeted — materializing a name's token set
414
+ * (memoized, once per name) and the exact-hash pre-union phase are not. */
415
+ const DEDUP_MAX_PAIR_COMPARISONS = 25e4;
416
+ /**
417
+ * Two-phase near-duplicate clustering: exact normalized-hash groups first,
418
+ * then token-Jaccard edges at {@link DEDUP_SIMILARITY_THRESHOLD} with a token
419
+ * ratio guard, union-find across the whole set.
420
+ *
421
+ * PLAN-R2 P2-8 (2026-09-16): each name's token set is materialized once
422
+ * (memoized map), each pair takes an O(1) size-ratio short-circuit before the
423
+ * intersection, and the pairwise loop is bounded by
424
+ * `maxPairComparisons` (default {@link DEDUP_MAX_PAIR_COMPARISONS}); hitting
425
+ * the budget stops the scan and `truncated: true` says so. Small libraries
426
+ * (below the budget) behave exactly as the unbounded scan did.
427
+ */
428
+ function computeDedupGroups(input) {
429
+ const threshold = input.threshold ?? .95;
430
+ const maxPairComparisons = input.maxPairComparisons ?? 25e4;
431
+ const names = [...input.contents.keys()];
432
+ const hashes = /* @__PURE__ */ new Map();
433
+ for (const name of names) {
434
+ const hash = identity(projectionText("body", { content: input.contents.get(name) ?? "" }));
435
+ const bucket = hashes.get(hash);
436
+ if (bucket) bucket.push(name);
437
+ else hashes.set(hash, [name]);
438
+ }
439
+ const parent = /* @__PURE__ */ new Map();
440
+ const find = (x) => {
441
+ const root = parent.get(x) ?? x;
442
+ if (root !== x) parent.set(x, find(root));
443
+ return parent.get(x) ?? x;
444
+ };
445
+ const union = (a, b) => {
446
+ const [ra, rb] = [find(a), find(b)];
447
+ if (ra !== rb) parent.set(rb, ra);
448
+ };
449
+ for (const [, bucketNames] of hashes) {
450
+ const first = bucketNames[0];
451
+ if (first === void 0 || bucketNames.length === 1) continue;
452
+ for (let index = 1; index < bucketNames.length; index += 1) {
453
+ const peer = bucketNames[index];
454
+ if (peer) union(first, peer);
455
+ }
456
+ }
457
+ const tokens = /* @__PURE__ */ new Map();
458
+ const tokenSet = (name) => {
459
+ let set = tokens.get(name);
460
+ if (!set) {
461
+ set = vocabulary(projectionText("body", { content: input.contents.get(name) ?? "" }));
462
+ tokens.set(name, set);
463
+ }
464
+ return set;
465
+ };
466
+ let compared = 0;
467
+ let truncated = false;
468
+ for (let index = 0; index < names.length && !truncated; index += 1) {
469
+ const a = names[index];
470
+ if (a === void 0) continue;
471
+ for (let other = index + 1; other < names.length; other += 1) {
472
+ const b = names[other];
473
+ if (b === void 0) continue;
474
+ if (compared >= maxPairComparisons) {
475
+ truncated = true;
476
+ break;
477
+ }
478
+ compared += 1;
479
+ const [ta, tb] = [tokenSet(a), tokenSet(b)];
480
+ if (Math.max(ta.size, tb.size) / Math.max(1, Math.min(ta.size, tb.size)) > 5) continue;
481
+ if (affinity(ta, tb) >= threshold) union(a, b);
482
+ }
483
+ }
484
+ const groups = /* @__PURE__ */ new Map();
485
+ for (const name of names) {
486
+ const root = find(name);
487
+ const group = groups.get(root);
488
+ if (group) group.push(name);
489
+ else groups.set(root, [name]);
490
+ }
491
+ return {
492
+ groups: [...groups.values()].filter((group) => group.length > 1),
493
+ truncated
494
+ };
495
+ }
496
+ /**
497
+ * The create-time near-duplicate question (batch C, design §3C-2): WHICH
498
+ * existing skills is this authoring candidate about to near-copy?
499
+ *
500
+ * It is the SAME {@link affinity} question as the library-wide scan, asked over
501
+ * the `summary` projection — the one a listing already publishes
502
+ * (`SkillSummary` carries `name` and `description`; nothing here can see a
503
+ * body, which is the point: a create must not pay a SECOND whole-tree pass — the
504
+ * listing's own frontmatter read is what feeds this comparison). Deliberately hint-only: the caller writes regardless, and the
505
+ * matches are news, not a gate (G4 — the create-time foreground behavior is
506
+ * unchanged).
507
+ *
508
+ * The default level is far below the scan's {@link DEDUP_SIMILARITY_THRESHOLD}
509
+ * because the projection is thinner: a name plus one sentence shares far fewer
510
+ * tokens than two bodies, and a hint that fires on every new skill is noise.
511
+ * Exact same-name candidates are skipped — the library's own create refuses
512
+ * those, and this line must not repeat that refusal.
513
+ */
514
+ const SUMMARY_DUPLICATE_HINT_THRESHOLD = .5;
515
+ function nearDuplicateSummaries(input) {
516
+ const threshold = input.threshold ?? .5;
517
+ const limit = input.limit ?? 3;
518
+ const candidateTokens = vocabulary(projectionText("summary", input.candidate));
519
+ const matches = [];
520
+ for (const existing of input.existing) {
521
+ if (existing.name === input.candidate.name) continue;
522
+ const score = affinity(candidateTokens, vocabulary(projectionText("summary", existing)));
523
+ if (score >= threshold) matches.push({
524
+ name: existing.name,
525
+ score
526
+ });
527
+ }
528
+ return matches.sort((a, b) => b.score - a.score || a.name.localeCompare(b.name)).slice(0, limit);
529
+ }
530
+ /**
531
+ * Prefix-cluster index over a name set (rc.67 merge heuristic, input side):
532
+ * the curator prompt asks the model to identify "prefix clusters — skills
533
+ * sharing a first word or domain keyword"; the deterministic index supplies
534
+ * stable ground truth instead of letting the model infer clusters from the
535
+ * raw list. Key = first alphanumeric run of the lowercased name; groups with
536
+ * at least two members, largest first then alphabetical. Orientation-only:
537
+ * nomination authority stays with the LLM and the candidate-pool gates.
538
+ */
539
+ function computePrefixClusters(names) {
540
+ const groups = /* @__PURE__ */ new Map();
541
+ for (const name of names) {
542
+ const key = name.toLowerCase().split(/[^a-z0-9]+/)[0];
543
+ if (!key) continue;
544
+ const bucket = groups.get(key);
545
+ if (bucket) bucket.push(name);
546
+ else groups.set(key, [name]);
547
+ }
548
+ return [...groups.entries()].filter(([, members]) => members.length >= 2).map(([key, members]) => ({
549
+ key,
550
+ members
551
+ })).sort((a, b) => b.members.length - a.members.length || a.key.localeCompare(b.key));
552
+ }
553
+ //#endregion
554
+ export { EXTRACT_PROMPT_VERSION as C, EXTRACT_PROMPT_V1 as S, ownerCandidatesFromSummaries as T, readProposalReport as _, SUMMARY_DUPLICATE_HINT_THRESHOLD as a, proposalFromPlan as b, computePrefixClusters as c, nearDuplicateSummaries as d, projectionText as f, proposalReportName as g, proposalReportDir as h, QUALITY_WEIGHTS as i, computeQualityScores as l, readExternalSupport as m, DEDUP_SIMILARITY_THRESHOLD as n, affinity as o, vocabulary as p, LOW_QUALITY_THRESHOLD as r, computeDedupGroups as s, DEDUP_MAX_PAIR_COMPARISONS as t, identity as u, readProposalReports as v, findOwnerCandidate as w, EXTRACT_PROMPT_HASH as x, writeProposalReport as y };
package/lib/restrictor.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { n as errorText } from "./errors-BxzLTVbS.js";
2
2
  import { t as presetsPort } from "./presets-C8vuCuNA.js";
3
- import { n as toolsPort } from "./tools-DzcNFex2.js";
3
+ import { n as toolsPort } from "./tools-BrUswg8v.js";
4
4
  //#region lib/types/restrictor.js
5
5
  const name = "evolution-restrictor";
6
6
  const inject = ["agentPresets"];
package/lib/result.js ADDED
@@ -0,0 +1,33 @@
1
+ //#region lib/types/result.js
2
+ function ok(value) {
3
+ return {
4
+ ok: true,
5
+ value
6
+ };
7
+ }
8
+ function err(error) {
9
+ return {
10
+ ok: false,
11
+ error
12
+ };
13
+ }
14
+ function isOk(result) {
15
+ return result.ok;
16
+ }
17
+ function isErr(result) {
18
+ return !result.ok;
19
+ }
20
+ /** The value, or the supplied fallback when the result is an error. */
21
+ function unwrapOr(result, fallback) {
22
+ return result.ok ? result.value : fallback;
23
+ }
24
+ /** Coerce a caught value into the family error shape. */
25
+ function familyError(code, cause) {
26
+ return {
27
+ code,
28
+ message: cause instanceof Error ? cause.message : String(cause),
29
+ ...cause === void 0 ? {} : { cause }
30
+ };
31
+ }
32
+ //#endregion
33
+ export { err, familyError, isErr, isOk, ok, unwrapOr };