@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.
- package/lib/authority-plugin.js +2 -1
- package/lib/citations-CZKTUGQF.js +198 -0
- package/lib/composition/index.js +2 -2
- package/lib/{composition-Cqjbho0t.js → composition-DA8XPfMc.js} +1 -1
- package/lib/connection-DAJy7Xjm.js +28 -0
- package/lib/{ensure-CAjLGd9f.js → ensure-Bx4ksgJk.js} +15 -5
- package/lib/errors.js +2 -0
- package/lib/extract-plan-Bru3c9ec.js +271 -0
- package/lib/extract.js +240 -0
- package/lib/http-routes.js +27 -7
- package/lib/index.js +41 -822
- package/lib/{numeric-D8js3sqC.js → limits-C9jfvxBl.js} +1 -43
- package/lib/{mutation-authority-l57R626O.js → mutation-authority-DQfpXs1O.js} +2 -54
- package/lib/numeric-Dc53KQoe.js +43 -0
- package/lib/platform/index.js +4 -3
- package/lib/platform-DyHnHUmQ.js +251 -0
- package/lib/policy.js +3 -2
- package/lib/quality-WAU6YatF.js +554 -0
- package/lib/restrictor.js +1 -1
- package/lib/result.js +33 -0
- package/lib/runtime/plugin.js +97 -43
- package/lib/{session-projection-DSXnUNZG.js → session-projection-ByNxQi9O.js} +2 -198
- package/lib/skill-health-Bl-MdXZ4.js +1409 -0
- package/lib/skills.js +7 -4
- package/lib/state-store-Jpa-iYIZ.js +54 -0
- package/lib/subagent/index.js +214 -176
- package/lib/{tools-DzcNFex2.js → tools-BrUswg8v.js} +3 -1
- package/lib/types/composition/ensure.js +21 -7
- package/lib/types/extract-plan.d.ts +2 -0
- package/lib/types/extract.d.ts +12 -0
- package/lib/types/extract.js +12 -0
- package/lib/types/http-routes.js +32 -9
- package/lib/types/index.d.ts +0 -3
- package/lib/types/index.js +0 -3
- package/lib/types/long-runs.d.ts +0 -5
- package/lib/types/long-runs.js +0 -7
- package/lib/types/opt-in.js +4 -3
- package/lib/types/params.js +2 -1
- package/lib/types/platform/agents.d.ts +32 -0
- package/lib/types/platform/agents.js +26 -0
- package/lib/types/platform/commands.d.ts +14 -0
- package/lib/types/platform/commands.js +9 -0
- package/lib/types/platform/connection.d.ts +26 -0
- package/lib/types/platform/connection.js +27 -0
- package/lib/types/platform/index.d.ts +26 -0
- package/lib/types/platform/index.js +13 -0
- package/lib/types/platform/llm.d.ts +3 -1
- package/lib/types/platform/llm.js +1 -0
- package/lib/types/platform/platformView.d.ts +21 -0
- package/lib/types/platform/platformView.js +29 -0
- package/lib/types/platform/profileContext.d.ts +16 -0
- package/lib/types/platform/profileContext.js +14 -0
- package/lib/types/platform/sessionQuery.d.ts +14 -0
- package/lib/types/platform/sessionQuery.js +9 -0
- package/lib/types/platform/settings.d.ts +22 -0
- package/lib/types/platform/settings.js +14 -0
- package/lib/types/platform/skills.d.ts +16 -0
- package/lib/types/platform/skills.js +9 -0
- package/lib/types/platform/storageDomain.d.ts +13 -0
- package/lib/types/platform/storageDomain.js +9 -0
- package/lib/types/platform/subagents.d.ts +25 -0
- package/lib/types/platform/subagents.js +17 -0
- package/lib/types/platform/systemPrompt.d.ts +16 -0
- package/lib/types/platform/systemPrompt.js +13 -0
- package/lib/types/platform/tools.d.ts +4 -0
- package/lib/types/platform/tools.js +2 -0
- package/lib/types/platform/userQuestions.d.ts +33 -0
- package/lib/types/platform/userQuestions.js +9 -0
- package/lib/types/platform/workingDirectory.d.ts +14 -0
- package/lib/types/platform/workingDirectory.js +9 -0
- package/lib/types/platform-line.generated.d.ts +5 -5
- package/lib/types/platform-line.generated.js +5 -5
- package/lib/types/platform-services.js +3 -0
- package/lib/types/result.d.ts +35 -0
- package/lib/types/result.js +25 -0
- package/lib/types/runtime/llm.d.ts +2 -2
- package/lib/types/runtime/llm.js +5 -8
- package/lib/types/runtime/platform.d.ts +37 -4
- package/lib/types/runtime/platform.js +40 -5
- package/lib/types/runtime/projections.d.ts +9 -4
- package/lib/types/runtime/projections.js +64 -28
- package/lib/types/subagent/channel.d.ts +1 -3
- package/lib/types/subagent/channel.js +2 -332
- package/lib/types/subagent/index.d.ts +2 -0
- package/lib/types/subagent/index.js +2 -0
- package/lib/types/subagent/kernel.d.ts +4 -0
- package/lib/types/subagent/kernel.js +234 -0
- package/lib/types/subagent/readiness.js +5 -7
- package/lib/types/subagent/run.d.ts +53 -0
- package/lib/types/subagent/run.js +125 -0
- package/lib/types/subagent/types.d.ts +2 -2
- package/lib/types/write-inventory.d.ts +0 -11
- package/lib/types/write-inventory.js +0 -16
- package/lib/usage-DdjIBAkm.js +1252 -0
- package/package.json +37 -25
- package/lib/platform-Cc9cNt5j.js +0 -111
- package/lib/skill-health-DP8z9TPf.js +0 -2923
|
@@ -0,0 +1,1252 @@
|
|
|
1
|
+
import { c as transactIo, o as nodeEvolutionIo } from "./io-GxghO3Ip.js";
|
|
2
|
+
import { o as resolveCitations } from "./citations-CZKTUGQF.js";
|
|
3
|
+
import { G as SKILL_NAME_RE, i as DEFAULT_SKILL_LIMITS, u as CONTENT_SPLIT_HINT } from "./limits-C9jfvxBl.js";
|
|
4
|
+
import { n as isRecord } from "./guards-3f02mnf2.js";
|
|
5
|
+
import { join } from "node:path";
|
|
6
|
+
import { parse } from "yaml";
|
|
7
|
+
//#region lib/types/reference-rewrite.js
|
|
8
|
+
/**
|
|
9
|
+
* Reference re-homing plans (0.5.0 V1, design §16.7).
|
|
10
|
+
*
|
|
11
|
+
* A consolidation moves one skill's body under ANOTHER skill root, where every
|
|
12
|
+
* support-dir reference resolves against that other root (design §2.1). This
|
|
13
|
+
* module plans what has to happen to the support files and to the body's
|
|
14
|
+
* references for the move to leave no dangling link. Pure: the caller owns IO,
|
|
15
|
+
* decides the destination names, and decides whether the plan is applied (V2)
|
|
16
|
+
* or only reported (V1). Cross-skill rewriting is out of scope by design (§14) —
|
|
17
|
+
* a plan covers ONE body.
|
|
18
|
+
*/
|
|
19
|
+
/**
|
|
20
|
+
* Provisional re-homing rule. The naming style for re-homed files is still an
|
|
21
|
+
* open decision (design §16.3 B5); this rule only fires on a COLLISION, where
|
|
22
|
+
* something has to give: a path that the target already occupies gets the source
|
|
23
|
+
* name as a prefix (`references/a.md` -> `references/<source>-a.md`). Nested
|
|
24
|
+
* destinations are deliberately avoided: the support listing is one level deep,
|
|
25
|
+
* so a file moved into a subdirectory would drop out of the listing entirely.
|
|
26
|
+
* @param sourceFiles - the moving skill's support files.
|
|
27
|
+
* @param targetFiles - the destination skill's support files.
|
|
28
|
+
* @param sourceName - the moving skill's name, used as the collision prefix.
|
|
29
|
+
* @returns the moves plus the paths that collided (for the report).
|
|
30
|
+
*/
|
|
31
|
+
function planRehoming(sourceFiles, targetFiles, sourceName) {
|
|
32
|
+
const taken = new Set(targetFiles);
|
|
33
|
+
const collisions = [];
|
|
34
|
+
const moves = [];
|
|
35
|
+
for (const path of sourceFiles) {
|
|
36
|
+
if (!taken.has(path)) {
|
|
37
|
+
moves.push({
|
|
38
|
+
from: path,
|
|
39
|
+
to: path
|
|
40
|
+
});
|
|
41
|
+
continue;
|
|
42
|
+
}
|
|
43
|
+
collisions.push(path);
|
|
44
|
+
const cut = path.lastIndexOf("/");
|
|
45
|
+
const dir = cut < 0 ? "" : path.slice(0, cut + 1);
|
|
46
|
+
const name = path.slice(cut + 1);
|
|
47
|
+
let candidate = `${dir}${sourceName}-${name}`;
|
|
48
|
+
let counter = 2;
|
|
49
|
+
while (taken.has(candidate)) {
|
|
50
|
+
candidate = `${dir}${sourceName}-${counter}-${name}`;
|
|
51
|
+
counter += 1;
|
|
52
|
+
}
|
|
53
|
+
taken.add(candidate);
|
|
54
|
+
moves.push({
|
|
55
|
+
from: path,
|
|
56
|
+
to: candidate
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
return {
|
|
60
|
+
moves,
|
|
61
|
+
collisions
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Plan the reference rewrites for one body that is moving into another root.
|
|
66
|
+
* @param input - the body, the MOVING skill's file list, the re-homing moves and
|
|
67
|
+
* the destination's file list (with the moved paths already included).
|
|
68
|
+
* @returns the edits, the cited files without a destination, and any target that
|
|
69
|
+
* the destination file list cannot prove (applying such a plan would dangle).
|
|
70
|
+
*/
|
|
71
|
+
function planReferenceRewrite(input) {
|
|
72
|
+
const report = resolveCitations({
|
|
73
|
+
content: input.content,
|
|
74
|
+
file: "SKILL.md",
|
|
75
|
+
files: input.files
|
|
76
|
+
});
|
|
77
|
+
const byFrom = new Map(input.moves.map((move) => [move.from, move.to]));
|
|
78
|
+
const available = new Set(input.targetFiles);
|
|
79
|
+
const edits = [];
|
|
80
|
+
const unresolved = [];
|
|
81
|
+
const residual = /* @__PURE__ */ new Set();
|
|
82
|
+
const used = /* @__PURE__ */ new Set();
|
|
83
|
+
for (const ref of report.refs) {
|
|
84
|
+
if (ref.kind !== "citation" || ref.target === null) continue;
|
|
85
|
+
const move = byFrom.get(ref.target);
|
|
86
|
+
const to = move ?? ref.target;
|
|
87
|
+
if (move !== void 0) {
|
|
88
|
+
used.add(ref.target);
|
|
89
|
+
if (move !== ref.target) edits.push({
|
|
90
|
+
line: ref.line,
|
|
91
|
+
from: ref.target,
|
|
92
|
+
to: move,
|
|
93
|
+
raw: ref.raw
|
|
94
|
+
});
|
|
95
|
+
} else if (!report.dangling.some((entry) => entry.target === ref.target)) unresolved.push(ref.target);
|
|
96
|
+
if (!available.has(to)) residual.add(to);
|
|
97
|
+
}
|
|
98
|
+
return {
|
|
99
|
+
edits,
|
|
100
|
+
unresolved: [...new Set(unresolved)],
|
|
101
|
+
residualDangling: [...residual],
|
|
102
|
+
moves: input.moves.filter((move) => used.has(move.from))
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* Apply a plan's edits to the body (V2). Line-wise and literal: line N gets its
|
|
107
|
+
* FIRST occurrence of the recorded token replaced, everything else is copied
|
|
108
|
+
* byte for byte — no regex, so a token that happens to contain regex
|
|
109
|
+
* metacharacters cannot rewrite more than it matched.
|
|
110
|
+
* @param content - the body the plan was computed against.
|
|
111
|
+
* @param edits - the plan's edits.
|
|
112
|
+
* @returns the rewritten body (identical to the input when there is nothing to do).
|
|
113
|
+
*/
|
|
114
|
+
function applyReferenceRewrite(content, edits) {
|
|
115
|
+
if (edits.length === 0) return content;
|
|
116
|
+
const byLine = /* @__PURE__ */ new Map();
|
|
117
|
+
for (const edit of edits) {
|
|
118
|
+
const list = byLine.get(edit.line);
|
|
119
|
+
if (list === void 0) byLine.set(edit.line, [edit]);
|
|
120
|
+
else list.push(edit);
|
|
121
|
+
}
|
|
122
|
+
const lines = content.split("\n");
|
|
123
|
+
for (const [lineNo, lineEdits] of byLine) {
|
|
124
|
+
const index = lineNo - 1;
|
|
125
|
+
const original = lines[index];
|
|
126
|
+
if (original === void 0) continue;
|
|
127
|
+
let next = original;
|
|
128
|
+
for (const edit of lineEdits) {
|
|
129
|
+
const at = next.indexOf(edit.raw);
|
|
130
|
+
if (at < 0) continue;
|
|
131
|
+
next = next.slice(0, at) + edit.to + next.slice(at + edit.raw.length);
|
|
132
|
+
}
|
|
133
|
+
lines[index] = next;
|
|
134
|
+
}
|
|
135
|
+
return lines.join("\n");
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* One-line, model-facing summary of a plan, for the consolidation refusal and
|
|
139
|
+
* for the V2 apply path's audit text.
|
|
140
|
+
* @param plan - the plan to describe.
|
|
141
|
+
* @returns a compact sentence naming counts, the moves and any residual risk.
|
|
142
|
+
*/
|
|
143
|
+
function describeReferenceRewrite(plan) {
|
|
144
|
+
const renames = plan.moves.filter((move) => move.from !== move.to);
|
|
145
|
+
return `plan: ${[
|
|
146
|
+
`re-home ${plan.moves.length} file(s)`,
|
|
147
|
+
renames.length === 0 ? "" : `renamed: ${renames.map((move) => `${move.from}->${move.to}`).join(", ")}`,
|
|
148
|
+
`rewrite ${plan.edits.length} reference(s)`,
|
|
149
|
+
`residual dangling ${plan.residualDangling.length}`,
|
|
150
|
+
plan.unresolved.length === 0 ? "" : `no destination: ${plan.unresolved.slice(0, 5).join(", ")}`
|
|
151
|
+
].filter((part) => part.length > 0).join("; ")}`;
|
|
152
|
+
}
|
|
153
|
+
//#endregion
|
|
154
|
+
//#region lib/types/support-refs.js
|
|
155
|
+
/**
|
|
156
|
+
* Support-directory references in a markdown body (009 kernel): references/…,
|
|
157
|
+
* templates/…, scripts/…, assets/… relative links — any extension and nested
|
|
158
|
+
* paths. Pure: who checks them and what the verdict is belongs to the caller.
|
|
159
|
+
* `..` traversal is a different defect class (path validation owns it) and is
|
|
160
|
+
* not a support link.
|
|
161
|
+
*/
|
|
162
|
+
function supportRefs(content) {
|
|
163
|
+
const refs = [];
|
|
164
|
+
for (const match of content.matchAll(/(?<![A-Za-z0-9._/-])(?:references|templates|scripts|assets)\/[A-Za-z0-9._/-]+/g)) {
|
|
165
|
+
const ref = match[0];
|
|
166
|
+
if (ref.includes("..")) continue;
|
|
167
|
+
refs.push(ref);
|
|
168
|
+
}
|
|
169
|
+
return refs;
|
|
170
|
+
}
|
|
171
|
+
/**
|
|
172
|
+
* References that leave the skill root: parent traversals or absolute support paths.
|
|
173
|
+
* Extract must not silently treat these as relative support files; the caller reports
|
|
174
|
+
* them (bounded external copy is a separate, explicit policy).
|
|
175
|
+
* @param content - markdown body.
|
|
176
|
+
* @returns external-looking support references, de-duplicated in first-seen order.
|
|
177
|
+
*/
|
|
178
|
+
function externalRefs(content) {
|
|
179
|
+
const refs = [];
|
|
180
|
+
for (const match of content.matchAll(/(?:^|[\s("'`])((?:\.\.\/)+[A-Za-z0-9._/-]+|\/[A-Za-z0-9._/-]+)/g)) {
|
|
181
|
+
const ref = match[1]?.replace(/[.,;:]+$/, "");
|
|
182
|
+
if (ref === void 0 || ref.length === 0 || refs.includes(ref)) continue;
|
|
183
|
+
refs.push(ref);
|
|
184
|
+
}
|
|
185
|
+
return refs;
|
|
186
|
+
}
|
|
187
|
+
//#endregion
|
|
188
|
+
//#region lib/types/frontmatter.js
|
|
189
|
+
/**
|
|
190
|
+
* Frontmatter parsing, normalization and validation for skill Markdown files.
|
|
191
|
+
*
|
|
192
|
+
* Split out of skill-store.ts (S2-1): pure functions over file text, no store
|
|
193
|
+
* state. skill-store.ts re-exports the same names it exported before the split,
|
|
194
|
+
* so the package export surface is unchanged.
|
|
195
|
+
*/
|
|
196
|
+
/**
|
|
197
|
+
* Shared frontmatter block detection (P3-3 single owner): opening line `---`
|
|
198
|
+
* and closing line exactly `---`. Used by `parseFrontmatter`,
|
|
199
|
+
* `frontmatterCatalogInvalid` and `normalizeFrontmatter` so the three can
|
|
200
|
+
* never disagree about where the block ends (the loose `indexOf('\n---')`
|
|
201
|
+
* form matched `\n----` and was replaced by this strict line rule).
|
|
202
|
+
*
|
|
203
|
+
* V27 G2.1: both fence lines are matched EXACTLY, tolerating only a trailing
|
|
204
|
+
* `\r` — the same rule the upstream filesystem catalog uses
|
|
205
|
+
* (`skill-filesystem.parseFrontmatter`). The former `.trim()` comparison
|
|
206
|
+
* accepted ` --- `, so an indented fence loaded in the family while the
|
|
207
|
+
* platform ignored the file: family visibility split from platform visibility,
|
|
208
|
+
* which is exactly what a strict-YAML frontmatter is supposed to prevent.
|
|
209
|
+
*/
|
|
210
|
+
/**
|
|
211
|
+
* S1.1 (v37 P1-4): the frontmatter block is split on LF and every line keeps its
|
|
212
|
+
* own `\r`, so the byte-preserving rebuild (`lines.join('\n')`) is exact. Line
|
|
213
|
+
* MATCHERS must therefore look at a CR-stripped view: JS `.` does not match `\r`,
|
|
214
|
+
* so `(.*)$` never reaches the end of a CRLF line.
|
|
215
|
+
* @param line - one block line, possibly CR-terminated.
|
|
216
|
+
* @returns the line without its trailing CR.
|
|
217
|
+
*/
|
|
218
|
+
function withoutCr(line) {
|
|
219
|
+
return line.endsWith("\r") ? line.slice(0, -1) : line;
|
|
220
|
+
}
|
|
221
|
+
function frontmatterBlock(content) {
|
|
222
|
+
if (!content.trimStart().startsWith("---")) return null;
|
|
223
|
+
const firstBreak = content.indexOf("\n");
|
|
224
|
+
const nl = firstBreak > 0 && content[firstBreak - 1] === "\r" ? "\r\n" : "\n";
|
|
225
|
+
const lines = content.split("\n");
|
|
226
|
+
if ((lines[0] ?? "").replace(/\r$/, "") !== "---") return null;
|
|
227
|
+
let end = -1;
|
|
228
|
+
for (let i = 1; i < lines.length; i++) {
|
|
229
|
+
const line = lines[i];
|
|
230
|
+
if (line === void 0) continue;
|
|
231
|
+
if (line === "---" || line === "---\r") {
|
|
232
|
+
end = i;
|
|
233
|
+
break;
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
if (end < 0) return null;
|
|
237
|
+
return {
|
|
238
|
+
block: lines.slice(1, end).join("\n"),
|
|
239
|
+
lines,
|
|
240
|
+
end,
|
|
241
|
+
nl
|
|
242
|
+
};
|
|
243
|
+
}
|
|
244
|
+
/**
|
|
245
|
+
* Raw-line scan of a frontmatter block: the single owner of "which entries the
|
|
246
|
+
* strict catalog cannot load". `frontmatterCatalogInvalid` publishes it and
|
|
247
|
+
* `normalizeFrontmatter` decides each rewrite with the same predicate
|
|
248
|
+
* (`yamlPlainScalarNeedsQuotes`), so the audit verdict and the write path can
|
|
249
|
+
* never disagree. A9 (audit P2-12): the scan is ENDING-AGNOSTIC — lines are
|
|
250
|
+
* split on `\n` with the per-line CR stripped, exactly the iteration the
|
|
251
|
+
* rewrite path uses. The former split on the block's FIRST-LINE ending turned
|
|
252
|
+
* a mixed-ending block (first line CRLF, entries LF) into one unsplit chunk
|
|
253
|
+
* whose entries were all skipped, so an unquoted ` #` value read as CLEAN
|
|
254
|
+
* while the catalog silently dropped it and the next edit would have quoted
|
|
255
|
+
* it. Only single-line `key: value` entries are judged.
|
|
256
|
+
*/
|
|
257
|
+
function unsafeFrontmatterEntries(block) {
|
|
258
|
+
const found = [];
|
|
259
|
+
for (const rawLine of block.split("\n")) {
|
|
260
|
+
const match = /^([A-Za-z0-9_-]+):\s*(.*)$/.exec(withoutCr(rawLine));
|
|
261
|
+
if (!match) continue;
|
|
262
|
+
const key = match[1];
|
|
263
|
+
if (key === void 0) continue;
|
|
264
|
+
const value = (match[2] ?? "").trim();
|
|
265
|
+
if (yamlPlainScalarNeedsQuotes(value)) found.push({
|
|
266
|
+
key,
|
|
267
|
+
value
|
|
268
|
+
});
|
|
269
|
+
}
|
|
270
|
+
return found;
|
|
271
|
+
}
|
|
272
|
+
/**
|
|
273
|
+
* Frontmatter fields the platform catalog reads as STRINGS (`stringField` /
|
|
274
|
+
* `optionalString` in `skill-filesystem`): any other YAML type reads as
|
|
275
|
+
* ABSENT there, and an absent `name`/`description` makes the catalog ignore the
|
|
276
|
+
* whole file. The family publishes text for these keys anyway (its lenient
|
|
277
|
+
* read), which is the one split a write must not create.
|
|
278
|
+
*/
|
|
279
|
+
const PLATFORM_STRING_FIELDS = [
|
|
280
|
+
"name",
|
|
281
|
+
"description",
|
|
282
|
+
"whenToUse"
|
|
283
|
+
];
|
|
284
|
+
/**
|
|
285
|
+
* Frontmatter values as the STRICT platform catalog reads them — the `yaml`
|
|
286
|
+
* package (YAML 1.2 core schema, the same dependency the platform's
|
|
287
|
+
* skill-filesystem parses with — see the import note above),
|
|
288
|
+
* the parser `normalizeFrontmatter` also verifies rewrites with — or `null`
|
|
289
|
+
* when the block is not loadable as a YAML mapping. Also reports the platform
|
|
290
|
+
* string fields whose value is not a string ({@link PlatformStringSplit}).
|
|
291
|
+
*
|
|
292
|
+
* Scalars publish their text (`name`, `description`, `whenToUse` are strings by
|
|
293
|
+
* contract; a number/boolean-shaped value keeps the text the family always
|
|
294
|
+
* published), a flow or block sequence publishes its inline `[a, b]` form
|
|
295
|
+
* (`relatedSkillNames` scans names out of it), and a nested mapping publishes
|
|
296
|
+
* nothing — no consumer in this family reads one, and a lossy string could be
|
|
297
|
+
* picked up by a routing field. A string value is trimmed: YAML's block-scalar
|
|
298
|
+
* chomping appends a newline that the family's single-line routing fields never
|
|
299
|
+
* carried.
|
|
300
|
+
*/
|
|
301
|
+
function strictFrontmatterValues(block) {
|
|
302
|
+
if (block.trim() === "") return {
|
|
303
|
+
values: /* @__PURE__ */ new Map(),
|
|
304
|
+
split: []
|
|
305
|
+
};
|
|
306
|
+
let loaded;
|
|
307
|
+
try {
|
|
308
|
+
loaded = parse(block);
|
|
309
|
+
} catch {
|
|
310
|
+
return null;
|
|
311
|
+
}
|
|
312
|
+
if (loaded === null || loaded === void 0) return {
|
|
313
|
+
values: /* @__PURE__ */ new Map(),
|
|
314
|
+
split: []
|
|
315
|
+
};
|
|
316
|
+
if (typeof loaded !== "object" || Array.isArray(loaded)) return null;
|
|
317
|
+
const values = /* @__PURE__ */ new Map();
|
|
318
|
+
const split = [];
|
|
319
|
+
let metadata;
|
|
320
|
+
for (const [key, value] of Object.entries(loaded)) {
|
|
321
|
+
if (typeof value !== "string" && PLATFORM_STRING_FIELDS.includes(key)) split.push({
|
|
322
|
+
key,
|
|
323
|
+
kind: value === null || value === void 0 ? "null" : Array.isArray(value) ? "sequence" : typeof value === "object" ? "mapping" : "scalar"
|
|
324
|
+
});
|
|
325
|
+
if (typeof value === "string") {
|
|
326
|
+
values.set(key, value.trim());
|
|
327
|
+
continue;
|
|
328
|
+
}
|
|
329
|
+
if (typeof value === "number" || typeof value === "boolean") {
|
|
330
|
+
values.set(key, String(value));
|
|
331
|
+
continue;
|
|
332
|
+
}
|
|
333
|
+
if (Array.isArray(value)) {
|
|
334
|
+
values.set(key, `[${value.map((item) => String(item)).join(", ")}]`);
|
|
335
|
+
continue;
|
|
336
|
+
}
|
|
337
|
+
if (key === "metadata" && isRecord(value)) {
|
|
338
|
+
metadata = value;
|
|
339
|
+
continue;
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
return {
|
|
343
|
+
values,
|
|
344
|
+
split,
|
|
345
|
+
metadata
|
|
346
|
+
};
|
|
347
|
+
}
|
|
348
|
+
/**
|
|
349
|
+
* Lenient line scan, used only for a block the strict parser rejects: the
|
|
350
|
+
* family keeps routing a legacy file the platform refuses, and
|
|
351
|
+
* `catalogInvalid` reports the split instead of hiding it. Values are trimmed
|
|
352
|
+
* and unquoted exactly as before.
|
|
353
|
+
*/
|
|
354
|
+
function lenientFrontmatterValues(block, nl) {
|
|
355
|
+
const values = /* @__PURE__ */ new Map();
|
|
356
|
+
const blockLines = block.split(nl);
|
|
357
|
+
for (let i = 0; i < blockLines.length; i += 1) {
|
|
358
|
+
const line = withoutCr(blockLines[i] ?? "");
|
|
359
|
+
const match = /^([A-Za-z0-9_-]+):\s*(.*)$/.exec(line);
|
|
360
|
+
if (!match) continue;
|
|
361
|
+
const [, key, value] = match;
|
|
362
|
+
if (key === void 0 || value === void 0) continue;
|
|
363
|
+
const header = /^([>|])[+-]?\d*$/.exec(value.trim());
|
|
364
|
+
if (header !== null) {
|
|
365
|
+
const fold = header[1] === ">";
|
|
366
|
+
const parts = [];
|
|
367
|
+
let scan = i + 1;
|
|
368
|
+
for (; scan < blockLines.length; scan += 1) {
|
|
369
|
+
const raw = blockLines[scan] ?? "";
|
|
370
|
+
if (raw.trim() === "") {
|
|
371
|
+
parts.push("");
|
|
372
|
+
continue;
|
|
373
|
+
}
|
|
374
|
+
if (!/^\s/.test(raw)) break;
|
|
375
|
+
parts.push(raw.trim());
|
|
376
|
+
}
|
|
377
|
+
while (parts.length > 0 && parts[parts.length - 1] === "") parts.pop();
|
|
378
|
+
let folded = "";
|
|
379
|
+
for (const part of parts) {
|
|
380
|
+
if (part === "") {
|
|
381
|
+
if (folded !== "" && !folded.endsWith("\n")) folded += "\n";
|
|
382
|
+
continue;
|
|
383
|
+
}
|
|
384
|
+
if (folded === "" || folded.endsWith("\n")) folded += part;
|
|
385
|
+
else folded += ` ${part}`;
|
|
386
|
+
}
|
|
387
|
+
values.set(key, (fold ? folded : parts.join("\n")).trim());
|
|
388
|
+
i = scan - 1;
|
|
389
|
+
continue;
|
|
390
|
+
}
|
|
391
|
+
values.set(key, value.trim().replace(/^["']|["']$/g, ""));
|
|
392
|
+
}
|
|
393
|
+
return values;
|
|
394
|
+
}
|
|
395
|
+
/**
|
|
396
|
+
* The single read of a SKILL.md frontmatter block: values, body and every
|
|
397
|
+
* strict-catalog signal, computed once. `null` only when the file has no
|
|
398
|
+
* frontmatter block; the body may be empty. {@link parseFrontmatter} and
|
|
399
|
+
* {@link frontmatterCatalogInvalid} are its two projections.
|
|
400
|
+
*
|
|
401
|
+
* @param content - the SKILL.md text.
|
|
402
|
+
* @returns the block read, or `null` when there is no block.
|
|
403
|
+
*/
|
|
404
|
+
function readFrontmatterBlock(content) {
|
|
405
|
+
const found = frontmatterBlock(content);
|
|
406
|
+
if (!found) return null;
|
|
407
|
+
const body = found.lines.slice(found.end + 1).join("\n").trim();
|
|
408
|
+
const strict = strictFrontmatterValues(found.block);
|
|
409
|
+
const values = strict?.values ?? lenientFrontmatterValues(found.block, found.nl);
|
|
410
|
+
const frontmatter = {};
|
|
411
|
+
for (const [key, value] of values) frontmatter[key] = value;
|
|
412
|
+
return {
|
|
413
|
+
frontmatter,
|
|
414
|
+
body,
|
|
415
|
+
unsafeValues: unsafeFrontmatterEntries(found.block),
|
|
416
|
+
strictFailed: strict === null,
|
|
417
|
+
platformStringSplit: strict?.split ?? [],
|
|
418
|
+
metadata: strict?.metadata
|
|
419
|
+
};
|
|
420
|
+
}
|
|
421
|
+
/**
|
|
422
|
+
* Parse a SKILL.md: its frontmatter values and body, or `null` when the file
|
|
423
|
+
* has no frontmatter block or no body. Every consumer of frontmatter values
|
|
424
|
+
* goes through here — the write path's validation, `list()`'s published
|
|
425
|
+
* description, `relatedSkillNames` and the audit — so all of them read the same
|
|
426
|
+
* bytes the same way.
|
|
427
|
+
*
|
|
428
|
+
* @param content - the SKILL.md text.
|
|
429
|
+
* @returns the read, or `null` when there is no block or no body.
|
|
430
|
+
*/
|
|
431
|
+
function parseFrontmatter(content) {
|
|
432
|
+
const read = readFrontmatterBlock(content);
|
|
433
|
+
if (!read || !read.body) return null;
|
|
434
|
+
return {
|
|
435
|
+
frontmatter: read.frontmatter,
|
|
436
|
+
body: read.body,
|
|
437
|
+
unsafeValues: read.unsafeValues,
|
|
438
|
+
metadata: read.metadata,
|
|
439
|
+
catalogInvalid: read.strictFailed || read.unsafeValues.length > 0 || read.platformStringSplit.length > 0,
|
|
440
|
+
platformStringSplit: read.platformStringSplit
|
|
441
|
+
};
|
|
442
|
+
}
|
|
443
|
+
/**
|
|
444
|
+
* Whether this file's frontmatter is valid as written for the strict platform
|
|
445
|
+
* catalog (see `FrontmatterRead.catalogInvalid`). Body-independent (a body-less
|
|
446
|
+
* file is still judged), and derived from the same read as `parseFrontmatter` —
|
|
447
|
+
* so the audit's verdict and the values the family publishes for one file can
|
|
448
|
+
* never disagree (V27 G2.1).
|
|
449
|
+
*
|
|
450
|
+
* @param content - the SKILL.md text.
|
|
451
|
+
* @returns `true` when the strict parser rejects the block or an unquoted value would read as something else.
|
|
452
|
+
*/
|
|
453
|
+
function frontmatterCatalogInvalid(content) {
|
|
454
|
+
const read = readFrontmatterBlock(content);
|
|
455
|
+
if (read !== null) return read.strictFailed || read.unsafeValues.length > 0 || read.platformStringSplit.length > 0;
|
|
456
|
+
return frontmatterBlock(content.replace(/^\uFEFF/, "").replace(/\r\n/g, "\n")) !== null;
|
|
457
|
+
}
|
|
458
|
+
/** YAML plain-scalar hazards that make an UNQUOTED frontmatter value
|
|
459
|
+
* unloadable to the platform catalog (strict YAML parser): `: ` (mapping
|
|
460
|
+
* separator), ` #` (comment start), a trailing `:` (a mapping marker),
|
|
461
|
+
* or a leading YAML indicator. The evolution `parseFrontmatter` is
|
|
462
|
+
* deliberately lenient, so violations silently split family-visibility from
|
|
463
|
+
* platform-visibility (0.3.11 inkos-harness case: the description carried
|
|
464
|
+
* "…: " and the catalog dropped the whole skill). Already-quoted values and
|
|
465
|
+
* well-formed flow collections (`[a, b]` / `{a: b}`) are considered safe.
|
|
466
|
+
* 0.3.16 (E-47): null/bool/number-shaped plain scalars are flagged too — they
|
|
467
|
+
* parse as booleans/numbers on the platform while the family keeps the string
|
|
468
|
+
* (a `description: true` split-brain).
|
|
469
|
+
* This rule is only the FAST PATH — the write path re-verifies every rewrite
|
|
470
|
+
* with the real YAML parser (see normalizeFrontmatter), so an incomplete
|
|
471
|
+
* approximation can never corrupt a multiline flow value (P3-4). */
|
|
472
|
+
function yamlPlainScalarNeedsQuotes(value) {
|
|
473
|
+
if (value.length === 0) return false;
|
|
474
|
+
if (value.length >= 2 && (value.startsWith("\"") && value.endsWith("\"") || value.startsWith("'") && value.endsWith("'"))) return false;
|
|
475
|
+
if (/^\[.*\]$/.test(value) || /^\{.*\}$/.test(value)) return false;
|
|
476
|
+
if (/^[>|][+-]?\d*$/.test(value)) return false;
|
|
477
|
+
if (value.includes(": ")) return true;
|
|
478
|
+
if (value.includes(" #")) return true;
|
|
479
|
+
if (value.endsWith(":")) return true;
|
|
480
|
+
if (/^(?:null|true|false|~)$/i.test(value)) return true;
|
|
481
|
+
if (/^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?$/.test(value)) return true;
|
|
482
|
+
if (/^0x[0-9a-f]+$/i.test(value)) return true;
|
|
483
|
+
if (/^0o[0-7]+$/.test(value)) return true;
|
|
484
|
+
if (/^(?:[-+]?\.inf|\.nan)$/i.test(value)) return true;
|
|
485
|
+
if (/^[-?:,[\]{}#&*!|>'"%@`\s]/.test(value)) return true;
|
|
486
|
+
return false;
|
|
487
|
+
}
|
|
488
|
+
/**
|
|
489
|
+
* Normalize a SKILL.md frontmatter block into catalog-loadable YAML: values
|
|
490
|
+
* that YAML forbids unquoted get quotes — double quotes normally, single
|
|
491
|
+
* quotes (with `''` doubling) when the value contains `"` or `\` (both legal
|
|
492
|
+
* unescaped inside single-quoted YAML). Idempotent; only single-line
|
|
493
|
+
* `key: value` entries are touched; body text is never modified; line-ending
|
|
494
|
+
* style is preserved. **Every rewrite is re-verified with the real YAML
|
|
495
|
+
* parser** (`yaml` — the package the platform's skill-filesystem catalog parses
|
|
496
|
+
* with, YAML 1.2 core schema; PLAN S2.1, 2026-09-16 — the former "js-yaml, the
|
|
497
|
+
* same parser" claim was false: js-yaml speaks YAML 1.1 full and diverged on
|
|
498
|
+
* dates, timestamps and 1.1 int forms): if the
|
|
499
|
+
* rewritten block no longer parses, or a rewritten value's parsed content
|
|
500
|
+
* differs from the original, the rewrite is rolled back and reported in
|
|
501
|
+
* `issues` (fail-loud, never a silent value corruption — P3-4).
|
|
502
|
+
*
|
|
503
|
+
* V10-02 (P2-3): the rewrite decision is PER LINE — each entry parses its own
|
|
504
|
+
* value, so a duplicated key can never route one entry's unsafe value into a
|
|
505
|
+
* different line's rewrite (the old key→Map lookup rewrote the FIRST (safe)
|
|
506
|
+
* line with the SECOND line's quoted value, and the last-wins YAML reader
|
|
507
|
+
* masked the damage). A duplicated key is itself invalid input and is
|
|
508
|
+
* reported in `issues` (the write path refuses) instead of being rewritten.
|
|
509
|
+
*/
|
|
510
|
+
function normalizeFrontmatter(content) {
|
|
511
|
+
const block = frontmatterBlock(content);
|
|
512
|
+
if (!block) return {
|
|
513
|
+
content,
|
|
514
|
+
changed: false,
|
|
515
|
+
fields: [],
|
|
516
|
+
issues: []
|
|
517
|
+
};
|
|
518
|
+
const { lines, end } = block;
|
|
519
|
+
const fields = [];
|
|
520
|
+
const issues = [];
|
|
521
|
+
const seen = /* @__PURE__ */ new Set();
|
|
522
|
+
const originalValues = /* @__PURE__ */ new Map();
|
|
523
|
+
let changed = false;
|
|
524
|
+
for (let i = 1; i < end; i++) {
|
|
525
|
+
const raw = lines[i];
|
|
526
|
+
if (raw === void 0) continue;
|
|
527
|
+
const match = /^([A-Za-z0-9_-]+):\s*(.*)$/.exec(withoutCr(raw));
|
|
528
|
+
if (!match) continue;
|
|
529
|
+
const key = match[1];
|
|
530
|
+
if (key === void 0) continue;
|
|
531
|
+
const value = (match[2] ?? "").trim();
|
|
532
|
+
if (seen.has(key)) {
|
|
533
|
+
issues.push(`${key}: duplicate frontmatter key — remove the repeated entry and retry`);
|
|
534
|
+
continue;
|
|
535
|
+
}
|
|
536
|
+
seen.add(key);
|
|
537
|
+
if (!yamlPlainScalarNeedsQuotes(value)) continue;
|
|
538
|
+
if (/[\u0000-\u0008\u000B\u000C\u000E-\u001F]/.test(value)) {
|
|
539
|
+
issues.push(`${key}: value contains control characters — clean them manually`);
|
|
540
|
+
continue;
|
|
541
|
+
}
|
|
542
|
+
lines[i] = `${key}: ${value.includes("\"") || value.includes("\\") ? `'${value.replace(/'/g, "''")}'` : `"${value}"`}${raw.endsWith("\r") ? "\r" : ""}`;
|
|
543
|
+
originalValues.set(key, value);
|
|
544
|
+
fields.push(key);
|
|
545
|
+
changed = true;
|
|
546
|
+
}
|
|
547
|
+
if (issues.length > 0) return {
|
|
548
|
+
content,
|
|
549
|
+
changed: false,
|
|
550
|
+
fields: [],
|
|
551
|
+
issues
|
|
552
|
+
};
|
|
553
|
+
if (!changed) return {
|
|
554
|
+
content,
|
|
555
|
+
changed: false,
|
|
556
|
+
fields: [],
|
|
557
|
+
issues
|
|
558
|
+
};
|
|
559
|
+
const rewrittenBlock = lines.slice(1, end).join("\n");
|
|
560
|
+
try {
|
|
561
|
+
const parsed = parse(rewrittenBlock);
|
|
562
|
+
for (const key of fields) if (String(parsed[key]) !== originalValues.get(key)) throw new Error(`rewritten value for ${key} differs from the original`);
|
|
563
|
+
return {
|
|
564
|
+
content: lines.join("\n"),
|
|
565
|
+
changed: true,
|
|
566
|
+
fields,
|
|
567
|
+
issues
|
|
568
|
+
};
|
|
569
|
+
} catch (error) {
|
|
570
|
+
return {
|
|
571
|
+
content,
|
|
572
|
+
changed: false,
|
|
573
|
+
fields: [],
|
|
574
|
+
issues: [`frontmatter rewrite verification failed (${error instanceof Error ? error.message : String(error)}) — quoting skipped; wrap this value manually`]
|
|
575
|
+
};
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
/**
|
|
579
|
+
* Skill names referenced by a SKILL.md's `related_skills` frontmatter
|
|
580
|
+
* (B-line G3, rc.44): the single parsing source for the quality references
|
|
581
|
+
* factor and the learning-graph edges. The DSH frontmatter parser keeps the
|
|
582
|
+
* YAML value as a string (`"[a, b]"`), so names are scanned out of it; each
|
|
583
|
+
* must satisfy the skill-name shape and the referencing skill itself is
|
|
584
|
+
* excluded. Pure and deduplicated.
|
|
585
|
+
*/
|
|
586
|
+
function relatedSkillNames(content, exclude) {
|
|
587
|
+
const parsed = parseFrontmatter(content);
|
|
588
|
+
if (!parsed) return [];
|
|
589
|
+
const nestedHost = parsed.metadata?.["hermes"];
|
|
590
|
+
const nestedRaw = isRecord(nestedHost) ? nestedHost["related_skills"] : void 0;
|
|
591
|
+
const flat = parsed.frontmatter["related_skills"];
|
|
592
|
+
const raw = typeof flat === "string" ? flat : Array.isArray(nestedRaw) ? `[${nestedRaw.map((item) => String(item)).join(", ")}]` : void 0;
|
|
593
|
+
if (typeof raw !== "string") return [];
|
|
594
|
+
const names = /* @__PURE__ */ new Set();
|
|
595
|
+
for (const match of Array.from(raw.matchAll(/(?<![A-Za-z0-9_-])[a-z0-9][a-z0-9-]*(?![A-Za-z0-9_-])/g))) {
|
|
596
|
+
const target = match[0];
|
|
597
|
+
if (target && SKILL_NAME_RE.test(target) && target !== exclude) names.add(target);
|
|
598
|
+
}
|
|
599
|
+
return [...names];
|
|
600
|
+
}
|
|
601
|
+
/** S1.2 (v37 P2-1): the content limit applies to the bytes that LAND ON DISK.
|
|
602
|
+
* Every write normalizes with `trimEnd() + '\n'`, so judging the raw argument let
|
|
603
|
+
* a 100_000-character body with no trailing newline land as 100_001 bytes — and
|
|
604
|
+
* every later patch/update of that skill was then refused, which made it
|
|
605
|
+
* unmaintainable through `skill_manage` with no repair path at all. */
|
|
606
|
+
/** The bytes that land on disk for a SKILL.md write — the ONE accounting basis
|
|
607
|
+
* shared by the content limit and the cost estimate (design §5.2). */
|
|
608
|
+
function skillMdOnDisk(content) {
|
|
609
|
+
return content.trimEnd() + "\n";
|
|
610
|
+
}
|
|
611
|
+
/** Whether `content` would exceed `limit` once written. */
|
|
612
|
+
function exceedsContentLimit(content, limit) {
|
|
613
|
+
return skillMdOnDisk(content).length > limit;
|
|
614
|
+
}
|
|
615
|
+
/** S1.2: the repair path — a write that makes an already-over-limit file smaller.
|
|
616
|
+
* Only a NET SHRINK is exempt; an equal or larger write stays refused. */
|
|
617
|
+
function shrinksOverLimit(next, current, limit) {
|
|
618
|
+
if (current === null || current === void 0 || !exceedsContentLimit(current, limit)) return false;
|
|
619
|
+
return skillMdOnDisk(next).length < skillMdOnDisk(current).length;
|
|
620
|
+
}
|
|
621
|
+
/**
|
|
622
|
+
* Synthesize a missing SKILL.md header at the write boundary.
|
|
623
|
+
*
|
|
624
|
+
* A model-authored create/update whose body starts with `# Title` is valid Markdown but the
|
|
625
|
+
* skill writer rejects it before any content check. Repair only the truly headerless shape: an
|
|
626
|
+
* existing fence is passed through byte-identical, even when it is malformed, so this helper
|
|
627
|
+
* cannot mask a header error that the validator should report. The caller owns the audit notice.
|
|
628
|
+
* @param content - the model-authored SKILL.md text.
|
|
629
|
+
* @param name - the validated skill name used for the `name:` field.
|
|
630
|
+
* @param description - optional description; otherwise derived from the first heading/prose.
|
|
631
|
+
* @returns the write text and whether a header was synthesized.
|
|
632
|
+
*/
|
|
633
|
+
function ensureSkillFrontmatter(content, name, description) {
|
|
634
|
+
if (frontmatterBlock(content) !== null || content.trimStart().startsWith("---")) return {
|
|
635
|
+
content,
|
|
636
|
+
repaired: false
|
|
637
|
+
};
|
|
638
|
+
const body = content.replace(/^\uFEFF/, "").replace(/^(?:[ \t]*\r?\n)+/, "");
|
|
639
|
+
const heading = /^#{1,6}\s+(.+?)\s*$/m.exec(body)?.[1];
|
|
640
|
+
const firstLine = body.split(/\r?\n/).map((line) => line.trim()).find((line) => line !== "" && !line.startsWith("#")) ?? "";
|
|
641
|
+
const source = (description?.trim() || heading || firstLine || name).replace(/\s+/g, " ").trim();
|
|
642
|
+
const clipped = source.length > 58 ? source.slice(0, 57) + "…" : source;
|
|
643
|
+
const summary = /[.。!?!?]$/.test(clipped) ? clipped : clipped + ".";
|
|
644
|
+
const encoded = yamlPlainScalarNeedsQuotes(summary) ? JSON.stringify(summary) : summary;
|
|
645
|
+
return {
|
|
646
|
+
content: [
|
|
647
|
+
"---",
|
|
648
|
+
`name: ${name}`,
|
|
649
|
+
`description: ${encoded}`,
|
|
650
|
+
"version: 0.1.0",
|
|
651
|
+
"author: Hermes",
|
|
652
|
+
"---",
|
|
653
|
+
""
|
|
654
|
+
].join("\n") + "\n" + body,
|
|
655
|
+
repaired: true
|
|
656
|
+
};
|
|
657
|
+
}
|
|
658
|
+
function validateFrontmatter(content, expectedName, limits = DEFAULT_SKILL_LIMITS, current) {
|
|
659
|
+
const parsed = parseFrontmatter(content);
|
|
660
|
+
if (!parsed) return "SKILL.md 必须以 `---` 行开头,用另一个完全相同的 `---` 行结束 frontmatter(只容忍结尾的 `\\r`),并在其下包含正文。";
|
|
661
|
+
const unreadable = parsed.platformStringSplit.filter((entry) => entry.kind === "sequence" || entry.kind === "mapping");
|
|
662
|
+
if (unreadable.length > 0) return `Frontmatter 字段 ${unreadable.map((entry) => `"${entry.key}" (a YAML ${entry.kind})`).join(", ")} 必须是字符串:平台技能目录会把这种字段当作缺失,并忽略整个文件。请写成纯文本,或用双引号包住取值以保持字面内容。`;
|
|
663
|
+
if (!parsed.frontmatter.name) return "Frontmatter 必须包含 name 字段。";
|
|
664
|
+
if (!SKILL_NAME_RE.test(parsed.frontmatter.name)) return `技能名「${parsed.frontmatter.name}」不合法:请只用小写字母、数字和连字符。`;
|
|
665
|
+
if (parsed.frontmatter.name.length > limits.maxNameLength) return `技能名超过 ${limits.maxNameLength} 个字符。`;
|
|
666
|
+
if (expectedName && parsed.frontmatter.name !== expectedName) return `Frontmatter 里的 name「${parsed.frontmatter.name}」与目标技能「${expectedName}」不一致。`;
|
|
667
|
+
if (!parsed.frontmatter.description) return "Frontmatter 必须包含 description 字段。";
|
|
668
|
+
if (parsed.frontmatter.description.length > limits.maxDescriptionLength) return `description 超过 ${limits.maxDescriptionLength} 个字符。`;
|
|
669
|
+
if (exceedsContentLimit(content, limits.maxSkillContentChars) && !shrinksOverLimit(content, current, limits.maxSkillContentChars)) return `SKILL.md 内容超过 ${limits.maxSkillContentChars} 个字符。${CONTENT_SPLIT_HINT}`;
|
|
670
|
+
return null;
|
|
671
|
+
}
|
|
672
|
+
/**
|
|
673
|
+
* Advisory authoring feedback (P0): evaluate frontmatter against the
|
|
674
|
+
* authoring bar WITHOUT changing platform validation semantics. The bar is
|
|
675
|
+
* the quality target, `validateFrontmatter`'s limits are the compatibility
|
|
676
|
+
* floor, and this bridge layer tells the model when its text would be
|
|
677
|
+
* truncated or route-poor instead of silently shipping it.
|
|
678
|
+
*/
|
|
679
|
+
function authoringFeedback(frontmatter) {
|
|
680
|
+
const description = frontmatter.description ?? "";
|
|
681
|
+
const over60 = description.length > 60;
|
|
682
|
+
const hasColon = description.includes(":");
|
|
683
|
+
const lines = [];
|
|
684
|
+
lines.push(over60 ? `描述为 ${description.length}/60 个字符 —— 超过 60 字符的作者规范上限(Hermes 标准;技能目录会按平台配置的上限截断)。` : `描述为 ${description.length}/60 个字符 —— 在作者规范上限之内。`);
|
|
685
|
+
if (hasColon) lines.push("描述里含冒号 —— 请用双引号把整个取值包起来。");
|
|
686
|
+
return {
|
|
687
|
+
descriptionChars: description.length,
|
|
688
|
+
over60,
|
|
689
|
+
hasColon,
|
|
690
|
+
lines
|
|
691
|
+
};
|
|
692
|
+
}
|
|
693
|
+
/** A1-15 (v18) / P2-2 (v19): the io layer marks an error `committed: true` when
|
|
694
|
+
* the rename landed and only the directory fsync failed. Every single-file
|
|
695
|
+
* writer must treat that as "written, durability unconfirmed" — never as a
|
|
696
|
+
* plain failure (which a caller would retry, or a two-phase caller roll back).
|
|
697
|
+
* v28 G2.1 (EVO-IO-05): this is a delegation to the seam's own
|
|
698
|
+
* `isCommittedWarning` — the marker predicate has exactly one definition. */
|
|
699
|
+
//#endregion
|
|
700
|
+
//#region lib/types/document-body.js
|
|
701
|
+
/**
|
|
702
|
+
* What the panel shows when it renders one version as a document.
|
|
703
|
+
*
|
|
704
|
+
* Two decisions, both made here so the preview and the rendered diff cannot drift apart:
|
|
705
|
+
*
|
|
706
|
+
* - FRONTMATTER IS NOT DOCUMENT TEXT. A SKILL.md opens with a YAML block; the renderer read its
|
|
707
|
+
* closing `---` as a setext underline, so the metadata line became the document's biggest heading
|
|
708
|
+
* and the real title sat below it (measured on the installed panel 2026-09-28). The block is
|
|
709
|
+
* stripped for DISPLAY only: the raw view and the body route still carry every byte, and the
|
|
710
|
+
* panel already shows the name and description on the row and in the left column.
|
|
711
|
+
* - STRIPPING FAILS OPEN. Only a block that the family's own reader accepts is removed. A document
|
|
712
|
+
* whose text merely starts with a thematic break, a block with no closing line, or a frontmatter
|
|
713
|
+
* whose body is empty is returned UNCHANGED — showing a document's first line is always better
|
|
714
|
+
* than showing nothing.
|
|
715
|
+
*
|
|
716
|
+
* `readingStats` exists for the other half of the reader's honesty: a preview that stops early has
|
|
717
|
+
* to be able to say HOW much it is not showing.
|
|
718
|
+
* @module @lmzhen/dsh-evolution-core/document-body
|
|
719
|
+
*/
|
|
720
|
+
/**
|
|
721
|
+
* The document a reader sees: the body without its leading frontmatter block.
|
|
722
|
+
* @param content - the stored bytes of one version.
|
|
723
|
+
* @returns the text to render; unchanged when there is no frontmatter the reader accepts.
|
|
724
|
+
*/
|
|
725
|
+
function displayBodyOf(content) {
|
|
726
|
+
const block = frontmatterBlock(content);
|
|
727
|
+
if (block === null) return content;
|
|
728
|
+
if (parseFrontmatter(content) === null) return content;
|
|
729
|
+
return block.lines.slice(block.end + 1).join("\n").replace(/^\s*\n/, "");
|
|
730
|
+
}
|
|
731
|
+
/**
|
|
732
|
+
* How much of a version the panel is showing.
|
|
733
|
+
* @param full - the whole stored text.
|
|
734
|
+
* @param shown - the part the route handed over.
|
|
735
|
+
* @returns the counts, so the panel can say what it is not showing.
|
|
736
|
+
*/
|
|
737
|
+
function readingStats(full, shown) {
|
|
738
|
+
return {
|
|
739
|
+
totalChars: full.length,
|
|
740
|
+
shownChars: shown.length,
|
|
741
|
+
truncated: shown.length < full.length
|
|
742
|
+
};
|
|
743
|
+
}
|
|
744
|
+
/**
|
|
745
|
+
* The H2 sections of a body, in document order — the ONE scan (G3).
|
|
746
|
+
*
|
|
747
|
+
* Both the restructure candidate list and the store anchor validation call this function, so a
|
|
748
|
+
* candidate can only name a heading that exists EXACTLY ONCE and has content: the two rejections a
|
|
749
|
+
* hand-written anchor used to hit ("no such heading", "ambiguous anchor") stop being reachable.
|
|
750
|
+
* H2 is the section boundary (a section spans to the next H2 or EOF), matching the store.
|
|
751
|
+
* @param body - the markdown after the frontmatter block.
|
|
752
|
+
* @returns one row per H2 heading, with `count` filled in a second pass.
|
|
753
|
+
*/
|
|
754
|
+
function h2Sections(body) {
|
|
755
|
+
const lines = body.split(String.fromCharCode(10));
|
|
756
|
+
const rows = [];
|
|
757
|
+
for (let i = 0; i < lines.length; i += 1) {
|
|
758
|
+
const match = /^#{2}\s+(.+?)\s*$/.exec(lines[i] ?? "");
|
|
759
|
+
if (match === null) continue;
|
|
760
|
+
const title = (match[1] ?? "").trim();
|
|
761
|
+
let end = lines.length;
|
|
762
|
+
for (let j = i + 1; j < lines.length; j += 1) if (/^#{2}\s/.test(lines[j] ?? "")) {
|
|
763
|
+
end = j;
|
|
764
|
+
break;
|
|
765
|
+
}
|
|
766
|
+
rows.push({
|
|
767
|
+
title,
|
|
768
|
+
start: i,
|
|
769
|
+
end,
|
|
770
|
+
count: 0
|
|
771
|
+
});
|
|
772
|
+
}
|
|
773
|
+
for (const row of rows) row.count = rows.filter((other) => other.title === row.title).length;
|
|
774
|
+
return rows;
|
|
775
|
+
}
|
|
776
|
+
//#endregion
|
|
777
|
+
//#region lib/types/section-selection.js
|
|
778
|
+
const LF = String.fromCharCode(10);
|
|
779
|
+
/**
|
|
780
|
+
* Select whole H2 sections or exact content sub-blocks from one body.
|
|
781
|
+
*
|
|
782
|
+
* The H2 scan is document-body's h2Sections, so restructure and extract share
|
|
783
|
+
* one boundary rule. A start/end pair selects an inclusive, contiguous run of
|
|
784
|
+
* exact lines inside that heading; it cannot select the heading itself, overlap
|
|
785
|
+
* another request, or leave a selected range empty.
|
|
786
|
+
* @param body - markdown after frontmatter.
|
|
787
|
+
* @param requests - exact heading plus optional start/end line pairs.
|
|
788
|
+
* @returns selected ranges in request order, or the first refusal.
|
|
789
|
+
*/
|
|
790
|
+
function selectSections(body, requests) {
|
|
791
|
+
const lines = body.split(LF);
|
|
792
|
+
const sections = h2Sections(body);
|
|
793
|
+
const selected = [];
|
|
794
|
+
for (let requestIndex = 0; requestIndex < requests.length; requestIndex += 1) {
|
|
795
|
+
const request = requests[requestIndex];
|
|
796
|
+
if (request === void 0) continue;
|
|
797
|
+
const wanted = request.heading.trim();
|
|
798
|
+
const matching = sections.filter((section) => section.title === wanted);
|
|
799
|
+
if (matching.length === 0) return {
|
|
800
|
+
ok: false,
|
|
801
|
+
code: "heading-missing",
|
|
802
|
+
message: "no \"## " + wanted + "\" heading in the body"
|
|
803
|
+
};
|
|
804
|
+
if (matching.length > 1) return {
|
|
805
|
+
ok: false,
|
|
806
|
+
code: "heading-ambiguous",
|
|
807
|
+
message: "heading \"## " + wanted + "\" appears " + matching.length + " times (ambiguous anchor)"
|
|
808
|
+
};
|
|
809
|
+
const section = matching[0];
|
|
810
|
+
if (section === void 0) return {
|
|
811
|
+
ok: false,
|
|
812
|
+
code: "heading-missing",
|
|
813
|
+
message: "no \"## " + wanted + "\" heading in the body"
|
|
814
|
+
};
|
|
815
|
+
if (selected.some((entry) => entry.start === section.start)) return {
|
|
816
|
+
ok: false,
|
|
817
|
+
code: "heading-duplicate",
|
|
818
|
+
message: "heading \"## " + wanted + "\" is moved twice"
|
|
819
|
+
};
|
|
820
|
+
if (!(request.start !== void 0 || request.end !== void 0)) {
|
|
821
|
+
if (section.end === section.start + 1) return {
|
|
822
|
+
ok: false,
|
|
823
|
+
code: "heading-empty",
|
|
824
|
+
message: "heading \"## " + wanted + "\" has an empty section"
|
|
825
|
+
};
|
|
826
|
+
selected.push({
|
|
827
|
+
heading: wanted,
|
|
828
|
+
start: section.start,
|
|
829
|
+
end: section.end,
|
|
830
|
+
text: lines.slice(section.start, section.end).join(LF),
|
|
831
|
+
requestIndex
|
|
832
|
+
});
|
|
833
|
+
continue;
|
|
834
|
+
}
|
|
835
|
+
if (request.start === void 0 || request.end === void 0) return {
|
|
836
|
+
ok: false,
|
|
837
|
+
code: "part-anchor-incomplete",
|
|
838
|
+
message: "heading \"## " + wanted + "\" needs both start and end anchors"
|
|
839
|
+
};
|
|
840
|
+
const startMatches = [];
|
|
841
|
+
const endMatches = [];
|
|
842
|
+
for (let index = 0; index < lines.length; index += 1) {
|
|
843
|
+
if (index <= section.start || index >= section.end) continue;
|
|
844
|
+
if (lines[index] === request.start) startMatches.push(index);
|
|
845
|
+
if (lines[index] === request.end) endMatches.push(index);
|
|
846
|
+
}
|
|
847
|
+
if (startMatches.length !== 1) return {
|
|
848
|
+
ok: false,
|
|
849
|
+
code: "part-anchor-not-found",
|
|
850
|
+
message: "heading \"## " + wanted + "\" start anchor must match exactly one content line"
|
|
851
|
+
};
|
|
852
|
+
if (endMatches.length !== 1) return {
|
|
853
|
+
ok: false,
|
|
854
|
+
code: "part-anchor-not-found",
|
|
855
|
+
message: "heading \"## " + wanted + "\" end anchor must match exactly one content line"
|
|
856
|
+
};
|
|
857
|
+
const start = startMatches[0];
|
|
858
|
+
const end = endMatches[0];
|
|
859
|
+
if (start === void 0 || end === void 0 || start > end) return {
|
|
860
|
+
ok: false,
|
|
861
|
+
code: "part-anchor-order",
|
|
862
|
+
message: "heading \"## " + wanted + "\" start anchor is after end anchor"
|
|
863
|
+
};
|
|
864
|
+
if (selected.some((entry) => start < entry.end && end + 1 > entry.start)) return {
|
|
865
|
+
ok: false,
|
|
866
|
+
code: "part-anchor-overlaps",
|
|
867
|
+
message: "heading \"## " + wanted + "\" selection overlaps another selected block"
|
|
868
|
+
};
|
|
869
|
+
selected.push({
|
|
870
|
+
heading: wanted,
|
|
871
|
+
start,
|
|
872
|
+
end: end + 1,
|
|
873
|
+
text: lines.slice(start, end + 1).join(LF),
|
|
874
|
+
requestIndex,
|
|
875
|
+
anchorStart: request.start,
|
|
876
|
+
anchorEnd: request.end
|
|
877
|
+
});
|
|
878
|
+
}
|
|
879
|
+
return {
|
|
880
|
+
ok: true,
|
|
881
|
+
sections: selected
|
|
882
|
+
};
|
|
883
|
+
}
|
|
884
|
+
//#endregion
|
|
885
|
+
//#region lib/types/usage.js
|
|
886
|
+
/**
|
|
887
|
+
* Skill usage telemetry sidecar: `$DSH_HOME/skills/.usage.json`.
|
|
888
|
+
* Format-compatible with Hermes Agent / hermes-claw core fields.
|
|
889
|
+
*/
|
|
890
|
+
function usageFile(root) {
|
|
891
|
+
return join(root, ".usage.json");
|
|
892
|
+
}
|
|
893
|
+
function emptyRecord() {
|
|
894
|
+
return {
|
|
895
|
+
created_by: null,
|
|
896
|
+
use_count: 0,
|
|
897
|
+
view_count: 0,
|
|
898
|
+
patch_count: 0,
|
|
899
|
+
last_used_at: null,
|
|
900
|
+
last_viewed_at: null,
|
|
901
|
+
last_patched_at: null,
|
|
902
|
+
created_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
903
|
+
state: "active",
|
|
904
|
+
pinned: false,
|
|
905
|
+
archived_at: null
|
|
906
|
+
};
|
|
907
|
+
}
|
|
908
|
+
/** A timestamp passes only when `Date.parse` yields a finite epoch (N-3): a bare
|
|
909
|
+
* string check let garbage like "not-a-date" propagate as Invalid Date → NaN
|
|
910
|
+
* into quality math and lifecycle comparisons. */
|
|
911
|
+
const validTimestamp = (value) => typeof value === "string" && Number.isFinite(Date.parse(value));
|
|
912
|
+
const nullableTimestamp = (value) => value === null || validTimestamp(value);
|
|
913
|
+
/**
|
|
914
|
+
* Field-level normalization for one sidecar record (rc.42 audit P2-3): the
|
|
915
|
+
* spread used to copy any junk through verbatim, so a corrupted file could
|
|
916
|
+
* carry `use_count: "3"` into the quality math and lifecycle comparisons as
|
|
917
|
+
* NaN. Every field falls back to its `emptyRecord()` baseline unless it has
|
|
918
|
+
* exactly the declared type; an invalid `created_at` anchors the age clock at
|
|
919
|
+
* now (first-sight defer semantics for a record whose age is unknowable).
|
|
920
|
+
* Timestamps additionally require a parseable date (N-3): `"not-a-date"`
|
|
921
|
+
* would otherwise survive the type check as Invalid Date.
|
|
922
|
+
* Pure — exported for unit tests; `loadUsage` is the production caller.
|
|
923
|
+
*/
|
|
924
|
+
function normalizeUsageRecord(record) {
|
|
925
|
+
const base = emptyRecord();
|
|
926
|
+
if (!record || typeof record !== "object" || Array.isArray(record)) return base;
|
|
927
|
+
const raw = record;
|
|
928
|
+
const num = (value, fallback) => typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : fallback;
|
|
929
|
+
const bool = (value, fallback) => typeof value === "boolean" ? value : fallback;
|
|
930
|
+
return {
|
|
931
|
+
...raw,
|
|
932
|
+
created_by: typeof raw.created_by === "string" ? raw.created_by : null,
|
|
933
|
+
use_count: num(raw.use_count, base.use_count),
|
|
934
|
+
view_count: num(raw.view_count, base.view_count),
|
|
935
|
+
patch_count: num(raw.patch_count, base.patch_count),
|
|
936
|
+
last_used_at: nullableTimestamp(raw.last_used_at) ? raw.last_used_at : base.last_used_at,
|
|
937
|
+
last_viewed_at: nullableTimestamp(raw.last_viewed_at) ? raw.last_viewed_at : base.last_viewed_at,
|
|
938
|
+
last_patched_at: nullableTimestamp(raw.last_patched_at) ? raw.last_patched_at : base.last_patched_at,
|
|
939
|
+
created_at: validTimestamp(raw.created_at) ? raw.created_at : base.created_at,
|
|
940
|
+
state: raw.state === "stale" || raw.state === "archived" ? raw.state : "active",
|
|
941
|
+
pinned: bool(raw.pinned, base.pinned),
|
|
942
|
+
archived_at: nullableTimestamp(raw.archived_at) ? raw.archived_at : base.archived_at,
|
|
943
|
+
quality_score: typeof raw.quality_score === "number" && Number.isFinite(raw.quality_score) ? raw.quality_score : void 0,
|
|
944
|
+
quality_warn: typeof raw.quality_warn === "boolean" ? raw.quality_warn : void 0,
|
|
945
|
+
feedback_score: typeof raw.feedback_score === "number" && Number.isFinite(raw.feedback_score) ? raw.feedback_score : void 0,
|
|
946
|
+
feedback_warn: typeof raw.feedback_warn === "boolean" ? raw.feedback_warn : void 0,
|
|
947
|
+
support_reads: normalizeSupportReads(raw.support_reads)
|
|
948
|
+
};
|
|
949
|
+
}
|
|
950
|
+
/** Sidecar bound: a pathological path set must not grow the usage file forever. */
|
|
951
|
+
const MAX_SUPPORT_READ_PATHS = 200;
|
|
952
|
+
/** Sanitize the per-support-file read counts: non-negative finite numbers under
|
|
953
|
+
* non-empty, bounded, non-traversal path keys. An unusable value drops the whole
|
|
954
|
+
* map (absence over a poisoned count). */
|
|
955
|
+
function normalizeSupportReads(value) {
|
|
956
|
+
if (value === null || typeof value !== "object" || Array.isArray(value)) return void 0;
|
|
957
|
+
const out = {};
|
|
958
|
+
let kept = 0;
|
|
959
|
+
for (const [key, count] of Object.entries(value)) {
|
|
960
|
+
if (kept >= 200) break;
|
|
961
|
+
if (key === "" || key.length > 200 || key.split("/").includes("..")) continue;
|
|
962
|
+
if (typeof count !== "number" || !Number.isFinite(count) || count < 0) continue;
|
|
963
|
+
out[key] = count;
|
|
964
|
+
kept += 1;
|
|
965
|
+
}
|
|
966
|
+
return kept === 0 ? void 0 : out;
|
|
967
|
+
}
|
|
968
|
+
/** Parse a raw usage sidecar; malformed content reads as empty (best-effort telemetry). */
|
|
969
|
+
function parseUsage(raw) {
|
|
970
|
+
const map = /* @__PURE__ */ new Map();
|
|
971
|
+
if (raw === null) return map;
|
|
972
|
+
try {
|
|
973
|
+
const parsed = JSON.parse(raw);
|
|
974
|
+
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return map;
|
|
975
|
+
for (const [name, record] of Object.entries(parsed)) map.set(name, normalizeUsageRecord(record));
|
|
976
|
+
} catch {}
|
|
977
|
+
return map;
|
|
978
|
+
}
|
|
979
|
+
async function loadUsage(root, io = nodeEvolutionIo()) {
|
|
980
|
+
return parseUsage(await io.readText(usageFile(root)));
|
|
981
|
+
}
|
|
982
|
+
async function mutateUsage(root, io, task, options = {}) {
|
|
983
|
+
const run = async () => {
|
|
984
|
+
await transactIo(io, usageFile(root), async (current) => {
|
|
985
|
+
let shapePreserved = false;
|
|
986
|
+
let recovered = null;
|
|
987
|
+
const quarantineCopy = async () => {
|
|
988
|
+
const corruptPath = `${usageFile(root)}.corrupt`;
|
|
989
|
+
return io.writeText(corruptPath, current).then(() => true, () => false);
|
|
990
|
+
};
|
|
991
|
+
if (current !== null) {
|
|
992
|
+
let parsed = null;
|
|
993
|
+
try {
|
|
994
|
+
const probe = JSON.parse(current);
|
|
995
|
+
if (isRecord(probe)) parsed = probe;
|
|
996
|
+
} catch {
|
|
997
|
+
parsed = null;
|
|
998
|
+
}
|
|
999
|
+
if (parsed === null) {
|
|
1000
|
+
if (!await quarantineCopy()) {
|
|
1001
|
+
options.onQuarantine?.(`usage sidecar ${usageFile(root)} is unreadable; the .corrupt copy could not be written — refusing this write so the original bytes stay recoverable (telemetry is frozen until the file is recovered manually)`);
|
|
1002
|
+
return current;
|
|
1003
|
+
}
|
|
1004
|
+
options.onQuarantine?.(`usage sidecar ${usageFile(root)} is unreadable (unparsable JSON or wrong top-level shape); the original bytes were copied to ${usageFile(root)}.corrupt and the sidecar restarts empty`);
|
|
1005
|
+
} else {
|
|
1006
|
+
const record = parsed;
|
|
1007
|
+
const isMalformed = (value) => value === null || typeof value !== "object" || Array.isArray(value);
|
|
1008
|
+
if (typeof record.version === "number" && record.version > 1) {
|
|
1009
|
+
const message = `usage sidecar ${usageFile(root)} carries schema version ${String(record.version)} (> this runtime) — writes stay frozen and the bytes preserved until the runtime is upgraded`;
|
|
1010
|
+
if (options.onQuarantine !== void 0) options.onQuarantine(message);
|
|
1011
|
+
else console.warn(message);
|
|
1012
|
+
shapePreserved = true;
|
|
1013
|
+
} else if (Object.values(record).some(isMalformed)) {
|
|
1014
|
+
const bad = Object.keys(record).filter((key) => isMalformed(record[key]));
|
|
1015
|
+
if (!await quarantineCopy()) {
|
|
1016
|
+
options.onQuarantine?.(`usage sidecar ${usageFile(root)} carried ${bad.length} malformed entr${bad.length === 1 ? "y" : "ies"} (${bad.slice(0, 5).join(", ")}); the .corrupt copy could not be written — refusing this write so the original bytes stay recoverable`);
|
|
1017
|
+
return current;
|
|
1018
|
+
}
|
|
1019
|
+
recovered = JSON.stringify(Object.fromEntries(Object.entries(record).filter(([, value]) => !isMalformed(value))));
|
|
1020
|
+
options.onQuarantine?.(`usage sidecar ${usageFile(root)} carried ${bad.length} malformed entr${bad.length === 1 ? "y" : "ies"} (${bad.slice(0, 5).join(", ")}); the original bytes were copied to ${usageFile(root)}.corrupt and the remaining entries continue to be served`);
|
|
1021
|
+
}
|
|
1022
|
+
}
|
|
1023
|
+
}
|
|
1024
|
+
if (shapePreserved) return current;
|
|
1025
|
+
const map = parseUsage(recovered ?? current);
|
|
1026
|
+
await task(map);
|
|
1027
|
+
return JSON.stringify(Object.fromEntries(map.entries()), null, 2);
|
|
1028
|
+
});
|
|
1029
|
+
};
|
|
1030
|
+
if (options.fence !== void 0) await options.fence.run(run);
|
|
1031
|
+
else await run();
|
|
1032
|
+
}
|
|
1033
|
+
/** Curator-owned usage fields (rc.67 K-2): the curator writes ONLY this set —
|
|
1034
|
+
* lifecycle state, archive stamp, the six-factor quality pair, and the
|
|
1035
|
+
* marker-mirrored pin flag; counters and activity stamps belong to the
|
|
1036
|
+
* tool-telemetry side and are never copied by a fold. P2-12 (v39): the
|
|
1037
|
+
* combined `applyCuratorFields` wrapper had no production caller (folds go
|
|
1038
|
+
* through {@link foldCuratorFields}), so the two field copies below are the
|
|
1039
|
+
* whole contract. */
|
|
1040
|
+
/** Copy only the lifecycle pair (state/archived_at) — see the ownership split
|
|
1041
|
+
* rationale above. */
|
|
1042
|
+
function applyCuratorLifecycleFields(disk, curated) {
|
|
1043
|
+
disk.state = curated.state;
|
|
1044
|
+
disk.archived_at = curated.archived_at;
|
|
1045
|
+
}
|
|
1046
|
+
/**
|
|
1047
|
+
* Copy the recomputed meta pair (quality_score/quality_warn + the
|
|
1048
|
+
* marker-mirrored pin flag) — refreshed tree-wide each run by design, so a
|
|
1049
|
+
* concurrent curator run's lifecycle changes are never reverted by them.
|
|
1050
|
+
* P1-1 (v15): the feedback pair (`feedback_score`/`feedback_warn`) is
|
|
1051
|
+
* deliberately NOT copied — it is feedback-owned (see the field-ownership
|
|
1052
|
+
* contract on {@link UsageRecord}) and must survive curator runs untouched.
|
|
1053
|
+
*/
|
|
1054
|
+
function applyCuratorMetaFields(disk, curated) {
|
|
1055
|
+
disk.quality_score = curated.quality_score;
|
|
1056
|
+
disk.quality_warn = curated.quality_warn;
|
|
1057
|
+
disk.pinned = curated.pinned;
|
|
1058
|
+
}
|
|
1059
|
+
/**
|
|
1060
|
+
* Fold a curator run-start snapshot onto the current on-disk map (rc.67 K-2):
|
|
1061
|
+
* each curated record is projected onto its disk peer by copying only the
|
|
1062
|
+
* curator-owned fields, so a concurrent tool-side bump between snapshot and
|
|
1063
|
+
* save survives. Records absent from the snapshot are left untouched; a
|
|
1064
|
+
* curated record with no disk peer is seeded from the snapshot. `stateOwned`
|
|
1065
|
+
* (rc.72 H-1) restricts the lifecycle pair to the names this run ACTUALLY
|
|
1066
|
+
* transitioned — a concurrent curator run's archive/restore is never reverted
|
|
1067
|
+
* by a stale snapshot; without it both pairs apply everywhere.
|
|
1068
|
+
*/
|
|
1069
|
+
function foldCuratorFields(disk, curated, stateOwned, runStartStates) {
|
|
1070
|
+
const skipped = [];
|
|
1071
|
+
for (const [name, record] of curated) {
|
|
1072
|
+
const diskRecord = disk.get(name);
|
|
1073
|
+
if (!diskRecord) {
|
|
1074
|
+
disk.set(name, { ...record });
|
|
1075
|
+
continue;
|
|
1076
|
+
}
|
|
1077
|
+
applyCuratorMetaFields(diskRecord, record);
|
|
1078
|
+
if (stateOwned === void 0 || stateOwned.has(name)) {
|
|
1079
|
+
const expected = runStartStates?.get(name);
|
|
1080
|
+
if (expected !== void 0 && diskRecord.state !== expected) {
|
|
1081
|
+
skipped.push(name);
|
|
1082
|
+
continue;
|
|
1083
|
+
}
|
|
1084
|
+
applyCuratorLifecycleFields(diskRecord, record);
|
|
1085
|
+
}
|
|
1086
|
+
}
|
|
1087
|
+
return skipped;
|
|
1088
|
+
}
|
|
1089
|
+
/** Whole-file usage write (V6-37, 0.3.37): this is the ONE path that bypasses
|
|
1090
|
+
* the malformed-defense and the transact lock — prefer `mutateUsage` for any
|
|
1091
|
+
* read-modify-write so a concurrent writer cannot lose its update and a
|
|
1092
|
+
* malformed sidecar stays recoverable. Kept for fixture/test seeding.
|
|
1093
|
+
* @internal P3-16 (v14): no production caller (verified by grep); exported for
|
|
1094
|
+
* the family's tests only. Do not use it to write the sidecar in new code. */
|
|
1095
|
+
async function saveUsage(root, map, io = nodeEvolutionIo()) {
|
|
1096
|
+
const obj = Object.fromEntries(map.entries());
|
|
1097
|
+
await io.writeText(usageFile(root), JSON.stringify(obj, null, 2));
|
|
1098
|
+
}
|
|
1099
|
+
function getRecord(map, name) {
|
|
1100
|
+
let record = map.get(name);
|
|
1101
|
+
if (!record) {
|
|
1102
|
+
record = emptyRecord();
|
|
1103
|
+
map.set(name, record);
|
|
1104
|
+
}
|
|
1105
|
+
return record;
|
|
1106
|
+
}
|
|
1107
|
+
function bumpView(map, name, when = /* @__PURE__ */ new Date()) {
|
|
1108
|
+
const record = getRecord(map, name);
|
|
1109
|
+
record.view_count += 1;
|
|
1110
|
+
record.last_viewed_at = when.toISOString();
|
|
1111
|
+
}
|
|
1112
|
+
function bumpUse(map, name, when = /* @__PURE__ */ new Date()) {
|
|
1113
|
+
const record = getRecord(map, name);
|
|
1114
|
+
record.use_count += 1;
|
|
1115
|
+
record.last_used_at = when.toISOString();
|
|
1116
|
+
}
|
|
1117
|
+
function bumpPatch(map, name, when = /* @__PURE__ */ new Date()) {
|
|
1118
|
+
const record = getRecord(map, name);
|
|
1119
|
+
record.patch_count += 1;
|
|
1120
|
+
record.last_patched_at = when.toISOString();
|
|
1121
|
+
}
|
|
1122
|
+
/** Count one observed support-file read (design §5.5). The map is created on
|
|
1123
|
+
* first evidence only — a skill with no support reads keeps the field absent. */
|
|
1124
|
+
function bumpSupportRead(map, name, rel, when = /* @__PURE__ */ new Date()) {
|
|
1125
|
+
const record = getRecord(map, name);
|
|
1126
|
+
const counts = record.support_reads ?? {};
|
|
1127
|
+
counts[rel] = (counts[rel] ?? 0) + 1;
|
|
1128
|
+
record.support_reads = counts;
|
|
1129
|
+
record.last_viewed_at = when.toISOString();
|
|
1130
|
+
}
|
|
1131
|
+
function markAgentCreated(map, name) {
|
|
1132
|
+
getRecord(map, name).created_by = "agent";
|
|
1133
|
+
}
|
|
1134
|
+
function latestActivityAt(record) {
|
|
1135
|
+
const values = [
|
|
1136
|
+
record.last_used_at,
|
|
1137
|
+
record.last_viewed_at,
|
|
1138
|
+
record.last_patched_at
|
|
1139
|
+
].filter((value) => typeof value === "string" && Number.isFinite(Date.parse(value)));
|
|
1140
|
+
if (values.length === 0) return null;
|
|
1141
|
+
return values.reduce((latest, value) => Date.parse(value) > Date.parse(latest) ? value : latest);
|
|
1142
|
+
}
|
|
1143
|
+
/** Days between an ISO timestamp (falling back to `created`) and `now`. An
|
|
1144
|
+
* unparseable date counts as 0 days: NaN silently froze every age comparison
|
|
1145
|
+
* (A2-9). */
|
|
1146
|
+
function daysSinceIso(iso, created, nowMs) {
|
|
1147
|
+
const t = Date.parse(iso ?? created);
|
|
1148
|
+
if (!Number.isFinite(t)) return 0;
|
|
1149
|
+
return (nowMs - t) / 864e5;
|
|
1150
|
+
}
|
|
1151
|
+
/** Idle days of one skill since its lifecycle age anchor (`last activity ??
|
|
1152
|
+
* created_at`) — the SAME anchor the curator's transitions use, so the
|
|
1153
|
+
* maintenance view and the lifecycle can never disagree about staleness. */
|
|
1154
|
+
function idleDays(record, now = /* @__PURE__ */ new Date()) {
|
|
1155
|
+
return daysSinceIso(latestActivityAt(record), record.created_at, now.getTime());
|
|
1156
|
+
}
|
|
1157
|
+
/**
|
|
1158
|
+
* Whether the library has ANY observed read evidence (C observation window):
|
|
1159
|
+
* reads were invisible to the usage sidecar before A2, so `view_count` zero
|
|
1160
|
+
* means "never read" ONLY after the first observed read exists anywhere in
|
|
1161
|
+
* the map. Before that, churn-based signals (write-ghost) are untrustworthy
|
|
1162
|
+
* and callers must suppress them. Pure and derived — never persisted.
|
|
1163
|
+
*/
|
|
1164
|
+
function usageObserved(usage) {
|
|
1165
|
+
for (const record of usage.values()) if (record.view_count > 0) return true;
|
|
1166
|
+
return false;
|
|
1167
|
+
}
|
|
1168
|
+
/**
|
|
1169
|
+
* Curator suppression sidecar: built-in skills the curator has archived stay
|
|
1170
|
+
* suppressed across re-seeds, so the lifecycle never fights a re-created
|
|
1171
|
+
* bundled skill. Best-effort load/save, mirroring the usage sidecar posture.
|
|
1172
|
+
* Versioned shape ({ version, names }) with legacy plain-array compat.
|
|
1173
|
+
*/
|
|
1174
|
+
const SUPPRESSED_FILE_VERSION = 1;
|
|
1175
|
+
function suppressedFile(root) {
|
|
1176
|
+
return join(root, ".curator-suppressed.json");
|
|
1177
|
+
}
|
|
1178
|
+
async function loadSuppressedNames(root, io = nodeEvolutionIo()) {
|
|
1179
|
+
return parseSuppressed(await io.readText(suppressedFile(root)));
|
|
1180
|
+
}
|
|
1181
|
+
function parseSuppressed(raw) {
|
|
1182
|
+
if (raw === null) return /* @__PURE__ */ new Set();
|
|
1183
|
+
try {
|
|
1184
|
+
const parsed = JSON.parse(raw);
|
|
1185
|
+
const names = Array.isArray(parsed) ? parsed : typeof parsed === "object" && parsed !== null && Array.isArray(parsed.names) ? parsed.names : [];
|
|
1186
|
+
return new Set(names.filter((entry) => typeof entry === "string"));
|
|
1187
|
+
} catch {
|
|
1188
|
+
return /* @__PURE__ */ new Set();
|
|
1189
|
+
}
|
|
1190
|
+
}
|
|
1191
|
+
/**
|
|
1192
|
+
* Plain wholesale write of the suppression sidecar (tests and fixture seeding).
|
|
1193
|
+
* @internal S2.4 (PLAN 2026-09-16, audit P2-31): NO production consumer
|
|
1194
|
+
* (verified by grep; production suppressions go through
|
|
1195
|
+
* {@link updateSuppressedNames}) — exported for the family's tests only. Do
|
|
1196
|
+
* not use it to write the sidecar in new code.
|
|
1197
|
+
*
|
|
1198
|
+
* The write rides the {@link transactIo} channel (the same lock the RMW
|
|
1199
|
+
* writer uses), not the former naked read → `io.writeText`: that form was an
|
|
1200
|
+
* unserialized read-modify-write — the last `saveSuppressedNames` in this file
|
|
1201
|
+
* with no lock, while its sibling `saveUsage` already carried the `@internal`
|
|
1202
|
+
* test-only note. Version discipline is unchanged (V24-09 / S2-14): a read
|
|
1203
|
+
* failure surfaces (an unreadable sidecar is never written over), a newer
|
|
1204
|
+
* on-disk schema is warned about and preserved byte-for-byte (the
|
|
1205
|
+
* byte-identical result short-circuits the write), and a malformed sidecar is
|
|
1206
|
+
* still overwritten with the v1 shape (the historical plain-writer posture).
|
|
1207
|
+
*/
|
|
1208
|
+
async function saveSuppressedNames(root, names, io = nodeEvolutionIo()) {
|
|
1209
|
+
await transactIo(io, suppressedFile(root), (current) => {
|
|
1210
|
+
if (current !== null) try {
|
|
1211
|
+
const parsed = JSON.parse(current);
|
|
1212
|
+
if (parsed !== null && typeof parsed.version === "number" && parsed.version > 1) {
|
|
1213
|
+
console.warn(`suppression sidecar ${suppressedFile(root)} declares version ${String(parsed.version)} (newer than 1); not overwritten`);
|
|
1214
|
+
return current;
|
|
1215
|
+
}
|
|
1216
|
+
} catch {}
|
|
1217
|
+
return JSON.stringify({
|
|
1218
|
+
version: 1,
|
|
1219
|
+
names: [...names].sort()
|
|
1220
|
+
}, null, 2);
|
|
1221
|
+
});
|
|
1222
|
+
}
|
|
1223
|
+
/**
|
|
1224
|
+
* Atomic read-modify-write on the suppression sidecar (rc.50 P2-2): `task`
|
|
1225
|
+
* receives the set parsed from the current on-disk state and may mutate it;
|
|
1226
|
+
* the result is persisted inside the same transact so a second process
|
|
1227
|
+
* sharing DSH_HOME cannot interleave its RMW. Best-effort posture unchanged.
|
|
1228
|
+
*/
|
|
1229
|
+
async function updateSuppressedNames(root, io, task) {
|
|
1230
|
+
await transactIo(io, suppressedFile(root), async (current) => {
|
|
1231
|
+
if (current !== null) {
|
|
1232
|
+
let parsed = null;
|
|
1233
|
+
try {
|
|
1234
|
+
parsed = JSON.parse(current);
|
|
1235
|
+
} catch {
|
|
1236
|
+
return current;
|
|
1237
|
+
}
|
|
1238
|
+
if (parsed !== null && typeof parsed.version === "number" && parsed.version > 1) {
|
|
1239
|
+
console.warn(`suppression sidecar ${suppressedFile(root)} declares version ${String(parsed.version)} (newer than 1); not overwritten`);
|
|
1240
|
+
return current;
|
|
1241
|
+
}
|
|
1242
|
+
}
|
|
1243
|
+
const names = parseSuppressed(current);
|
|
1244
|
+
await task(names);
|
|
1245
|
+
return JSON.stringify({
|
|
1246
|
+
version: 1,
|
|
1247
|
+
names: [...names].sort()
|
|
1248
|
+
}, null, 2);
|
|
1249
|
+
});
|
|
1250
|
+
}
|
|
1251
|
+
//#endregion
|
|
1252
|
+
export { authoringFeedback as A, validateFrontmatter as B, updateSuppressedNames as C, displayBodyOf as D, selectSections as E, normalizeFrontmatter as F, describeReferenceRewrite as G, externalRefs as H, parseFrontmatter as I, planReferenceRewrite as K, relatedSkillNames as L, exceedsContentLimit as M, frontmatterBlock as N, h2Sections as O, frontmatterCatalogInvalid as P, shrinksOverLimit as R, suppressedFile as S, usageObserved as T, supportRefs as U, yamlPlainScalarNeedsQuotes as V, applyReferenceRewrite as W, markAgentCreated as _, bumpPatch as a, saveSuppressedNames as b, bumpView as c, foldCuratorFields as d, getRecord as f, loadUsage as g, loadSuppressedNames as h, applyCuratorMetaFields as i, ensureSkillFrontmatter as j, readingStats as k, daysSinceIso as l, latestActivityAt as m, SUPPRESSED_FILE_VERSION as n, bumpSupportRead as o, idleDays as p, planRehoming as q, applyCuratorLifecycleFields as r, bumpUse as s, MAX_SUPPORT_READ_PATHS as t, emptyRecord as u, mutateUsage as v, usageFile as w, saveUsage as x, normalizeUsageRecord as y, skillMdOnDisk as z };
|