@lmzhen/dsh-evolution-curator 0.1.0-rc.8 → 0.1.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/README.md +7 -1
- package/lib/index.js +553 -84
- package/lib/types/index.d.ts +148 -14
- package/package.json +11 -11
package/README.md
CHANGED
|
@@ -28,4 +28,10 @@ Independent of request-prefix construction. This package does not alter the asse
|
|
|
28
28
|
|
|
29
29
|
- `archive` never deletes: skills move to `.archive/` with a `.archive-reason` marker.
|
|
30
30
|
- `restore(name)` (service) / `/evolution skill restore <name>` brings one archived skill back to the active root and resets its usage state.
|
|
31
|
-
- `consolidate(target, sources)` (service) / `/evolution consolidate` merges source bodies into the target, archives the sources with an absorbed-into marker, and folds their usage records into `archived` state. Both operations snapshot the
|
|
31
|
+
- `consolidate(target, sources)` (service) / `/evolution consolidate` merges source bodies into the target, archives the sources with an absorbed-into marker, and folds their usage records into `archived` state. Both operations snapshot the full state first (`pre-consolidate` / `pre-restore`).
|
|
32
|
+
- `restoreSnapshot` (service) / `/evolution restore` rolls the FULL state back to the latest snapshot: active tree, usage/suppression sidecars, `.archive/` and the curator state carried in the snapshot (`curator-state.json`), so the interval gate does not immediately re-fire after a rollback. The restore itself is undoable — the pre-rollback safety snapshot preserves the current tree plus its state.
|
|
33
|
+
|
|
34
|
+
## Automatic scheduling
|
|
35
|
+
|
|
36
|
+
- `autoStart` (default true) arms an hourly interval check plus a deferred catch-up check `bootGraceSeconds` (default 10) after host boot. Both decide due-ness from the **persisted** `lastRunAt`, so a restart with an overdue schedule runs the first pass within the boot grace instead of waiting a full interval. `bootGraceSeconds: 0` disables the deferral (not recommended: the check may run against a half-mounted host). All scheduling gates — interval, idle, first-run deferral, and the reentrancy guard — remain inside `run()`.
|
|
37
|
+
- `autoStart: false` disables both automatic checks; `/evolution curator run` (manual, gate-skipping) still works.
|
package/lib/index.js
CHANGED
|
@@ -3,25 +3,41 @@ import { randomUUID } from "node:crypto";
|
|
|
3
3
|
import { join } from "node:path";
|
|
4
4
|
import { BlockAssembler, createUserMessage } from "@deepseek-ai/dsh-llm";
|
|
5
5
|
import z from "@deepseek-ai/schemastery";
|
|
6
|
-
import { CURATOR_PROMPT, SkillLibrary, buildCuratorRunReport, computeLifecycleTransitions, evolutionHome, evolutionIoAdapter, loadUsage,
|
|
6
|
+
import { CURATOR_DRY_RUN_BANNER, CURATOR_PROMPT, DEFAULT_ARCHIVE_AFTER_DAYS, DEFAULT_CURATOR_INTERVAL_HOURS, DEFAULT_MIN_IDLE_HOURS, DEFAULT_STALE_AFTER_DAYS, EvolutionGateSet, SkillLibrary, buildCuratorRunReport, computeDedupGroups, computeLifecycleTransitions, computePrefixClusters, computeQualityScores, computeScopeView, emptyRecord, evolutionHome, evolutionIoAdapter, foldCuratorFields, loadSuppressedNames, loadUsage, mutateUsage, parseCuratorNominations, relatedSkillNames, renderCuratorReportMarkdown, updateSuppressedNames } from "@lmzhen/dsh-evolution-core";
|
|
7
7
|
//#region lib/types/index.js
|
|
8
8
|
/**
|
|
9
9
|
* Deterministic skill lifecycle curator with interval gate and archive.
|
|
10
10
|
* @module @lmzhen/dsh-evolution-curator
|
|
11
11
|
*/
|
|
12
|
+
/** Quality-warned skills may turn stale after this many idle days (package-private tunable, P2-8). */
|
|
13
|
+
const DEFAULT_QUALITY_WARN_STALE_AFTER_DAYS = 7;
|
|
14
|
+
/**
|
|
15
|
+
* Block LLM-nominated consolidations that would touch a gate-protected name:
|
|
16
|
+
* exclude / referenced / suppressed skills must never merge (neither as the
|
|
17
|
+
* source being archived nor as the umbrella being edited). Mirrors the control
|
|
18
|
+
* plane's `consolidate()` guard; automatic nominations must pass the same gate.
|
|
19
|
+
*/
|
|
20
|
+
function gateConsolidations(consolidations, gates) {
|
|
21
|
+
const gateSet = gates instanceof EvolutionGateSet ? gates : new EvolutionGateSet(gates);
|
|
22
|
+
return consolidations.filter((n) => !gateSet.isBlocked(n.from) && !gateSet.isBlocked(n.into));
|
|
23
|
+
}
|
|
12
24
|
var EvolutionCurator = class extends Service {
|
|
13
25
|
static inject = ["evolutionIo"];
|
|
14
26
|
static Config = z.object({
|
|
15
27
|
enabled: z.boolean().default(true),
|
|
16
|
-
intervalHours: z.number().default(
|
|
17
|
-
staleAfterDays: z.number().default(
|
|
18
|
-
archiveAfterDays: z.number().default(
|
|
28
|
+
intervalHours: z.number().default(DEFAULT_CURATOR_INTERVAL_HOURS),
|
|
29
|
+
staleAfterDays: z.number().default(DEFAULT_STALE_AFTER_DAYS),
|
|
30
|
+
archiveAfterDays: z.number().default(DEFAULT_ARCHIVE_AFTER_DAYS),
|
|
19
31
|
llmReview: z.boolean().default(false),
|
|
20
32
|
curatorProvider: z.string().default("deepseek-official"),
|
|
21
|
-
qualityWarnStaleAfterDays: z.number().default(
|
|
22
|
-
minIdleHours: z.number().default(
|
|
33
|
+
qualityWarnStaleAfterDays: z.number().default(DEFAULT_QUALITY_WARN_STALE_AFTER_DAYS),
|
|
34
|
+
minIdleHours: z.number().default(DEFAULT_MIN_IDLE_HOURS),
|
|
23
35
|
excludeSkillNames: z.array(z.string()).default([]),
|
|
24
36
|
manageUnmanaged: z.boolean().default(false),
|
|
37
|
+
pruneBuiltins: z.boolean().default(false),
|
|
38
|
+
referencedSkillNames: z.array(z.string()).default([]),
|
|
39
|
+
autoStart: z.boolean().default(true),
|
|
40
|
+
bootGraceSeconds: z.number().default(10),
|
|
25
41
|
curatorReviewMaxTokens: z.number().default(2048)
|
|
26
42
|
});
|
|
27
43
|
skills;
|
|
@@ -36,23 +52,33 @@ var EvolutionCurator = class extends Service {
|
|
|
36
52
|
minIdleHours;
|
|
37
53
|
excludeSkillNames;
|
|
38
54
|
manageUnmanaged;
|
|
55
|
+
pruneBuiltins;
|
|
56
|
+
referencedSkillNames;
|
|
57
|
+
bootGraceSeconds;
|
|
39
58
|
curatorReviewMaxTokens;
|
|
40
59
|
lastRun = 0;
|
|
41
60
|
timer;
|
|
61
|
+
bootCheck;
|
|
62
|
+
running = false;
|
|
42
63
|
constructor(ctx, config = {}) {
|
|
43
64
|
super(ctx, "evolutionCurator");
|
|
44
65
|
this.io = evolutionIoAdapter(() => ctx.evolutionIo.provider());
|
|
45
|
-
this.skills = new SkillLibrary(void 0, this.io)
|
|
66
|
+
this.skills = new SkillLibrary(void 0, this.io, void 0, (event) => {
|
|
67
|
+
this.ctx.emit("evolution/skill-mutated", event);
|
|
68
|
+
});
|
|
46
69
|
this.enabled = config.enabled ?? true;
|
|
47
|
-
this.intervalHours = config.intervalHours ??
|
|
48
|
-
this.staleAfterDays = config.staleAfterDays ??
|
|
49
|
-
this.archiveAfterDays = config.archiveAfterDays ??
|
|
70
|
+
this.intervalHours = config.intervalHours ?? DEFAULT_CURATOR_INTERVAL_HOURS;
|
|
71
|
+
this.staleAfterDays = config.staleAfterDays ?? DEFAULT_STALE_AFTER_DAYS;
|
|
72
|
+
this.archiveAfterDays = config.archiveAfterDays ?? DEFAULT_ARCHIVE_AFTER_DAYS;
|
|
50
73
|
this.llmReview = config.llmReview ?? false;
|
|
51
74
|
this.curatorProvider = config.curatorProvider ?? "deepseek-official";
|
|
52
|
-
this.qualityWarnStaleAfterDays = config.qualityWarnStaleAfterDays ??
|
|
53
|
-
this.minIdleHours = config.minIdleHours ??
|
|
75
|
+
this.qualityWarnStaleAfterDays = config.qualityWarnStaleAfterDays ?? DEFAULT_QUALITY_WARN_STALE_AFTER_DAYS;
|
|
76
|
+
this.minIdleHours = config.minIdleHours ?? DEFAULT_MIN_IDLE_HOURS;
|
|
54
77
|
this.excludeSkillNames = new Set(config.excludeSkillNames ?? []);
|
|
55
78
|
this.manageUnmanaged = config.manageUnmanaged ?? false;
|
|
79
|
+
this.pruneBuiltins = config.pruneBuiltins ?? false;
|
|
80
|
+
this.referencedSkillNames = new Set(config.referencedSkillNames ?? []);
|
|
81
|
+
this.bootGraceSeconds = config.bootGraceSeconds ?? 10;
|
|
56
82
|
this.curatorReviewMaxTokens = config.curatorReviewMaxTokens ?? 2048;
|
|
57
83
|
this.lastRun = Date.now();
|
|
58
84
|
this.ctx.effect(() => {
|
|
@@ -60,6 +86,7 @@ var EvolutionCurator = class extends Service {
|
|
|
60
86
|
this.stop();
|
|
61
87
|
};
|
|
62
88
|
}, "evolution-curator.stop");
|
|
89
|
+
if (config.autoStart ?? true) this.start();
|
|
63
90
|
}
|
|
64
91
|
lifecycle() {
|
|
65
92
|
const snapshot = this.ctx.get("evolutionPolicy")?.get();
|
|
@@ -71,33 +98,85 @@ var EvolutionCurator = class extends Service {
|
|
|
71
98
|
}
|
|
72
99
|
start() {
|
|
73
100
|
if (!this.enabled || this.timer) return;
|
|
74
|
-
this.
|
|
75
|
-
|
|
76
|
-
|
|
101
|
+
this.bootCheck = setTimeout(() => {
|
|
102
|
+
this.bootCheck = void 0;
|
|
103
|
+
this.autoCheck();
|
|
104
|
+
}, this.bootGraceSeconds * 1e3);
|
|
105
|
+
this.bootCheck.unref();
|
|
106
|
+
this.timer = setInterval(() => void this.autoCheck(), 3600 * 1e3);
|
|
77
107
|
this.timer.unref();
|
|
78
108
|
}
|
|
79
109
|
stop() {
|
|
80
110
|
if (this.timer) clearInterval(this.timer);
|
|
81
111
|
this.timer = void 0;
|
|
112
|
+
if (this.bootCheck) clearTimeout(this.bootCheck);
|
|
113
|
+
this.bootCheck = void 0;
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* Pause or resume automatic curation (B-line G2, Hermes `set_paused`
|
|
117
|
+
* parity): the flag is persisted on the curator state record and the
|
|
118
|
+
* `run()` paused gate skips automatic passes while it holds. Manual runs
|
|
119
|
+
* (`ignoreGates`) are unaffected — pause is a soft stop for the scheduler,
|
|
120
|
+
* not a lock on the operator.
|
|
121
|
+
*
|
|
122
|
+
* Pausing on a state-less curator state seeds the record with `lastRunAt:
|
|
123
|
+
* now`, so a later resume re-enters through the interval gate and defers a
|
|
124
|
+
* full cycle instead of firing immediately (first-run defer interaction,
|
|
125
|
+
* kept deliberately: an unattended resume must not auto-run mid-boot).
|
|
126
|
+
*/
|
|
127
|
+
async setPaused(paused) {
|
|
128
|
+
const stateService = this.curatorStateService();
|
|
129
|
+
const persisted = await stateService?.loadCuratorState() ?? null;
|
|
130
|
+
await stateService?.saveCuratorState({
|
|
131
|
+
schemaVersion: 1,
|
|
132
|
+
lastRunAt: persisted?.lastRunAt ?? Date.now(),
|
|
133
|
+
runCount: persisted?.runCount ?? 0,
|
|
134
|
+
lastSummary: persisted?.lastSummary ?? (paused ? "paused" : "resumed"),
|
|
135
|
+
paused
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
/** Current persisted curator state (read-only view for /evolution curator status). */
|
|
139
|
+
async status() {
|
|
140
|
+
return await this.curatorStateService()?.loadCuratorState() ?? null;
|
|
82
141
|
}
|
|
83
142
|
/**
|
|
84
|
-
*
|
|
85
|
-
*
|
|
86
|
-
*
|
|
87
|
-
*
|
|
143
|
+
* One automatic schedule check: run a pass when the persisted curator state
|
|
144
|
+
* (falling back to the in-memory clock for state-less compositions) is at
|
|
145
|
+
* least one interval old. All gates — interval, idle, first-run defer,
|
|
146
|
+
* reentrancy — stay inside `run()`, so this method only decides whether to
|
|
147
|
+
* wake it, and never duplicates gate logic.
|
|
88
148
|
*/
|
|
89
|
-
async
|
|
90
|
-
|
|
149
|
+
async autoCheck() {
|
|
150
|
+
const last = (await this.curatorStateService()?.loadCuratorState())?.lastRunAt ?? this.lastRun;
|
|
151
|
+
if (Date.now() - last >= this.lifecycle().intervalHours * 36e5) await this.run();
|
|
152
|
+
}
|
|
153
|
+
/**
|
|
154
|
+
* Optional Hermes-curator LLM pass. The model may only NOMINATE pruning and
|
|
155
|
+
* consolidation; every move stays a control-plane operation and each
|
|
156
|
+
* nomination is re-validated against the tree and protected markers before
|
|
157
|
+
* any file move. `dryRun` prepends the report-only banner.
|
|
158
|
+
*/
|
|
159
|
+
async recommend(candidates, options = {}) {
|
|
160
|
+
const empty = {
|
|
161
|
+
prunings: [],
|
|
162
|
+
consolidations: []
|
|
163
|
+
};
|
|
164
|
+
if (candidates.length === 0) return empty;
|
|
91
165
|
const llm = this.ctx.get("llm");
|
|
92
|
-
if (!llm) return
|
|
166
|
+
if (!llm) return empty;
|
|
93
167
|
const model = this.ctx.get("evolutionPolicy")?.get().curatorModel ?? "deepseek-v4-pro";
|
|
168
|
+
const clusters = computePrefixClusters(candidates);
|
|
169
|
+
const clusterLines = clusters.length === 0 ? ["Prefix clusters observed in the candidate list: (none)"] : ["Prefix clusters observed in the candidate list (orientation only — verify against the names above; you may also flag additional clusters):", ...clusters.map((cluster) => `- '${cluster.key}': ${cluster.members.join(", ")}`)];
|
|
94
170
|
const prompt = [
|
|
171
|
+
options.dryRun ? CURATOR_DRY_RUN_BANNER : "",
|
|
95
172
|
CURATOR_PROMPT,
|
|
96
173
|
"",
|
|
97
|
-
|
|
174
|
+
`Stale candidates observed by the deterministic lifecycle scanner:${candidates.length === 0 ? " (none)" : ""}`,
|
|
98
175
|
...candidates.map((name) => `- ${name}`),
|
|
99
176
|
"",
|
|
100
|
-
|
|
177
|
+
...clusterLines,
|
|
178
|
+
"",
|
|
179
|
+
"Return a YAML summary with consolidations and prunings lists. Nominate only actions whose archival/merge is clearly safe."
|
|
101
180
|
].join("\n");
|
|
102
181
|
try {
|
|
103
182
|
const assembler = new BlockAssembler();
|
|
@@ -116,17 +195,57 @@ var EvolutionCurator = class extends Service {
|
|
|
116
195
|
summary: "curator review"
|
|
117
196
|
}
|
|
118
197
|
})],
|
|
119
|
-
maxTokens: this.curatorReviewMaxTokens
|
|
120
|
-
purpose: "evolution-curator"
|
|
198
|
+
maxTokens: this.curatorReviewMaxTokens
|
|
121
199
|
})) assembler.push(chunk);
|
|
122
|
-
const
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
200
|
+
const parsed = parseCuratorNominations(assembler.blocks().filter((block) => block.type === "text").map((block) => block.text).join("\n"));
|
|
201
|
+
return {
|
|
202
|
+
prunings: parsed.prunings.filter((name) => candidates.includes(name)),
|
|
203
|
+
consolidations: parsed.consolidations.filter((item) => candidates.includes(item.from))
|
|
204
|
+
};
|
|
127
205
|
} catch {
|
|
128
|
-
return
|
|
206
|
+
return empty;
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
/** Optional curator-state service (evolution-state-json / storage-domain). */
|
|
210
|
+
curatorStateService() {
|
|
211
|
+
return this.ctx.get("evolutionState");
|
|
212
|
+
}
|
|
213
|
+
/**
|
|
214
|
+
* Full-state snapshot: the skills tree plus the current curator state as an
|
|
215
|
+
* `extras/curator-state.json` side file. Every pre-mutation snapshot in the
|
|
216
|
+
* curator goes through here so a later `restoreSnapshot()` can rewind both
|
|
217
|
+
* the tree and the state (Hermes curator_backup backs up `.curator_state`).
|
|
218
|
+
*/
|
|
219
|
+
async snapshotFull(reason = "pre-mutation") {
|
|
220
|
+
const state = await this.curatorStateService()?.loadCuratorState();
|
|
221
|
+
const extras = state === null || state === void 0 ? [] : [{
|
|
222
|
+
name: "curator-state.json",
|
|
223
|
+
content: JSON.stringify(state, null, 2)
|
|
224
|
+
}];
|
|
225
|
+
return await this.skills.snapshotAll(reason, extras);
|
|
226
|
+
}
|
|
227
|
+
/**
|
|
228
|
+
* Full-state rollback: restore the latest snapshot's tree/sidecars/archive
|
|
229
|
+
* AND the curator state it carried. The pre-rollback safety snapshot keeps
|
|
230
|
+
* the current tree plus current state (as extras), so the rollback itself
|
|
231
|
+
* is reversible.
|
|
232
|
+
*/
|
|
233
|
+
async restoreSnapshot() {
|
|
234
|
+
const stateService = this.curatorStateService();
|
|
235
|
+
const currentState = await stateService?.loadCuratorState();
|
|
236
|
+
const extras = currentState === null || currentState === void 0 ? [] : [{
|
|
237
|
+
name: "curator-state.json",
|
|
238
|
+
content: JSON.stringify(currentState, null, 2)
|
|
239
|
+
}];
|
|
240
|
+
const result = await this.skills.restoreLatestSnapshot(extras);
|
|
241
|
+
if (!result.ok) return result;
|
|
242
|
+
const stateExtra = result.extras?.find((extra) => extra.name === "curator-state.json");
|
|
243
|
+
if (stateExtra && stateService) try {
|
|
244
|
+
await stateService.saveCuratorState(JSON.parse(stateExtra.content));
|
|
245
|
+
} catch (error) {
|
|
246
|
+
this.ctx.logger.warn(`evolution-curator: failed to restore curator state: ${error instanceof Error ? error.message : String(error)}`);
|
|
129
247
|
}
|
|
248
|
+
return result;
|
|
130
249
|
}
|
|
131
250
|
skippedReport(runId, startedAt) {
|
|
132
251
|
return buildCuratorRunReport({
|
|
@@ -137,57 +256,132 @@ var EvolutionCurator = class extends Service {
|
|
|
137
256
|
llmNominations: [],
|
|
138
257
|
archiveCandidates: [],
|
|
139
258
|
archived: [],
|
|
140
|
-
failed: []
|
|
259
|
+
failed: [],
|
|
260
|
+
llmReviewEnabled: this.llmReview
|
|
141
261
|
});
|
|
142
262
|
}
|
|
143
|
-
|
|
263
|
+
/**
|
|
264
|
+
* Run one curator pass. `ignoreGates` skips the interval and idle gates so an
|
|
265
|
+
* explicit `/evolution curator run` always executes (manual-run semantics):
|
|
266
|
+
* `dryRun` computes the lifecycle and the LLM nominations but performs no
|
|
267
|
+
* mutation, reports what WOULD happen, and does not push out the next run.
|
|
268
|
+
* Reentrant calls (autoStart timer + manual command at the same instant) are
|
|
269
|
+
* skipped with an explicit `already-running` outcome.
|
|
270
|
+
*/
|
|
271
|
+
async run(options = {}) {
|
|
272
|
+
if (this.running) return {
|
|
273
|
+
stale: [],
|
|
274
|
+
archived: [],
|
|
275
|
+
errors: [],
|
|
276
|
+
report: this.skippedReport("already-running", (/* @__PURE__ */ new Date()).toISOString()),
|
|
277
|
+
skipped: "already-running"
|
|
278
|
+
};
|
|
279
|
+
this.running = true;
|
|
280
|
+
try {
|
|
281
|
+
return await this.runCore(options);
|
|
282
|
+
} finally {
|
|
283
|
+
this.running = false;
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
async runCore(options = {}) {
|
|
287
|
+
const { ignoreGates = false, dryRun = false } = options;
|
|
144
288
|
const startedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
145
289
|
const runId = randomUUID();
|
|
146
|
-
const stateService = this.
|
|
290
|
+
const stateService = this.curatorStateService();
|
|
147
291
|
const lifecycle = this.lifecycle();
|
|
148
|
-
const persisted = await stateService?.loadCuratorState();
|
|
149
|
-
if (
|
|
292
|
+
const persisted = await stateService?.loadCuratorState() ?? null;
|
|
293
|
+
if (!ignoreGates && persisted?.paused === true) return {
|
|
294
|
+
stale: [],
|
|
295
|
+
archived: [],
|
|
296
|
+
errors: [],
|
|
297
|
+
report: this.skippedReport(runId, startedAt),
|
|
298
|
+
skipped: "paused"
|
|
299
|
+
};
|
|
300
|
+
if (!ignoreGates && persisted && Date.now() - persisted.lastRunAt < lifecycle.intervalHours * 36e5) return {
|
|
150
301
|
stale: [],
|
|
151
302
|
archived: [],
|
|
152
303
|
errors: [],
|
|
153
304
|
report: this.skippedReport(runId, startedAt),
|
|
154
305
|
skipped: "interval"
|
|
155
306
|
};
|
|
156
|
-
if (this.minIdleHours > 0 && this.recentSessionActive()) return {
|
|
307
|
+
if (!ignoreGates && this.minIdleHours > 0 && this.recentSessionActive()) return {
|
|
157
308
|
stale: [],
|
|
158
309
|
archived: [],
|
|
159
310
|
errors: [],
|
|
160
311
|
report: this.skippedReport(runId, startedAt),
|
|
161
312
|
skipped: "active-session"
|
|
162
313
|
};
|
|
314
|
+
if (!ignoreGates && persisted === null) {
|
|
315
|
+
await stateService?.saveCuratorState({
|
|
316
|
+
schemaVersion: 1,
|
|
317
|
+
lastRunAt: Date.now(),
|
|
318
|
+
runCount: 0,
|
|
319
|
+
lastSummary: "first-run-deferred",
|
|
320
|
+
paused: false
|
|
321
|
+
});
|
|
322
|
+
return {
|
|
323
|
+
stale: [],
|
|
324
|
+
archived: [],
|
|
325
|
+
errors: [],
|
|
326
|
+
report: this.skippedReport(runId, startedAt),
|
|
327
|
+
skipped: "first-run-deferred"
|
|
328
|
+
};
|
|
329
|
+
}
|
|
163
330
|
const root = this.skills.root;
|
|
164
|
-
const
|
|
165
|
-
const usage =
|
|
331
|
+
const rawUsage = await loadUsage(root, this.io);
|
|
332
|
+
const usage = dryRun ? new Map([...rawUsage].map(([name, record]) => [name, { ...record }])) : rawUsage;
|
|
333
|
+
const snapshotPath = dryRun ? void 0 : await this.snapshotFull("pre-curator-run");
|
|
334
|
+
const suppressedNames = new Set(await loadSuppressedNames(root, this.io));
|
|
335
|
+
const gates = new EvolutionGateSet({
|
|
336
|
+
exclude: this.excludeSkillNames,
|
|
337
|
+
referenced: this.referencedSkillNames,
|
|
338
|
+
suppressed: suppressedNames
|
|
339
|
+
});
|
|
340
|
+
const { bundledNames, treeNames } = await this.seedBaseline(usage);
|
|
341
|
+
const contents = /* @__PURE__ */ new Map();
|
|
342
|
+
for (const name of treeNames) {
|
|
343
|
+
const text = await this.skills.read(name);
|
|
344
|
+
if (text) contents.set(name, text);
|
|
345
|
+
}
|
|
346
|
+
const dedupMembers = [...new Set(computeDedupGroups({ contents }).filter((group) => group.length >= 2).flat())];
|
|
347
|
+
await this.scoreTree(usage, treeNames);
|
|
166
348
|
const result = computeLifecycleTransitions(usage, {
|
|
167
349
|
staleAfterDays: lifecycle.staleAfterDays,
|
|
168
350
|
archiveAfterDays: lifecycle.archiveAfterDays,
|
|
169
351
|
qualityWarnStaleAfterDays: this.qualityWarnStaleAfterDays,
|
|
170
352
|
excludeSkillNames: this.excludeSkillNames,
|
|
171
|
-
manageUnmanaged: this.manageUnmanaged
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
353
|
+
manageUnmanaged: this.manageUnmanaged,
|
|
354
|
+
pruneBuiltins: this.pruneBuiltins,
|
|
355
|
+
bundledNames,
|
|
356
|
+
suppressedNames,
|
|
357
|
+
referencedSkillNames: this.referencedSkillNames
|
|
358
|
+
}, /* @__PURE__ */ new Date(), gates);
|
|
359
|
+
const recommendPool = [...new Set([...result.markStale, ...dedupMembers])];
|
|
360
|
+
const nominations = this.llmReview ? await this.recommend(recommendPool, { dryRun }) : {
|
|
361
|
+
prunings: [],
|
|
362
|
+
consolidations: []
|
|
363
|
+
};
|
|
364
|
+
const gatedNominations = {
|
|
365
|
+
...nominations,
|
|
366
|
+
prunings: nominations.prunings.filter((name) => result.markStale.includes(name)),
|
|
367
|
+
consolidations: gateConsolidations(nominations.consolidations, gates)
|
|
368
|
+
};
|
|
369
|
+
const llmNominations = gatedNominations.prunings;
|
|
176
370
|
const archiveCandidates = [...new Set([...result.archive, ...llmNominations])];
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
this.lastRun = Date.now();
|
|
371
|
+
const { archivedSkills, errors, consolidated } = await this.applyMutations({
|
|
372
|
+
dryRun,
|
|
373
|
+
archiveCandidates,
|
|
374
|
+
nominations: gatedNominations,
|
|
375
|
+
treeNames,
|
|
376
|
+
usage,
|
|
377
|
+
bundledNames,
|
|
378
|
+
suppressedNames,
|
|
379
|
+
root,
|
|
380
|
+
recommendPool: new Set(recommendPool),
|
|
381
|
+
stateOwned: new Set([...result.transitions.map((t) => t.name), ...archiveCandidates]),
|
|
382
|
+
failedFrom: new Map(result.transitions.filter((t) => t.to === "archived").map((t) => [t.name, t.from]))
|
|
383
|
+
});
|
|
384
|
+
if (!dryRun) this.lastRun = Date.now();
|
|
191
385
|
const report = buildCuratorRunReport({
|
|
192
386
|
runId,
|
|
193
387
|
startedAt,
|
|
@@ -196,32 +390,206 @@ var EvolutionCurator = class extends Service {
|
|
|
196
390
|
llmNominations,
|
|
197
391
|
archiveCandidates,
|
|
198
392
|
archived: archivedSkills,
|
|
199
|
-
failed: archiveCandidates.filter((name) => errors.some((error) => error.startsWith(`${name}:`))).map((name) => {
|
|
393
|
+
failed: [...new Set([...archiveCandidates, ...gatedNominations.consolidations.map((item) => item.from)])].filter((name) => errors.some((error) => error.startsWith(`${name}:`))).map((name) => {
|
|
200
394
|
return {
|
|
201
395
|
name,
|
|
202
396
|
reason: errors.find((item) => item.startsWith(`${name}:`))?.slice(name.length + 2) ?? "unknown"
|
|
203
397
|
};
|
|
204
398
|
}),
|
|
205
|
-
|
|
399
|
+
consolidated,
|
|
400
|
+
...snapshotPath === void 0 ? {} : { snapshotPath },
|
|
401
|
+
llmReviewEnabled: this.llmReview
|
|
206
402
|
});
|
|
207
403
|
const reportsRoot = join(evolutionHome(), "reports");
|
|
208
404
|
try {
|
|
209
405
|
await this.io.writeText(join(reportsRoot, `curator-${runId}.json`), JSON.stringify(report, null, 2));
|
|
406
|
+
await this.io.writeText(join(reportsRoot, `curator-${runId}.md`), renderCuratorReportMarkdown(report));
|
|
407
|
+
await this.retainReports(20);
|
|
210
408
|
} catch (error) {
|
|
211
409
|
this.ctx.logger.warn(`evolution-curator: failed to persist report ${runId}`);
|
|
212
410
|
this.ctx.logger.warn(error);
|
|
213
411
|
}
|
|
412
|
+
const llmHint = !this.llmReview && result.markStale.length > 0 ? " (llmReview: off - deterministic archive only; set llmReview: true for the LLM merge channel)" : "";
|
|
413
|
+
const summary = `${dryRun ? "dry-run" : "auto"}: stale:${result.markStale.length} archived:${archivedSkills.length} consolidated:${gatedNominations.consolidations.length}${llmHint}`;
|
|
414
|
+
const pausedNow = (await stateService?.loadCuratorState())?.paused ?? false;
|
|
214
415
|
await stateService?.saveCuratorState({
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
416
|
+
schemaVersion: 1,
|
|
417
|
+
lastRunAt: dryRun ? persisted?.lastRunAt ?? this.lastRun : this.lastRun,
|
|
418
|
+
runCount: dryRun ? persisted?.runCount ?? 0 : (persisted?.runCount ?? 0) + 1,
|
|
419
|
+
lastSummary: summary,
|
|
420
|
+
paused: pausedNow
|
|
219
421
|
});
|
|
220
422
|
return {
|
|
221
423
|
stale: result.markStale,
|
|
222
424
|
archived: archivedSkills.map((item) => item.name),
|
|
223
425
|
errors,
|
|
224
|
-
report
|
|
426
|
+
report,
|
|
427
|
+
...this.llmReview ? { nominations: gatedNominations } : {}
|
|
428
|
+
};
|
|
429
|
+
}
|
|
430
|
+
/**
|
|
431
|
+
* Seed baseline records for tree skills the sidecar has not seen yet, so
|
|
432
|
+
* their inactivity clock starts now (first-sight defer) and bundled skills
|
|
433
|
+
* become known candidates only when prune-builtins opts them in. Also
|
|
434
|
+
* returns the full active tree names for nomination validation.
|
|
435
|
+
*/
|
|
436
|
+
async seedBaseline(usage) {
|
|
437
|
+
const bundledNames = /* @__PURE__ */ new Set();
|
|
438
|
+
const treeNames = /* @__PURE__ */ new Set();
|
|
439
|
+
for (const summary of await this.skills.list()) {
|
|
440
|
+
treeNames.add(summary.name);
|
|
441
|
+
if (!usage.has(summary.name)) usage.set(summary.name, emptyRecord());
|
|
442
|
+
if (await this.skills.isBundled(summary.name)) bundledNames.add(summary.name);
|
|
443
|
+
const record = usage.get(summary.name);
|
|
444
|
+
if (record) record.pinned = await this.skills.isPinned(summary.name);
|
|
445
|
+
}
|
|
446
|
+
return {
|
|
447
|
+
bundledNames,
|
|
448
|
+
treeNames
|
|
449
|
+
};
|
|
450
|
+
}
|
|
451
|
+
/**
|
|
452
|
+
* F13 six-factor quality scoring, persisted onto the usage records.
|
|
453
|
+
*/
|
|
454
|
+
async scoreTree(usage, treeNames) {
|
|
455
|
+
const supportDirs = /* @__PURE__ */ new Map();
|
|
456
|
+
for (const name of treeNames) supportDirs.set(name, await this.skills.countSupportDirs(name));
|
|
457
|
+
const quality = computeQualityScores({
|
|
458
|
+
usage,
|
|
459
|
+
supportDirs,
|
|
460
|
+
referenceCounts: await this.referenceCounts(treeNames)
|
|
461
|
+
});
|
|
462
|
+
for (const [name, score] of quality) {
|
|
463
|
+
const record = usage.get(name);
|
|
464
|
+
if (record) {
|
|
465
|
+
record.quality_score = score.score;
|
|
466
|
+
record.quality_warn = score.warn;
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
/**
|
|
471
|
+
* In-degree over explicit `related_skills` frontmatter references (the DSH
|
|
472
|
+
* equivalent of the graph-in-degree references factor): a skill listing
|
|
473
|
+
* other skill names counts as one reference to each of them, so hub skills
|
|
474
|
+
* that are explicitly named by peers get a non-zero references factor.
|
|
475
|
+
*/
|
|
476
|
+
async referenceCounts(treeNames) {
|
|
477
|
+
const counts = /* @__PURE__ */ new Map();
|
|
478
|
+
for (const name of treeNames) {
|
|
479
|
+
const content = await this.skills.read(name);
|
|
480
|
+
if (!content) continue;
|
|
481
|
+
for (const target of relatedSkillNames(content, name)) counts.set(target, (counts.get(target) ?? 0) + 1);
|
|
482
|
+
}
|
|
483
|
+
return counts;
|
|
484
|
+
}
|
|
485
|
+
/**
|
|
486
|
+
* Execute lifecycle archives and consolidation nominations, then persist the
|
|
487
|
+
* suppression and usage sidecars best-effort. A dry-run short-circuits: no
|
|
488
|
+
* file moves and no state persistence — the caller still writes the report.
|
|
489
|
+
*/
|
|
490
|
+
async applyMutations(input) {
|
|
491
|
+
if (input.dryRun) return {
|
|
492
|
+
archivedSkills: [],
|
|
493
|
+
errors: [],
|
|
494
|
+
suppressedChanged: false,
|
|
495
|
+
consolidated: []
|
|
496
|
+
};
|
|
497
|
+
const { archiveCandidates, nominations, treeNames, usage, bundledNames, suppressedNames, root, failedFrom } = input;
|
|
498
|
+
const errors = [];
|
|
499
|
+
const archivedSkills = [];
|
|
500
|
+
const executedConsolidations = [];
|
|
501
|
+
let suppressedChanged = false;
|
|
502
|
+
const suppressedAdded = /* @__PURE__ */ new Set();
|
|
503
|
+
const stateOwned = new Set(input.stateOwned ?? []);
|
|
504
|
+
for (const name of archiveCandidates) {
|
|
505
|
+
const archived = await this.skills.archive(name, {
|
|
506
|
+
reason: "Lifecycle: reached archive threshold",
|
|
507
|
+
allowBundled: this.pruneBuiltins
|
|
508
|
+
});
|
|
509
|
+
if (!archived.ok) {
|
|
510
|
+
const record = usage.get(name);
|
|
511
|
+
const from = failedFrom?.get(name);
|
|
512
|
+
if (record && (from === "stale" || from === "active")) {
|
|
513
|
+
record.state = from;
|
|
514
|
+
record.archived_at = null;
|
|
515
|
+
stateOwned.add(name);
|
|
516
|
+
}
|
|
517
|
+
errors.push(`${name}: ${archived.message}`);
|
|
518
|
+
} else {
|
|
519
|
+
const record = usage.get(name);
|
|
520
|
+
if (record) {
|
|
521
|
+
record.state = "archived";
|
|
522
|
+
record.archived_at = (/* @__PURE__ */ new Date()).toISOString();
|
|
523
|
+
stateOwned.add(name);
|
|
524
|
+
}
|
|
525
|
+
archivedSkills.push({
|
|
526
|
+
name,
|
|
527
|
+
path: archived.path ?? "",
|
|
528
|
+
reason: "Lifecycle: reached archive threshold"
|
|
529
|
+
});
|
|
530
|
+
if (bundledNames.has(name)) {
|
|
531
|
+
suppressedNames.add(name);
|
|
532
|
+
suppressedAdded.add(name);
|
|
533
|
+
suppressedChanged = true;
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
const alreadyArchived = new Set(archiveCandidates);
|
|
538
|
+
for (const nomination of nominations.consolidations) {
|
|
539
|
+
if (alreadyArchived.has(nomination.from)) continue;
|
|
540
|
+
if (!treeNames.has(nomination.from) || !treeNames.has(nomination.into)) {
|
|
541
|
+
errors.push(`${nomination.from}: consolidation target or source missing from the skill tree`);
|
|
542
|
+
continue;
|
|
543
|
+
}
|
|
544
|
+
if (!input.recommendPool.has(nomination.from)) {
|
|
545
|
+
errors.push(`${nomination.from}: consolidation nomination outside the candidate pool — refused (advisory text has no executability authority)`);
|
|
546
|
+
continue;
|
|
547
|
+
}
|
|
548
|
+
const consolidated = await this.skills.consolidate(nomination.into, [nomination.from], "background_review");
|
|
549
|
+
if (!consolidated.ok) {
|
|
550
|
+
errors.push(`${nomination.from}: ${consolidated.message}`);
|
|
551
|
+
continue;
|
|
552
|
+
}
|
|
553
|
+
const record = usage.get(nomination.from);
|
|
554
|
+
if (record) {
|
|
555
|
+
record.state = "archived";
|
|
556
|
+
record.archived_at = (/* @__PURE__ */ new Date()).toISOString();
|
|
557
|
+
stateOwned.add(nomination.from);
|
|
558
|
+
}
|
|
559
|
+
alreadyArchived.add(nomination.from);
|
|
560
|
+
executedConsolidations.push({
|
|
561
|
+
from: nomination.from,
|
|
562
|
+
into: nomination.into
|
|
563
|
+
});
|
|
564
|
+
archivedSkills.push({
|
|
565
|
+
name: nomination.from,
|
|
566
|
+
path: join(this.skills.root, ".archive", nomination.from),
|
|
567
|
+
reason: `Consolidated into ${nomination.into}`
|
|
568
|
+
});
|
|
569
|
+
}
|
|
570
|
+
if (suppressedChanged) try {
|
|
571
|
+
await updateSuppressedNames(root, this.io, (current) => {
|
|
572
|
+
for (const name of suppressedAdded) current.add(name);
|
|
573
|
+
});
|
|
574
|
+
} catch {
|
|
575
|
+
this.ctx.logger.warn("evolution-curator: failed to persist suppressed names; archived built-ins may re-enter the lifecycle");
|
|
576
|
+
}
|
|
577
|
+
try {
|
|
578
|
+
await mutateUsage(root, this.io, (disk) => {
|
|
579
|
+
foldCuratorFields(disk, usage, stateOwned);
|
|
580
|
+
});
|
|
581
|
+
} catch {
|
|
582
|
+
this.ctx.logger.warn("evolution-curator: failed to persist usage sidecar");
|
|
583
|
+
}
|
|
584
|
+
const usageRegistry = this.ctx.get("skillUsage");
|
|
585
|
+
try {
|
|
586
|
+
await usageRegistry?.invalidate?.();
|
|
587
|
+
} catch {}
|
|
588
|
+
return {
|
|
589
|
+
archivedSkills,
|
|
590
|
+
errors,
|
|
591
|
+
suppressedChanged,
|
|
592
|
+
consolidated: executedConsolidations
|
|
225
593
|
};
|
|
226
594
|
}
|
|
227
595
|
recentSessionActive() {
|
|
@@ -235,11 +603,61 @@ var EvolutionCurator = class extends Service {
|
|
|
235
603
|
}
|
|
236
604
|
return latest > 0 && Date.now() - latest < this.minIdleHours * 36e5;
|
|
237
605
|
}
|
|
606
|
+
/**
|
|
607
|
+
* Keep only the newest N curator reports, ordered by the report's own
|
|
608
|
+
* `startedAt` (the runId is a UUID and cannot order history). Best-effort
|
|
609
|
+
* like `retainSnapshots`: a failed removal must not fail the run that just
|
|
610
|
+
* persisted its report. The paired `.md` digest is pruned with its JSON.
|
|
611
|
+
*/
|
|
612
|
+
async retainReports(keep) {
|
|
613
|
+
const reportsRoot = join(evolutionHome(), "reports");
|
|
614
|
+
let entries;
|
|
615
|
+
try {
|
|
616
|
+
entries = await this.io.list(reportsRoot);
|
|
617
|
+
} catch {
|
|
618
|
+
return;
|
|
619
|
+
}
|
|
620
|
+
const dated = [];
|
|
621
|
+
for (const name of entries.filter((entry) => entry.startsWith("curator-") && entry.endsWith(".json"))) try {
|
|
622
|
+
const raw = await this.io.readText(join(reportsRoot, name));
|
|
623
|
+
if (raw === null) continue;
|
|
624
|
+
const parsed = JSON.parse(raw);
|
|
625
|
+
const startedAt = typeof parsed.startedAt === "string" ? Date.parse(parsed.startedAt) : NaN;
|
|
626
|
+
if (Number.isFinite(startedAt)) dated.push({
|
|
627
|
+
name,
|
|
628
|
+
startedAt
|
|
629
|
+
});
|
|
630
|
+
} catch {}
|
|
631
|
+
dated.sort((a, b) => b.startedAt - a.startedAt);
|
|
632
|
+
for (const oldReport of dated.slice(keep)) {
|
|
633
|
+
const stem = oldReport.name.replace(/\.json$/, "");
|
|
634
|
+
try {
|
|
635
|
+
await this.io.remove(join(reportsRoot, oldReport.name));
|
|
636
|
+
} catch {}
|
|
637
|
+
try {
|
|
638
|
+
await this.io.remove(join(reportsRoot, `${stem}.md`));
|
|
639
|
+
} catch {}
|
|
640
|
+
}
|
|
641
|
+
}
|
|
238
642
|
async latestReport() {
|
|
239
643
|
const reportsRoot = join(evolutionHome(), "reports");
|
|
240
|
-
const
|
|
241
|
-
|
|
242
|
-
const
|
|
644
|
+
const names = (await this.io.list(reportsRoot)).filter((name) => name.startsWith("curator-") && name.endsWith(".json")).sort();
|
|
645
|
+
let latest = null;
|
|
646
|
+
for (const name of names) {
|
|
647
|
+
const raw = await this.io.readText(join(reportsRoot, name));
|
|
648
|
+
if (raw === null) continue;
|
|
649
|
+
try {
|
|
650
|
+
const parsed = JSON.parse(raw);
|
|
651
|
+
const startedAt = typeof parsed.startedAt === "string" ? Date.parse(parsed.startedAt) : 0;
|
|
652
|
+
if (!Number.isFinite(startedAt)) continue;
|
|
653
|
+
if (latest === null || startedAt > latest.startedAt) latest = {
|
|
654
|
+
name,
|
|
655
|
+
startedAt
|
|
656
|
+
};
|
|
657
|
+
} catch {}
|
|
658
|
+
}
|
|
659
|
+
if (latest === null) return null;
|
|
660
|
+
const raw = await this.io.readText(join(reportsRoot, latest.name));
|
|
243
661
|
if (raw === null) return null;
|
|
244
662
|
try {
|
|
245
663
|
return JSON.parse(raw);
|
|
@@ -248,25 +666,66 @@ var EvolutionCurator = class extends Service {
|
|
|
248
666
|
}
|
|
249
667
|
}
|
|
250
668
|
/**
|
|
669
|
+
* Read-only lifecycle scope classification: which skills are in scope,
|
|
670
|
+
* watched (stale/quality-warned), exempted, or protected. Uses the same
|
|
671
|
+
* candidate gate as `run()` (`computeScopeView` / `lifecycleCandidate`),
|
|
672
|
+
* so the view always predicts what a curator pass may touch.
|
|
673
|
+
*/
|
|
674
|
+
async scopeView() {
|
|
675
|
+
const root = this.skills.root;
|
|
676
|
+
const usage = await loadUsage(root, this.io);
|
|
677
|
+
const { bundledNames } = await this.seedBaseline(usage);
|
|
678
|
+
const gates = new EvolutionGateSet({
|
|
679
|
+
exclude: this.excludeSkillNames,
|
|
680
|
+
referenced: this.referencedSkillNames,
|
|
681
|
+
suppressed: new Set(await loadSuppressedNames(root, this.io))
|
|
682
|
+
});
|
|
683
|
+
return computeScopeView(usage, {
|
|
684
|
+
staleAfterDays: this.lifecycle().staleAfterDays,
|
|
685
|
+
archiveAfterDays: this.lifecycle().archiveAfterDays,
|
|
686
|
+
excludeSkillNames: this.excludeSkillNames,
|
|
687
|
+
referencedSkillNames: this.referencedSkillNames,
|
|
688
|
+
suppressedNames: new Set(gates.suppressed),
|
|
689
|
+
manageUnmanaged: this.manageUnmanaged,
|
|
690
|
+
pruneBuiltins: this.pruneBuiltins,
|
|
691
|
+
bundledNames
|
|
692
|
+
}, await this.protectedNameMap(), gates);
|
|
693
|
+
}
|
|
694
|
+
/** marker info (pinned/bundled/hub-installed) per skill, from the library list. */
|
|
695
|
+
async protectedNameMap() {
|
|
696
|
+
const map = /* @__PURE__ */ new Map();
|
|
697
|
+
for (const summary of await this.skills.list()) if (summary.protectedBy !== null) map.set(summary.name, summary.protectedBy);
|
|
698
|
+
return map;
|
|
699
|
+
}
|
|
700
|
+
/**
|
|
251
701
|
* Control-plane consolidation: merge source skill bodies into `target`,
|
|
252
702
|
* archive the sources with an absorbed-into marker, and fold their usage
|
|
253
703
|
* records into `archived` state. Snapshot-then-mutate, never a hard delete.
|
|
254
704
|
*/
|
|
255
705
|
async consolidate(target, sources) {
|
|
256
|
-
const
|
|
706
|
+
const suppressedNames = new Set(await loadSuppressedNames(this.skills.root, this.io));
|
|
707
|
+
const gates = new EvolutionGateSet({
|
|
708
|
+
exclude: this.excludeSkillNames,
|
|
709
|
+
referenced: this.referencedSkillNames,
|
|
710
|
+
suppressed: suppressedNames
|
|
711
|
+
});
|
|
712
|
+
const blocked = [...new Set([target, ...sources])].filter((name) => gates.isBlocked(name));
|
|
257
713
|
if (blocked.length > 0) return {
|
|
258
714
|
ok: false,
|
|
259
|
-
message: `Skill(s)
|
|
715
|
+
message: `Skill(s) protected from consolidation (excluded / referenced / suppressed / protected builtin): ${blocked.join(", ")}`
|
|
260
716
|
};
|
|
261
|
-
await this.
|
|
717
|
+
await this.snapshotFull("pre-consolidate");
|
|
262
718
|
const result = await this.skills.consolidate(target, sources);
|
|
263
719
|
if (!result.ok) return result;
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
720
|
+
await mutateUsage(this.skills.root, this.io, (disk) => {
|
|
721
|
+
for (const source of sources) {
|
|
722
|
+
const record = disk.get(source);
|
|
723
|
+
if (record) {
|
|
724
|
+
record.state = "archived";
|
|
725
|
+
record.archived_at = (/* @__PURE__ */ new Date()).toISOString();
|
|
726
|
+
}
|
|
727
|
+
}
|
|
728
|
+
});
|
|
270
729
|
return result;
|
|
271
730
|
}
|
|
272
731
|
/**
|
|
@@ -274,15 +733,25 @@ var EvolutionCurator = class extends Service {
|
|
|
274
733
|
* and reset its usage state, keeping the recoverable-archive invariant.
|
|
275
734
|
*/
|
|
276
735
|
async restore(name) {
|
|
277
|
-
await this.
|
|
736
|
+
await this.snapshotFull("pre-restore");
|
|
278
737
|
const result = await this.skills.restoreFromArchive(name);
|
|
279
738
|
if (!result.ok) return result;
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
739
|
+
await mutateUsage(this.skills.root, this.io, (disk) => {
|
|
740
|
+
const record = disk.get(name);
|
|
741
|
+
if (record) {
|
|
742
|
+
record.state = "active";
|
|
743
|
+
record.archived_at = null;
|
|
744
|
+
}
|
|
745
|
+
});
|
|
746
|
+
if (new Set(await loadSuppressedNames(this.skills.root, this.io)).has(name)) try {
|
|
747
|
+
await updateSuppressedNames(this.skills.root, this.io, (current) => {
|
|
748
|
+
current.delete(name);
|
|
749
|
+
});
|
|
750
|
+
} catch {
|
|
751
|
+
this.ctx.logger.warn(`evolution-curator: failed to persist suppressed names after restoring ${name}`);
|
|
752
|
+
}
|
|
284
753
|
return result;
|
|
285
754
|
}
|
|
286
755
|
};
|
|
287
756
|
//#endregion
|
|
288
|
-
export { EvolutionCurator, EvolutionCurator as default };
|
|
757
|
+
export { EvolutionCurator, EvolutionCurator as default, gateConsolidations };
|
package/lib/types/index.d.ts
CHANGED
|
@@ -4,8 +4,8 @@
|
|
|
4
4
|
*/
|
|
5
5
|
import { Context, Service } from '@deepseek-ai/cordis';
|
|
6
6
|
import type Schema from '@deepseek-ai/schemastery';
|
|
7
|
-
import { SkillLibrary } from '@deepseek-ai/dsh-evolution-core';
|
|
8
|
-
import { type CuratorRunReport, type SkillActionResult } from '@deepseek-ai/dsh-evolution-core';
|
|
7
|
+
import { EvolutionGateSet, SkillLibrary } from '@deepseek-ai/dsh-evolution-core';
|
|
8
|
+
import { type CuratorConsolidation, type CuratorNominations, type CuratorRunReport, type ScopeView, type SkillActionResult } from '@deepseek-ai/dsh-evolution-core';
|
|
9
9
|
declare module '@deepseek-ai/cordis' {
|
|
10
10
|
interface Context {
|
|
11
11
|
evolutionCurator: EvolutionCurator;
|
|
@@ -27,9 +27,46 @@ export interface Config {
|
|
|
27
27
|
excludeSkillNames?: string[];
|
|
28
28
|
/** Include usage records whose created_by is not 'agent' in lifecycle decisions. */
|
|
29
29
|
manageUnmanaged?: boolean;
|
|
30
|
+
/** Archive long-unused bundled skills too (with suppression against re-seeds). */
|
|
31
|
+
pruneBuiltins?: boolean;
|
|
32
|
+
/** Static scheduled-task skill references; such skills never auto-transition. */
|
|
33
|
+
referencedSkillNames?: string[];
|
|
34
|
+
/** Start the interval timer on context ready (auto-curation). Default true. */
|
|
35
|
+
autoStart?: boolean;
|
|
36
|
+
/** Seconds between host boot and the first automatic schedule check (restart catch-up). */
|
|
37
|
+
bootGraceSeconds?: number;
|
|
30
38
|
/** Max tokens for the optional LLM nomination pass. */
|
|
31
39
|
curatorReviewMaxTokens?: number;
|
|
32
40
|
}
|
|
41
|
+
/** Outcome of one curator run pass. */
|
|
42
|
+
export interface CuratorRunOutcome {
|
|
43
|
+
stale: string[];
|
|
44
|
+
archived: string[];
|
|
45
|
+
errors: string[];
|
|
46
|
+
report: CuratorRunReport;
|
|
47
|
+
skipped?: string;
|
|
48
|
+
/** LLM nominations when the optional review pass is enabled (audit visibility). */
|
|
49
|
+
nominations?: CuratorNominations;
|
|
50
|
+
}
|
|
51
|
+
/** Persisted curator-state record shape (schemaVersion optional for legacy reads). */
|
|
52
|
+
export interface CuratorStateRecordShape {
|
|
53
|
+
schemaVersion?: number;
|
|
54
|
+
lastRunAt: number;
|
|
55
|
+
runCount: number;
|
|
56
|
+
lastSummary: string;
|
|
57
|
+
paused: boolean;
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Block LLM-nominated consolidations that would touch a gate-protected name:
|
|
61
|
+
* exclude / referenced / suppressed skills must never merge (neither as the
|
|
62
|
+
* source being archived nor as the umbrella being edited). Mirrors the control
|
|
63
|
+
* plane's `consolidate()` guard; automatic nominations must pass the same gate.
|
|
64
|
+
*/
|
|
65
|
+
export declare function gateConsolidations(consolidations: CuratorConsolidation[], gates: EvolutionGateSet | {
|
|
66
|
+
exclude?: ReadonlySet<string>;
|
|
67
|
+
referenced?: ReadonlySet<string>;
|
|
68
|
+
suppressed?: ReadonlySet<string>;
|
|
69
|
+
}): CuratorConsolidation[];
|
|
33
70
|
export declare class EvolutionCurator extends Service {
|
|
34
71
|
static inject: string[];
|
|
35
72
|
static Config: Schema<Config>;
|
|
@@ -45,30 +82,127 @@ export declare class EvolutionCurator extends Service {
|
|
|
45
82
|
private readonly minIdleHours;
|
|
46
83
|
private readonly excludeSkillNames;
|
|
47
84
|
private readonly manageUnmanaged;
|
|
85
|
+
private readonly pruneBuiltins;
|
|
86
|
+
private readonly referencedSkillNames;
|
|
87
|
+
private readonly bootGraceSeconds;
|
|
48
88
|
private readonly curatorReviewMaxTokens;
|
|
49
89
|
private lastRun;
|
|
50
90
|
private timer;
|
|
91
|
+
private bootCheck;
|
|
92
|
+
private running;
|
|
51
93
|
constructor(ctx: Context, config?: Config);
|
|
52
94
|
private lifecycle;
|
|
53
95
|
start(): void;
|
|
54
96
|
stop(): void;
|
|
55
97
|
/**
|
|
56
|
-
*
|
|
57
|
-
*
|
|
58
|
-
*
|
|
59
|
-
*
|
|
98
|
+
* Pause or resume automatic curation (B-line G2, Hermes `set_paused`
|
|
99
|
+
* parity): the flag is persisted on the curator state record and the
|
|
100
|
+
* `run()` paused gate skips automatic passes while it holds. Manual runs
|
|
101
|
+
* (`ignoreGates`) are unaffected — pause is a soft stop for the scheduler,
|
|
102
|
+
* not a lock on the operator.
|
|
103
|
+
*
|
|
104
|
+
* Pausing on a state-less curator state seeds the record with `lastRunAt:
|
|
105
|
+
* now`, so a later resume re-enters through the interval gate and defers a
|
|
106
|
+
* full cycle instead of firing immediately (first-run defer interaction,
|
|
107
|
+
* kept deliberately: an unattended resume must not auto-run mid-boot).
|
|
60
108
|
*/
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
109
|
+
setPaused(paused: boolean): Promise<void>;
|
|
110
|
+
/** Current persisted curator state (read-only view for /evolution curator status). */
|
|
111
|
+
status(): Promise<CuratorStateRecordShape | null>;
|
|
112
|
+
/**
|
|
113
|
+
* One automatic schedule check: run a pass when the persisted curator state
|
|
114
|
+
* (falling back to the in-memory clock for state-less compositions) is at
|
|
115
|
+
* least one interval old. All gates — interval, idle, first-run defer,
|
|
116
|
+
* reentrancy — stay inside `run()`, so this method only decides whether to
|
|
117
|
+
* wake it, and never duplicates gate logic.
|
|
118
|
+
*/
|
|
119
|
+
private autoCheck;
|
|
120
|
+
/**
|
|
121
|
+
* Optional Hermes-curator LLM pass. The model may only NOMINATE pruning and
|
|
122
|
+
* consolidation; every move stays a control-plane operation and each
|
|
123
|
+
* nomination is re-validated against the tree and protected markers before
|
|
124
|
+
* any file move. `dryRun` prepends the report-only banner.
|
|
125
|
+
*/
|
|
126
|
+
recommend(candidates: string[], options?: {
|
|
127
|
+
dryRun?: boolean;
|
|
128
|
+
}): Promise<CuratorNominations>;
|
|
129
|
+
/** Optional curator-state service (evolution-state-json / storage-domain). */
|
|
130
|
+
private curatorStateService;
|
|
131
|
+
/**
|
|
132
|
+
* Full-state snapshot: the skills tree plus the current curator state as an
|
|
133
|
+
* `extras/curator-state.json` side file. Every pre-mutation snapshot in the
|
|
134
|
+
* curator goes through here so a later `restoreSnapshot()` can rewind both
|
|
135
|
+
* the tree and the state (Hermes curator_backup backs up `.curator_state`).
|
|
136
|
+
*/
|
|
137
|
+
snapshotFull(reason?: string): Promise<string>;
|
|
138
|
+
/**
|
|
139
|
+
* Full-state rollback: restore the latest snapshot's tree/sidecars/archive
|
|
140
|
+
* AND the curator state it carried. The pre-rollback safety snapshot keeps
|
|
141
|
+
* the current tree plus current state (as extras), so the rollback itself
|
|
142
|
+
* is reversible.
|
|
143
|
+
*/
|
|
144
|
+
restoreSnapshot(): Promise<SkillActionResult & {
|
|
145
|
+
extras?: Array<{
|
|
146
|
+
name: string;
|
|
147
|
+
content: string;
|
|
148
|
+
}>;
|
|
69
149
|
}>;
|
|
150
|
+
private skippedReport;
|
|
151
|
+
/**
|
|
152
|
+
* Run one curator pass. `ignoreGates` skips the interval and idle gates so an
|
|
153
|
+
* explicit `/evolution curator run` always executes (manual-run semantics):
|
|
154
|
+
* `dryRun` computes the lifecycle and the LLM nominations but performs no
|
|
155
|
+
* mutation, reports what WOULD happen, and does not push out the next run.
|
|
156
|
+
* Reentrant calls (autoStart timer + manual command at the same instant) are
|
|
157
|
+
* skipped with an explicit `already-running` outcome.
|
|
158
|
+
*/
|
|
159
|
+
run(options?: {
|
|
160
|
+
ignoreGates?: boolean;
|
|
161
|
+
dryRun?: boolean;
|
|
162
|
+
}): Promise<CuratorRunOutcome>;
|
|
163
|
+
private runCore;
|
|
164
|
+
/**
|
|
165
|
+
* Seed baseline records for tree skills the sidecar has not seen yet, so
|
|
166
|
+
* their inactivity clock starts now (first-sight defer) and bundled skills
|
|
167
|
+
* become known candidates only when prune-builtins opts them in. Also
|
|
168
|
+
* returns the full active tree names for nomination validation.
|
|
169
|
+
*/
|
|
170
|
+
private seedBaseline;
|
|
171
|
+
/**
|
|
172
|
+
* F13 six-factor quality scoring, persisted onto the usage records.
|
|
173
|
+
*/
|
|
174
|
+
private scoreTree;
|
|
175
|
+
/**
|
|
176
|
+
* In-degree over explicit `related_skills` frontmatter references (the DSH
|
|
177
|
+
* equivalent of the graph-in-degree references factor): a skill listing
|
|
178
|
+
* other skill names counts as one reference to each of them, so hub skills
|
|
179
|
+
* that are explicitly named by peers get a non-zero references factor.
|
|
180
|
+
*/
|
|
181
|
+
private referenceCounts;
|
|
182
|
+
/**
|
|
183
|
+
* Execute lifecycle archives and consolidation nominations, then persist the
|
|
184
|
+
* suppression and usage sidecars best-effort. A dry-run short-circuits: no
|
|
185
|
+
* file moves and no state persistence — the caller still writes the report.
|
|
186
|
+
*/
|
|
187
|
+
private applyMutations;
|
|
70
188
|
private recentSessionActive;
|
|
189
|
+
/**
|
|
190
|
+
* Keep only the newest N curator reports, ordered by the report's own
|
|
191
|
+
* `startedAt` (the runId is a UUID and cannot order history). Best-effort
|
|
192
|
+
* like `retainSnapshots`: a failed removal must not fail the run that just
|
|
193
|
+
* persisted its report. The paired `.md` digest is pruned with its JSON.
|
|
194
|
+
*/
|
|
195
|
+
private retainReports;
|
|
71
196
|
latestReport(): Promise<CuratorRunReport | null>;
|
|
197
|
+
/**
|
|
198
|
+
* Read-only lifecycle scope classification: which skills are in scope,
|
|
199
|
+
* watched (stale/quality-warned), exempted, or protected. Uses the same
|
|
200
|
+
* candidate gate as `run()` (`computeScopeView` / `lifecycleCandidate`),
|
|
201
|
+
* so the view always predicts what a curator pass may touch.
|
|
202
|
+
*/
|
|
203
|
+
scopeView(): Promise<ScopeView>;
|
|
204
|
+
/** marker info (pinned/bundled/hub-installed) per skill, from the library list. */
|
|
205
|
+
private protectedNameMap;
|
|
72
206
|
/**
|
|
73
207
|
* Control-plane consolidation: merge source skill bodies into `target`,
|
|
74
208
|
* archive the sources with an absorbed-into marker, and fold their usage
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lmzhen/dsh-evolution-curator",
|
|
3
3
|
"description": "Deterministic skill lifecycle and recovery (community build)",
|
|
4
|
-
"version": "0.1.0
|
|
4
|
+
"version": "0.1.0",
|
|
5
5
|
"publishConfig": {
|
|
6
6
|
"access": "public"
|
|
7
7
|
},
|
|
@@ -33,20 +33,20 @@
|
|
|
33
33
|
"license": "MIT",
|
|
34
34
|
"dependencies": {
|
|
35
35
|
"@deepseek-ai/schemastery": "^3.18.1",
|
|
36
|
-
"@lmzhen/dsh-evolution-core": "^0.1.0
|
|
36
|
+
"@lmzhen/dsh-evolution-core": "^0.1.0"
|
|
37
37
|
},
|
|
38
38
|
"peerDependencies": {
|
|
39
39
|
"@deepseek-ai/cordis": "^4.0.1",
|
|
40
|
-
"@deepseek-ai/dsh-invariants": "^0.1.
|
|
41
|
-
"@deepseek-ai/dsh-llm": "^0.1.
|
|
42
|
-
"@lmzhen/dsh-evolution-io": "^0.1.0
|
|
43
|
-
"@lmzhen/dsh-evolution-state": "^0.1.0
|
|
40
|
+
"@deepseek-ai/dsh-invariants": "^0.1.1-rc.2",
|
|
41
|
+
"@deepseek-ai/dsh-llm": "^0.1.1-rc.2",
|
|
42
|
+
"@lmzhen/dsh-evolution-io": "^0.1.0",
|
|
43
|
+
"@lmzhen/dsh-evolution-state": "^0.1.0"
|
|
44
44
|
},
|
|
45
45
|
"devDependencies": {
|
|
46
|
-
"@deepseek-ai/dsh-invariants": "^0.1.
|
|
47
|
-
"@deepseek-ai/dsh-llm": "^0.1.
|
|
48
|
-
"@lmzhen/dsh-evolution-core": "^0.1.0
|
|
49
|
-
"@lmzhen/dsh-evolution-io": "^0.1.0
|
|
50
|
-
"@lmzhen/dsh-evolution-state": "^0.1.0
|
|
46
|
+
"@deepseek-ai/dsh-invariants": "^0.1.1-rc.2",
|
|
47
|
+
"@deepseek-ai/dsh-llm": "^0.1.1-rc.2",
|
|
48
|
+
"@lmzhen/dsh-evolution-core": "^0.1.0",
|
|
49
|
+
"@lmzhen/dsh-evolution-io": "^0.1.0",
|
|
50
|
+
"@lmzhen/dsh-evolution-state": "^0.1.0"
|
|
51
51
|
}
|
|
52
52
|
}
|