@senpi/runtime 1.1.0-dev.runtime-phase-2.20260512102629 → 1.1.0-dev.runtime-phase-2.20260514134437

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/dist/cli/senpi-cli-config.d.ts +15 -1
  2. package/dist/cli/senpi-cli-config.d.ts.map +1 -1
  3. package/dist/cli/senpi-cli-config.js +19 -2
  4. package/dist/cli/senpi-cli-config.js.map +1 -1
  5. package/dist/cli/senpi-commands.d.ts.map +1 -1
  6. package/dist/cli/senpi-commands.js +96 -0
  7. package/dist/cli/senpi-commands.js.map +1 -1
  8. package/dist/index.d.ts +21 -0
  9. package/dist/index.d.ts.map +1 -1
  10. package/dist/index.js +84 -1
  11. package/dist/index.js.map +1 -1
  12. package/dist/runtime/auto-update/coordinator.d.ts +13 -0
  13. package/dist/runtime/auto-update/coordinator.d.ts.map +1 -1
  14. package/dist/runtime/auto-update/coordinator.js +14 -0
  15. package/dist/runtime/auto-update/coordinator.js.map +1 -1
  16. package/dist/skills-manager/bootstrap.d.ts +26 -0
  17. package/dist/skills-manager/bootstrap.d.ts.map +1 -0
  18. package/dist/skills-manager/bootstrap.js +86 -0
  19. package/dist/skills-manager/bootstrap.js.map +1 -0
  20. package/dist/skills-manager/constants.d.ts +31 -0
  21. package/dist/skills-manager/constants.d.ts.map +1 -0
  22. package/dist/skills-manager/constants.js +40 -0
  23. package/dist/skills-manager/constants.js.map +1 -0
  24. package/dist/skills-manager/coordinator.d.ts +336 -0
  25. package/dist/skills-manager/coordinator.d.ts.map +1 -0
  26. package/dist/skills-manager/coordinator.js +931 -0
  27. package/dist/skills-manager/coordinator.js.map +1 -0
  28. package/dist/skills-manager/fetcher.d.ts +28 -0
  29. package/dist/skills-manager/fetcher.d.ts.map +1 -0
  30. package/dist/skills-manager/fetcher.js +92 -0
  31. package/dist/skills-manager/fetcher.js.map +1 -0
  32. package/dist/skills-manager/index.d.ts +5 -0
  33. package/dist/skills-manager/index.d.ts.map +1 -0
  34. package/dist/skills-manager/index.js +4 -0
  35. package/dist/skills-manager/index.js.map +1 -0
  36. package/dist/skills-manager/state-store.d.ts +57 -0
  37. package/dist/skills-manager/state-store.d.ts.map +1 -0
  38. package/dist/skills-manager/state-store.js +129 -0
  39. package/dist/skills-manager/state-store.js.map +1 -0
  40. package/dist/skills-manager/types.d.ts +165 -0
  41. package/dist/skills-manager/types.d.ts.map +1 -0
  42. package/dist/skills-manager/types.js +2 -0
  43. package/dist/skills-manager/types.js.map +1 -0
  44. package/dist/skills-manager/utils.d.ts +63 -0
  45. package/dist/skills-manager/utils.d.ts.map +1 -0
  46. package/dist/skills-manager/utils.js +119 -0
  47. package/dist/skills-manager/utils.js.map +1 -0
  48. package/dist/skills-manager/version-manager.d.ts +146 -0
  49. package/dist/skills-manager/version-manager.d.ts.map +1 -0
  50. package/dist/skills-manager/version-manager.js +299 -0
  51. package/dist/skills-manager/version-manager.js.map +1 -0
  52. package/dist/skills-manager/writer.d.ts +28 -0
  53. package/dist/skills-manager/writer.d.ts.map +1 -0
  54. package/dist/skills-manager/writer.js +101 -0
  55. package/dist/skills-manager/writer.js.map +1 -0
  56. package/openclaw.plugin.json +27 -0
  57. package/package.json +3 -1
@@ -0,0 +1,931 @@
1
+ /**
2
+ * Central lifecycle manager for Senpi skills auto-update.
3
+ *
4
+ * Mirrors AutoUpdateCoordinator from src/runtime/auto-update/coordinator.ts
5
+ * for thread-safety (runToken + stopped + running triple) and uses the same
6
+ * injectable-dependency pattern for testability.
7
+ *
8
+ * Scheduling: this coordinator does not own a timer. Ticks fire from
9
+ * outside — currently from auto-update's `onTickComplete` hook in
10
+ * `src/index.ts`, which calls {@link SkillsUpdateCoordinator.runTickOnce}
11
+ * after every auto-update cycle. Skills-manager therefore inherits the
12
+ * `autoUpdate.pollIntervalMinutes` cadence and the same failure-backoff
13
+ * cadence.
14
+ *
15
+ * On start(): load persisted state, bootstrap any missing skills, mark
16
+ * health as healthy. The first tick fires on the next external invocation
17
+ * of `runTickOnce()`.
18
+ *
19
+ * Each tick: resolve skill names (configured list or discovery), check
20
+ * remote versions in parallel, auto-apply patch/minor, notify on major
21
+ * (deduped by version), skip on none/unknown.
22
+ */
23
+ import { readdir } from "node:fs/promises";
24
+ import { bootstrapSkillsIfNeeded } from "./bootstrap.js";
25
+ import { cloneSkillsRepo } from "./fetcher.js";
26
+ import { SkillsManagerStateStore } from "./state-store.js";
27
+ import { checkSkillVersion } from "./version-manager.js";
28
+ import { installSkill } from "./writer.js";
29
+ import { SKILLS_RAW_BASE_URL, SKILLS_REPO_URL } from "./constants.js";
30
+ import { createDefaultSkillState, createDefaultSkillsManagerState, formatErr } from "./utils.js";
31
+ export class SkillsUpdateCoordinator {
32
+ options;
33
+ store;
34
+ operationChain = Promise.resolve();
35
+ stopped = true;
36
+ runToken = 0;
37
+ state = createDefaultSkillsManagerState();
38
+ snapshot;
39
+ /** Latest remote version per skill name — populated during ticks. */
40
+ latestVersions = new Map();
41
+ /**
42
+ * Local (pre-install) version per skill name — populated during ticks
43
+ * and manual RPC paths from `SkillVersionInfo.localVersion`. Used by the
44
+ * update-summary and major-available notifications to render the
45
+ * `prev → new` transition. Captured *before* the install runs so the
46
+ * value still reflects the on-disk version at the time the user chose to
47
+ * update; reading `state.skills[name].installedVersion` instead would
48
+ * surface the *post-install* version (recorded by `recordSuccess`) and
49
+ * collapse the transition to `vX -> vX`.
50
+ */
51
+ previousVersions = new Map();
52
+ /**
53
+ * Cached short descriptions parsed from each skill's **remote** SKILL.md
54
+ * frontmatter — i.e. the description for the upcoming/current remote
55
+ * version, not whatever's installed locally. Used to enrich
56
+ * update-summary and major-available notifications with a one-line
57
+ * "About:" so the user gets context for the version the message is
58
+ * actually announcing.
59
+ *
60
+ * Populated during tick / updateSkill / updateAll alongside
61
+ * `latestVersions`; absent / null entries simply omit the line from the
62
+ * notification.
63
+ *
64
+ * Using the remote description (rather than the local one) keeps the
65
+ * notification description in sync with the version number it sits next
66
+ * to — e.g. when notifying about a major bump v1 → v2, the "About:" line
67
+ * reflects the v2 description, even if the v1 local copy on disk is
68
+ * stale or worded differently.
69
+ */
70
+ skillDescriptions = new Map();
71
+ constructor(options) {
72
+ this.options = options;
73
+ this.store = new SkillsManagerStateStore(options.stateDir, options.config.skillsDir, options.logger);
74
+ this.snapshot = this.buildSnapshot("disabled", "not-started");
75
+ }
76
+ /**
77
+ * Load persisted state and bootstrap missing skills. Does **not** schedule
78
+ * a poll loop — skills-manager runs off the auto-update coordinator's
79
+ * `onTickComplete` hook (see `src/index.ts`), which invokes
80
+ * {@link runTickOnce} on whatever cadence auto-update is configured with.
81
+ *
82
+ * Calling `start()` is still required even in the externally-scheduled
83
+ * mode so bootstrap, state load, and the "ready" snapshot all happen
84
+ * before the first external tick fires.
85
+ */
86
+ async start() {
87
+ this.runToken += 1;
88
+ this.stopped = false;
89
+ const { logger, config } = this.options;
90
+ if (!config.enabled) {
91
+ this.stopped = true;
92
+ this.snapshot = this.buildSnapshot("disabled", "skills-manager-disabled");
93
+ logger.info("[senpi-skills-manager] disabled by config");
94
+ return;
95
+ }
96
+ logger.info(`[senpi-skills-manager] starting | skillsDir=${config.skillsDir.join(",")} skills=${config.skills.join(",") || "(discover)"} cadence=external (driven by auto-update)`);
97
+ this.state = await this.store.load();
98
+ const bootstrapFn = this.options.deps?.bootstrapSkillsIfNeeded ?? bootstrapSkillsIfNeeded;
99
+ try {
100
+ await bootstrapFn(config, logger);
101
+ }
102
+ catch (err) {
103
+ logger.warn(`[senpi-skills-manager] bootstrap error (non-fatal): ${formatErr(err)}`);
104
+ }
105
+ this.snapshot = this.buildSnapshot("healthy", "started");
106
+ }
107
+ /**
108
+ * Stop the coordinator: prevent any new ticks from being processed, and
109
+ * wait for any in-flight tick or manual RPC to finish so the caller can
110
+ * rely on no async work still touching state after `stop()` resolves.
111
+ *
112
+ * Since scheduling is now external (auto-update's `onTickComplete` hook),
113
+ * there's no internal timer to cancel — `stop()` just flips the `stopped`
114
+ * flag (which `runTickOnce` checks) and drains the serialised operation
115
+ * queue. The auto-update hook itself becomes a no-op for stopped
116
+ * coordinators since `runTickOnce` returns early.
117
+ */
118
+ async stop() {
119
+ this.runToken += 1;
120
+ this.stopped = true;
121
+ const inFlight = this.operationChain;
122
+ this.options.logger.info("[senpi-skills-manager] stop requested — draining in-flight operations");
123
+ // operationChain never rejects (runSerialized catches via try/finally before
124
+ // releasing the queue), so this await always resolves.
125
+ await inFlight;
126
+ this.options.logger.info("[senpi-skills-manager] stopped");
127
+ }
128
+ /**
129
+ * Public one-shot tick entry point. Called externally on whatever cadence
130
+ * the host wires up — currently from the auto-update coordinator's
131
+ * `onTickComplete` hook in `src/index.ts`, which fires after each
132
+ * auto-update version check completes (success or failure).
133
+ *
134
+ * Replaces the previous internal `tick()` + `scheduleNext()` pair: the
135
+ * coordinator no longer owns a timer of its own. Manual RPCs
136
+ * (`senpi.skills.update`, `senpi.skills.updateAll`) remain independent of
137
+ * this path.
138
+ *
139
+ * Returns early as a no-op when:
140
+ * - The coordinator has been stopped (e.g. plugin teardown).
141
+ * - The runToken has rolled (e.g. a stop/start cycle invalidated this call).
142
+ * - The coordinator was disabled at start time (config.enabled === false).
143
+ *
144
+ * Tick errors are logged + recorded on the snapshot but never thrown —
145
+ * the caller (auto-update) must not have its own scheduling disturbed by
146
+ * a transient skills-manager failure.
147
+ */
148
+ async runTickOnce() {
149
+ const token = this.runToken;
150
+ if (this.stopped || !this.options.config.enabled)
151
+ return;
152
+ await this.runSerialized("tick", async () => {
153
+ if (this.stopped || token !== this.runToken)
154
+ return;
155
+ this.options.logger.info("[senpi-skills-manager] tick started (external trigger)");
156
+ try {
157
+ await this.runTick();
158
+ await this.persistState();
159
+ this.snapshot = this.buildSnapshot("healthy", "tick-complete");
160
+ }
161
+ catch (err) {
162
+ this.options.logger.warn(`[senpi-skills-manager] tick error: ${formatErr(err)}`);
163
+ this.snapshot = this.buildSnapshot("degraded", "tick-error", formatErr(err));
164
+ // No internal backoff — the next external tick (from auto-update's
165
+ // own poll loop / backoff) will retry on its own cadence.
166
+ }
167
+ });
168
+ }
169
+ /** Return the latest point-in-time snapshot for gateway RPCs. */
170
+ getSnapshot() {
171
+ return this.snapshot;
172
+ }
173
+ // ── Manual trigger methods (called by gateway RPCs) ────────────────────────
174
+ /**
175
+ * Force an immediate version check and apply for one named skill.
176
+ *
177
+ * Skips installation when the update kind is `"none"` (already current) or
178
+ * `"unknown"` (remote version could not be classified — e.g. the fetch
179
+ * failed or the remote `version` field is missing). Falling through on
180
+ * `"unknown"` would write `installedVersion: null` and lose tracking, so we
181
+ * treat it the same as `"none"` and return `updated: false`.
182
+ *
183
+ * @throws On network or install error so the gateway RPC can return ok=false.
184
+ */
185
+ async updateSkill(skillName) {
186
+ return this.runSerialized("updateSkill", async () => {
187
+ const { logger } = this.options;
188
+ logger.info(`[senpi-skills-manager] updateSkill invoked | skill=${skillName}`);
189
+ const checkVersionFn = this.resolveCheckFn();
190
+ let versionInfo;
191
+ try {
192
+ versionInfo = await checkVersionFn(this.options.config.skillsDir, skillName, SKILLS_RAW_BASE_URL, logger);
193
+ }
194
+ catch (err) {
195
+ // Version check threw (5xx, network error, timeout, body-parse failure
196
+ // — all now propagate from checkSkillVersion after the version-manager
197
+ // re-throw fix). Mirror the tick/updateAll paths and record the
198
+ // failure on this skill's state before rethrowing so the gateway RPC
199
+ // still returns ok=false to the caller.
200
+ const errorMessage = formatErr(err);
201
+ logger.warn(`[senpi-skills-manager] updateSkill — version check failed | skill=${skillName} err=${errorMessage}`);
202
+ this.recordCheckFailure(skillName, errorMessage);
203
+ await this.persistState();
204
+ this.snapshot = this.buildSnapshot(this.snapshot.health, "manual-update-failed", errorMessage);
205
+ throw err;
206
+ }
207
+ // Record the remote version we just learned so the snapshot's latestVersion
208
+ // field reflects it on the next getSnapshot() call — even when no install
209
+ // happens (skip paths below). Local description is cached alongside so
210
+ // notifications (sendUpdateSummary / handleMajorAvailable) can include it.
211
+ this.latestVersions.set(skillName, versionInfo.remoteVersion);
212
+ this.previousVersions.set(skillName, versionInfo.localVersion);
213
+ this.skillDescriptions.set(skillName, versionInfo.remoteDescription ?? null);
214
+ // Mirror runTick: every skill whose version we just checked gets its
215
+ // `lastCheckedAt` updated (and `installedVersion` refreshed from the local
216
+ // read) regardless of whether it proceeds to install. Without this, skills
217
+ // updated only via manual RPCs would show `lastCheckedAt: null` in the
218
+ // status snapshot until the next automatic tick fires (up to 60 min away).
219
+ const checkedState = this.state.skills[skillName] ?? createDefaultSkillState(skillName);
220
+ checkedState.lastCheckedAt = new Date().toISOString();
221
+ if (versionInfo.localVersion !== null) {
222
+ checkedState.installedVersion = versionInfo.localVersion;
223
+ }
224
+ // NOTE: do NOT clear failure state here. See runTick for rationale —
225
+ // a successful version check is not proof of operational health. Failure
226
+ // counters are only reset by `recordSuccess` after a successful install.
227
+ this.state.skills[skillName] = checkedState;
228
+ logger.info(`[senpi-skills-manager] updateSkill check result | skill=${skillName} local=${versionInfo.localVersion ?? "none"} remote=${versionInfo.remoteVersion ?? "unknown"} kind=${versionInfo.updateKind}`);
229
+ if (versionInfo.updateKind === "none" || versionInfo.updateKind === "unknown") {
230
+ logger.info(`[senpi-skills-manager] updateSkill skipped | skill=${skillName} reason=${versionInfo.updateKind}`);
231
+ // Persist so the `lastCheckedAt` timestamp survives a gateway restart
232
+ // even on skip paths (otherwise the next load() would see a stale null).
233
+ await this.persistState();
234
+ // Refresh snapshot so the status RPC doesn't return pre-check data.
235
+ this.snapshot = this.buildSnapshot(this.snapshot.health, "manual-update-skipped");
236
+ return { updated: false, version: versionInfo.localVersion };
237
+ }
238
+ try {
239
+ const installedVersion = await this.applyUpdate(skillName, versionInfo.remoteVersion);
240
+ logger.info(`[senpi-skills-manager] updateSkill complete | skill=${skillName} version=${installedVersion ?? "unknown"}`);
241
+ // Refresh snapshot so the status RPC reflects the freshly-installed version
242
+ // immediately, rather than waiting for the next poll tick (up to 60 min).
243
+ this.snapshot = this.buildSnapshot("healthy", "manual-update-complete");
244
+ return { updated: true, version: installedVersion };
245
+ }
246
+ catch (err) {
247
+ const errorMessage = formatErr(err);
248
+ // applyUpdate has already recorded per-skill failure state (consecutiveFailures,
249
+ // lastFailureAt, lastFailureReason) and persisted before throwing. We repeat
250
+ // persistState() here as a defensive backstop in case applyUpdate's internal
251
+ // persist silently failed, and also so the updated lastCheckedAt we set
252
+ // earlier in this method is guaranteed to reach disk on the error path.
253
+ await this.persistState();
254
+ this.snapshot = this.buildSnapshot(this.snapshot.health, "manual-update-failed", errorMessage);
255
+ throw err;
256
+ }
257
+ });
258
+ }
259
+ /**
260
+ * Force an immediate version check and apply for all discovered/configured skills.
261
+ * Individual failures do not abort the remaining skills.
262
+ *
263
+ * All skills share a single `git clone` — the repo is cloned once, every
264
+ * skill that needs an update is installed from that same checkout, then the
265
+ * checkout is cleaned up. A previous version called `updateSkill` in a loop,
266
+ * which caused one full clone per skill (N redundant clones for N skills);
267
+ * this mirrors the tick path's batching instead.
268
+ */
269
+ async updateAll() {
270
+ return this.runSerialized("updateAll", async () => {
271
+ const { logger, config } = this.options;
272
+ logger.info("[senpi-skills-manager] updateAll invoked");
273
+ const skillNames = await this.resolveSkillNames();
274
+ if (skillNames.length === 0) {
275
+ logger.info("[senpi-skills-manager] updateAll — no skills to check");
276
+ return [];
277
+ }
278
+ logger.info(`[senpi-skills-manager] updateAll — checking versions | skills=${skillNames.join(",")}`);
279
+ const checkVersionFn = this.resolveCheckFn();
280
+ // Check every skill's version in parallel — one rejection does not abort others.
281
+ const versionChecks = await Promise.allSettled(skillNames.map(async (skillName) => {
282
+ const versionInfo = await checkVersionFn(config.skillsDir, skillName, SKILLS_RAW_BASE_URL, logger);
283
+ this.latestVersions.set(skillName, versionInfo.remoteVersion);
284
+ this.previousVersions.set(skillName, versionInfo.localVersion);
285
+ this.skillDescriptions.set(skillName, versionInfo.remoteDescription ?? null);
286
+ return { name: skillName, ...versionInfo };
287
+ }));
288
+ const results = [];
289
+ const skillsToInstall = [];
290
+ for (let index = 0; index < versionChecks.length; index++) {
291
+ const skillName = skillNames[index];
292
+ const checkResult = versionChecks[index];
293
+ if (checkResult.status === "rejected") {
294
+ const errorMessage = formatErr(checkResult.reason);
295
+ logger.warn(`[senpi-skills-manager] updateAll — version check failed | skill=${skillName} err=${errorMessage}`);
296
+ // Mirror runTick: rejected checks update `lastCheckedAt`, bump the
297
+ // failure counter, and capture the reason. Otherwise a manual
298
+ // updateAll run could swallow a per-skill check failure entirely —
299
+ // the caller sees `error` in the returned array, but the snapshot
300
+ // and persisted state never reflect it.
301
+ this.recordCheckFailure(skillName, errorMessage);
302
+ results.push({ name: skillName, updated: false, version: null, error: errorMessage });
303
+ continue;
304
+ }
305
+ const { localVersion, updateKind } = checkResult.value;
306
+ // Mirror runTick: every successfully-checked skill gets `lastCheckedAt`
307
+ // updated and `installedVersion` refreshed from the local read, whether
308
+ // or not it proceeds to install. Otherwise skills touched only by
309
+ // manual RPCs would show `lastCheckedAt: null` in the status snapshot
310
+ // until the next automatic tick.
311
+ const skillState = this.state.skills[skillName] ?? createDefaultSkillState(skillName);
312
+ skillState.lastCheckedAt = new Date().toISOString();
313
+ if (localVersion !== null)
314
+ skillState.installedVersion = localVersion;
315
+ // NOTE: do NOT clear failure state here. See runTick for rationale —
316
+ // a successful version check is not proof of operational health.
317
+ // Failure counters are only reset by `recordSuccess` after a
318
+ // successful install.
319
+ this.state.skills[skillName] = skillState;
320
+ // Same skip policy as updateSkill: "none" and "unknown" leave the skill alone.
321
+ if (updateKind === "none" || updateKind === "unknown") {
322
+ logger.info(`[senpi-skills-manager] updateAll — skipping | skill=${skillName} reason=${updateKind}`);
323
+ results.push({ name: skillName, updated: false, version: localVersion });
324
+ continue;
325
+ }
326
+ skillsToInstall.push(skillName);
327
+ }
328
+ if (skillsToInstall.length === 0) {
329
+ logger.info(`[senpi-skills-manager] updateAll complete — no installs needed | checked=${skillNames.length}`);
330
+ // Persist so the `lastCheckedAt` timestamps we just set on every
331
+ // successfully-checked skill survive a gateway restart.
332
+ await this.persistState();
333
+ // No installs, but we may have learned new remote versions from the
334
+ // parallel checks above — refresh the snapshot so getSnapshot() doesn't
335
+ // return pre-check data.
336
+ this.snapshot = this.buildSnapshot(this.snapshot.health, "manual-update-skipped");
337
+ return results;
338
+ }
339
+ logger.info(`[senpi-skills-manager] updateAll — installing | count=${skillsToInstall.length} skills=${skillsToInstall.join(",")}`);
340
+ // Single clone, install many.
341
+ let installOutcomes;
342
+ try {
343
+ installOutcomes = await this.cloneAndInstallMany(skillsToInstall);
344
+ }
345
+ catch (err) {
346
+ const errorMessage = `clone failed: ${formatErr(err)}`;
347
+ logger.warn(`[senpi-skills-manager] updateAll — ${errorMessage}`);
348
+ for (const skillName of skillsToInstall) {
349
+ results.push({ name: skillName, updated: false, version: null, error: errorMessage });
350
+ }
351
+ // Clone failure doesn't produce install outcomes per-skill, but every
352
+ // checked skill already had `lastCheckedAt` updated in-memory above.
353
+ // Persist so those timestamps survive a gateway restart.
354
+ await this.persistState();
355
+ this.snapshot = this.buildSnapshot(this.snapshot.health, "manual-update-clone-failed");
356
+ return results;
357
+ }
358
+ let successCount = 0;
359
+ let failureCount = 0;
360
+ for (const skillName of skillsToInstall) {
361
+ const outcome = this.processInstallOutcome(skillName, installOutcomes);
362
+ if (outcome.success) {
363
+ results.push({ name: skillName, updated: true, version: outcome.version });
364
+ successCount += 1;
365
+ }
366
+ else {
367
+ results.push({ name: skillName, updated: false, version: null, error: outcome.error });
368
+ failureCount += 1;
369
+ }
370
+ }
371
+ await this.persistState();
372
+ logger.info(`[senpi-skills-manager] updateAll complete | installed=${successCount} failed=${failureCount} checked=${skillNames.length}`);
373
+ // Refresh snapshot so the status RPC reflects the freshly-installed
374
+ // versions immediately instead of waiting for the next poll tick.
375
+ this.snapshot = this.buildSnapshot("healthy", "manual-update-complete");
376
+ return results;
377
+ });
378
+ }
379
+ /**
380
+ * Run coordinator work in a global critical section so periodic ticks and
381
+ * manual RPC updates never interleave at await points.
382
+ */
383
+ async runSerialized(operationName, operation) {
384
+ const queued = this.operationChain;
385
+ let releaseQueue;
386
+ this.operationChain = new Promise((resolve) => {
387
+ releaseQueue = resolve;
388
+ });
389
+ await queued;
390
+ this.options.logger.info(`[senpi-skills-manager] runSerialized — entering critical section | op=${operationName}`);
391
+ try {
392
+ return await operation();
393
+ }
394
+ finally {
395
+ this.options.logger.info(`[senpi-skills-manager] runSerialized — leaving critical section | op=${operationName}`);
396
+ // Release the queue so the next caller can enter. We always release even
397
+ // if `operation` threw — otherwise a thrown error would deadlock every
398
+ // subsequent call forever.
399
+ releaseQueue?.();
400
+ }
401
+ }
402
+ /**
403
+ * Core tick logic: resolve skill names, check versions in parallel, apply
404
+ * policy per skill, then run a single clone for all skills needing update.
405
+ */
406
+ async runTick() {
407
+ const { logger, config } = this.options;
408
+ const skillNames = await this.resolveSkillNames();
409
+ if (skillNames.length === 0) {
410
+ logger.info("[senpi-skills-manager] tick — no skills to check");
411
+ return;
412
+ }
413
+ logger.info(`[senpi-skills-manager] tick — checking versions | count=${skillNames.length} skills=${skillNames.join(",")}`);
414
+ const checkVersionFn = this.resolveCheckFn();
415
+ // Check all versions in parallel — per-skill errors are captured, not thrown.
416
+ const versionChecks = await Promise.allSettled(skillNames.map(async (skillName) => {
417
+ const versionInfo = await checkVersionFn(config.skillsDir, skillName, SKILLS_RAW_BASE_URL, logger);
418
+ this.latestVersions.set(skillName, versionInfo.remoteVersion);
419
+ this.previousVersions.set(skillName, versionInfo.localVersion);
420
+ this.skillDescriptions.set(skillName, versionInfo.remoteDescription ?? null);
421
+ return { name: skillName, ...versionInfo };
422
+ }));
423
+ const skillsToInstall = [];
424
+ let majorPendingCount = 0;
425
+ let upToDateCount = 0;
426
+ for (let index = 0; index < versionChecks.length; index++) {
427
+ const skillName = skillNames[index];
428
+ const checkResult = versionChecks[index];
429
+ if (checkResult.status === "rejected") {
430
+ const errorMessage = formatErr(checkResult.reason);
431
+ this.recordCheckFailure(skillName, errorMessage);
432
+ logger.warn(`[senpi-skills-manager] tick — version check failed | skill=${skillName} err=${errorMessage}`);
433
+ continue;
434
+ }
435
+ const { localVersion, remoteVersion, updateKind } = checkResult.value;
436
+ const skillState = this.state.skills[skillName] ?? createDefaultSkillState(skillName);
437
+ skillState.lastCheckedAt = new Date().toISOString();
438
+ if (localVersion !== null)
439
+ skillState.installedVersion = localVersion;
440
+ // NOTE: do NOT clear failure state here. A successful version check does
441
+ // not prove the skill is operationally healthy — it only proves the raw
442
+ // SKILL.md is reachable. Install failures (clone, copy, swap) reflect
443
+ // real operational issues; clearing them on a check-success would wipe
444
+ // that history mid-tick and prevent consecutiveFailures from accumulating
445
+ // across multiple failed install attempts. Failure state is cleared only
446
+ // by `recordSuccess` (called after a successful install).
447
+ logger.info(`[senpi-skills-manager] tick — skill=${skillName} local=${localVersion ?? "none"} remote=${remoteVersion ?? "unknown"} kind=${updateKind}`);
448
+ if (updateKind === "none" || updateKind === "unknown") {
449
+ this.state.skills[skillName] = skillState;
450
+ upToDateCount += 1;
451
+ continue;
452
+ }
453
+ if (updateKind === "major") {
454
+ // Major versions are never auto-applied — notify the user and let them decide.
455
+ await this.handleMajorAvailable(skillState, skillName, remoteVersion);
456
+ this.state.skills[skillName] = skillState;
457
+ majorPendingCount += 1;
458
+ continue;
459
+ }
460
+ // patch / minor — queue for install
461
+ skillsToInstall.push(skillName);
462
+ this.state.skills[skillName] = skillState;
463
+ }
464
+ logger.info(`[senpi-skills-manager] tick — triage | upToDate=${upToDateCount} majorPending=${majorPendingCount} toInstall=${skillsToInstall.length}`);
465
+ if (skillsToInstall.length === 0)
466
+ return;
467
+ await this.applyUpdates(skillsToInstall);
468
+ }
469
+ /**
470
+ * Clone the repo once and install every skill in `skillNames`.
471
+ * Per-skill errors are recorded in state without aborting the others.
472
+ * The update summary notification distinguishes successful installs from
473
+ * failures so the user can see exactly which skills need attention.
474
+ *
475
+ * If the clone itself fails we log and return without touching state or
476
+ * sending a summary — a full-clone failure is almost always a transient
477
+ * network/git issue that affects every skill equally, so attributing it
478
+ * per-skill would be misleading. The next tick retries.
479
+ */
480
+ async applyUpdates(skillNames) {
481
+ const { logger } = this.options;
482
+ logger.info(`[senpi-skills-manager] applyUpdates — batch install starting | count=${skillNames.length} skills=${skillNames.join(",")}`);
483
+ let installOutcomes;
484
+ try {
485
+ installOutcomes = await this.cloneAndInstallMany(skillNames);
486
+ }
487
+ catch (err) {
488
+ logger.warn(`[senpi-skills-manager] applyUpdates — git clone failed, skipping batch: ${formatErr(err)}`);
489
+ return;
490
+ }
491
+ const succeededSkillNames = [];
492
+ const failedSkills = [];
493
+ for (const skillName of skillNames) {
494
+ const outcome = this.processInstallOutcome(skillName, installOutcomes);
495
+ if (outcome.success) {
496
+ succeededSkillNames.push(skillName);
497
+ logger.info(`[senpi-skills-manager] applyUpdates — installed | skill=${skillName} version=${outcome.version ?? "unknown"}`);
498
+ }
499
+ else {
500
+ failedSkills.push({ name: skillName, reason: outcome.error });
501
+ }
502
+ }
503
+ logger.info(`[senpi-skills-manager] applyUpdates complete | installed=${succeededSkillNames.length} failed=${failedSkills.length}`);
504
+ await this.sendUpdateSummary(succeededSkillNames, failedSkills);
505
+ }
506
+ /**
507
+ * Clone the remote skills repo exactly once and install every skill in
508
+ * `skillNames` from that single checkout. Returns a per-skill outcome map:
509
+ * `{ version }` on success or `{ version: null, error }` on install failure.
510
+ *
511
+ * Throws only when the clone itself fails — per-skill install failures are
512
+ * captured in the map so callers can continue processing the rest.
513
+ *
514
+ * When `deps.cloneAndInstall` is supplied (unit tests), that injector is
515
+ * called in place of the real clone+install loop; any names missing from
516
+ * its returned map are treated as install failures.
517
+ */
518
+ async cloneAndInstallMany(skillNames) {
519
+ const { logger, config } = this.options;
520
+ const outcomes = new Map();
521
+ if (skillNames.length === 0)
522
+ return outcomes;
523
+ if (this.options.deps?.cloneAndInstall) {
524
+ // Injected dep for tests — receives skill names + config, returns name→version map.
525
+ // Names absent from the returned map are treated as failures.
526
+ logger.info(`[senpi-skills-manager] cloneAndInstallMany — using injected dep | skills=${skillNames.join(",")}`);
527
+ const versionsByName = await this.options.deps.cloneAndInstall(skillNames, config);
528
+ for (const skillName of skillNames) {
529
+ if (versionsByName.has(skillName)) {
530
+ outcomes.set(skillName, {
531
+ version: versionsByName.get(skillName) ?? this.latestVersions.get(skillName) ?? null,
532
+ });
533
+ }
534
+ else {
535
+ outcomes.set(skillName, { version: null, error: "install failed" });
536
+ }
537
+ }
538
+ return outcomes;
539
+ }
540
+ logger.info(`[senpi-skills-manager] cloneAndInstallMany — cloning repo | url=${SKILLS_REPO_URL} timeoutMs=120000`);
541
+ const { cloneDir, cleanup } = await cloneSkillsRepo(SKILLS_REPO_URL, 120_000, logger);
542
+ logger.info(`[senpi-skills-manager] cloneAndInstallMany — clone ready, installing | count=${skillNames.length} cloneDir=${cloneDir}`);
543
+ try {
544
+ for (const skillName of skillNames) {
545
+ try {
546
+ // Writes always target the *primary* dir (first entry in the
547
+ // search path). Secondary dirs are read-only mirrors — we'd never
548
+ // overwrite them on a tick or manual update.
549
+ await installSkill(cloneDir, skillName, config.skillsDir[0], logger);
550
+ const newVersion = this.latestVersions.get(skillName) ?? null;
551
+ outcomes.set(skillName, { version: newVersion });
552
+ logger.info(`[senpi-skills-manager] cloneAndInstallMany — installed | skill=${skillName} version=${newVersion ?? "unknown"}`);
553
+ }
554
+ catch (err) {
555
+ const errorMessage = formatErr(err);
556
+ outcomes.set(skillName, { version: null, error: errorMessage });
557
+ logger.warn(`[senpi-skills-manager] cloneAndInstallMany — install failed | skill=${skillName} err=${errorMessage}`);
558
+ }
559
+ }
560
+ }
561
+ finally {
562
+ await cleanup();
563
+ logger.info("[senpi-skills-manager] cloneAndInstallMany — clone cleanup done");
564
+ }
565
+ return outcomes;
566
+ }
567
+ /**
568
+ * Record a successful install on in-memory skill state.
569
+ *
570
+ * Resets failure tracking — a successful end-to-end install is the only
571
+ * signal we treat as "operationally healthy." A successful version check
572
+ * alone is NOT sufficient (and intentionally does not call this), because:
573
+ *
574
+ * - The version check only proves the raw SKILL.md is reachable. It does
575
+ * not exercise the clone/copy/swap pipeline that actually keeps the skill
576
+ * working.
577
+ * - Clearing failure state on every check-success would wipe install-failure
578
+ * history mid-tick: a skill failing to install on every tick would still
579
+ * report `consecutiveFailures: 1` (instead of N) because each tick's
580
+ * check-success reset would precede the install-failure increment.
581
+ *
582
+ * Consequence: a skill that's perpetually up-to-date but had a one-off
583
+ * failure in the past will retain a non-zero `consecutiveFailures` until
584
+ * the next install. We accept that trade-off — surfacing a stale failure
585
+ * counter is preferable to silently wiping real install-failure history.
586
+ */
587
+ recordSuccess(skillState, newVersion) {
588
+ skillState.installedVersion = newVersion;
589
+ skillState.lastAppliedVersion = newVersion;
590
+ skillState.consecutiveFailures = 0;
591
+ skillState.lastFailureAt = null;
592
+ skillState.lastFailureReason = null;
593
+ }
594
+ /**
595
+ * Record a version-check failure on in-memory skill state.
596
+ *
597
+ * Shared by `runTick` and `updateAll` — both need to bump
598
+ * `consecutiveFailures` and capture the reason when `Promise.allSettled`
599
+ * surfaces a rejected check. `lastCheckedAt` is updated too so the snapshot
600
+ * doesn't look like the skill was never polled (it was — the poll failed).
601
+ */
602
+ recordCheckFailure(skillName, errorMessage) {
603
+ const skillState = this.state.skills[skillName] ?? createDefaultSkillState(skillName);
604
+ const now = new Date().toISOString();
605
+ skillState.lastCheckedAt = now;
606
+ skillState.consecutiveFailures += 1;
607
+ skillState.lastFailureAt = now;
608
+ skillState.lastFailureReason = errorMessage;
609
+ this.state.skills[skillName] = skillState;
610
+ }
611
+ /**
612
+ * Apply one install outcome to in-memory skill state and return a compact
613
+ * success/failure result for the caller's bookkeeping.
614
+ */
615
+ processInstallOutcome(skillName, installOutcomes) {
616
+ const outcome = installOutcomes.get(skillName) ?? { version: null, error: "install result missing" };
617
+ const skillState = this.state.skills[skillName] ?? createDefaultSkillState(skillName);
618
+ if (outcome.error) {
619
+ skillState.consecutiveFailures += 1;
620
+ skillState.lastFailureAt = new Date().toISOString();
621
+ skillState.lastFailureReason = outcome.error;
622
+ this.state.skills[skillName] = skillState;
623
+ return { success: false, error: outcome.error };
624
+ }
625
+ this.recordSuccess(skillState, outcome.version);
626
+ this.state.skills[skillName] = skillState;
627
+ return { success: true, version: outcome.version };
628
+ }
629
+ /**
630
+ * Apply a single skill update (used by the manual `updateSkill` RPC path).
631
+ * Returns the installed version.
632
+ *
633
+ * Delegates to {@link cloneAndInstallMany} so the single-skill and batch
634
+ * paths share one implementation of clone+install. The per-skill install
635
+ * error is re-thrown here so `updateSkill` can surface it to the RPC
636
+ * caller via a rejected promise (batch path captures it instead).
637
+ */
638
+ async applyUpdate(skillName, remoteVersion) {
639
+ const { logger } = this.options;
640
+ logger.info(`[senpi-skills-manager] applyUpdate — starting | skill=${skillName} targetVersion=${remoteVersion ?? "unknown"}`);
641
+ // Clone can throw (full repo fetch failed). Unlike the batch path — which
642
+ // intentionally doesn't attribute a shared clone failure to individual
643
+ // skills — the single-skill path has an unambiguous owner, so we record
644
+ // the clone failure against this skill's failure counters before
645
+ // re-throwing to the RPC caller.
646
+ let installOutcomes;
647
+ try {
648
+ installOutcomes = await this.cloneAndInstallMany([skillName]);
649
+ }
650
+ catch (err) {
651
+ const errorMessage = `clone failed: ${formatErr(err)}`;
652
+ const skillState = this.state.skills[skillName] ?? createDefaultSkillState(skillName);
653
+ skillState.consecutiveFailures += 1;
654
+ const now = new Date().toISOString();
655
+ skillState.lastFailureAt = now;
656
+ skillState.lastFailureReason = errorMessage;
657
+ this.state.skills[skillName] = skillState;
658
+ await this.persistState();
659
+ logger.warn(`[senpi-skills-manager] applyUpdate — ${errorMessage} | skill=${skillName}`);
660
+ throw err;
661
+ }
662
+ // Delegate outcome bookkeeping (success or install-failure) to the shared
663
+ // helper so the single-skill path records failure state identically to
664
+ // the batch path — previously this path threw raw without ever touching
665
+ // consecutiveFailures / lastFailureAt / lastFailureReason, so manual
666
+ // updateSkill install failures were silently invisible to the snapshot.
667
+ const processed = this.processInstallOutcome(skillName, installOutcomes);
668
+ await this.persistState();
669
+ if (!processed.success) {
670
+ logger.warn(`[senpi-skills-manager] applyUpdate — install failed | skill=${skillName} err=${processed.error}`);
671
+ throw new Error(processed.error);
672
+ }
673
+ const installedVersion = processed.version ?? remoteVersion ?? null;
674
+ logger.info(`[senpi-skills-manager] applyUpdate complete | skill=${skillName} version=${installedVersion ?? "unknown"}`);
675
+ return installedVersion;
676
+ }
677
+ /**
678
+ * Format the per-skill nested-bullet block used in both notification
679
+ * shapes. Renders the structure suggested in PR #78 review feedback:
680
+ *
681
+ * **skill-name**
682
+ * • v1.0.0 → v2.0.0 (or "v1.0.0 (install failed)" when failed)
683
+ * • description: … (omitted when no remote description)
684
+ * • error: … (only on failure, replaces the description)
685
+ *
686
+ * **Why markdown, not HTML?**
687
+ * Openclaw's Telegram channel (`src/telegram/send.ts:sendMessageTelegram`)
688
+ * pipes outbound text through `renderTelegramHtmlText`, which defaults
689
+ * `textMode` to `"markdown"` — i.e. it expects the source to be markdown
690
+ * and runs `markdownToTelegramHtml` over it before handing the converted
691
+ * HTML to the Bot API with `parse_mode: "HTML"`. The `message` tool
692
+ * (which is what this coordinator's `notify` callback ultimately hits via
693
+ * `/tools/invoke`) does not expose `textMode`, so HTML written by us is
694
+ * treated as literal characters by the markdown step and rendered as
695
+ * visible `<b>` text in the chat (the actual production bug this docstring
696
+ * fixes — confirmed against a live notification screenshot).
697
+ *
698
+ * Using markdown source (`**bold**`, backticks) instead means the channel's
699
+ * markdown→HTML converter produces the correct `<b>` / `<code>` HTML
700
+ * payload and Telegram renders the formatting properly.
701
+ *
702
+ * @param skillName Skill identifier (rendered bold via `**name**`).
703
+ * @param toVersion Resolved upgraded-to version. `null` for failure rows
704
+ * where no install completed; renders as
705
+ * "vPREV (install failed)".
706
+ * @param errorReason Optional failure reason. When provided, replaces
707
+ * the description line with `error: …`.
708
+ */
709
+ formatSkillBlock(skillName, toVersion, errorReason = null) {
710
+ const prev = this.previousVersions.get(skillName) ?? null;
711
+ const versionLine = errorReason !== null
712
+ ? ` • ${prev !== null ? `v${prev} ` : ""}(install failed)`
713
+ : ` • ${prev !== null ? `v${prev} → ` : ""}${toVersion !== null ? `v${toVersion}` : "(unknown)"}`;
714
+ const description = this.skillDescriptions.get(skillName) ?? null;
715
+ const trailingLine = errorReason !== null
716
+ ? ` • error: ${errorReason}`
717
+ : description
718
+ ? ` • description: ${description}`
719
+ : null;
720
+ // Skill name line: bold only, no leading bullet — the bold acts as the
721
+ // visual anchor for the block, and the nested bullets below already
722
+ // convey "these belong to this skill". A leading `•` on the heading
723
+ // looked redundant in production.
724
+ const lines = [`**${skillName}**`, versionLine];
725
+ if (trailingLine)
726
+ lines.push(trailingLine);
727
+ return lines.join("\n");
728
+ }
729
+ /**
730
+ * Send a one-way Telegram notification for a pending major update, deduped
731
+ * by version.
732
+ *
733
+ * The dedup key (`lastNotifiedMajorVersion`) is only set after the notify
734
+ * call resolves successfully. If the notification fails (Telegram API down,
735
+ * transient network error, etc.) the key is left unchanged so the next tick
736
+ * retries delivery instead of silently suppressing it forever.
737
+ */
738
+ async handleMajorAvailable(skillState, skillName, remoteVersion) {
739
+ if (skillState.lastNotifiedMajorVersion === remoteVersion) {
740
+ this.options.logger.info(`[senpi-skills-manager] handleMajorAvailable — notification already sent, skipping | skill=${skillName} version=${remoteVersion}`);
741
+ return;
742
+ }
743
+ try {
744
+ const block = this.formatSkillBlock(skillName, remoteVersion);
745
+ await this.options.notify(`Senpi skills update — major available:\n\n` +
746
+ `${block}\n\n` +
747
+ `Major updates are not applied automatically.\n` +
748
+ // Inline code via markdown backticks — the channel's markdown→HTML
749
+ // step converts these to `<code>` so the install command renders
750
+ // in monospace. Skill names in the senpi-skills repo are
751
+ // kebab-case identifiers (no backtick chars), so no escaping is
752
+ // needed here in practice.
753
+ `Run: \`openclaw senpi skills update ${skillName}\`\n\n` +
754
+ // Yes/no CTA — operator-friendly framing, intentionally short.
755
+ // Replies are routed to the agent layer, not to this coordinator.
756
+ `Want help with the upgrade? Reply yes or no.`);
757
+ skillState.lastNotifiedMajorVersion = remoteVersion;
758
+ this.options.logger.info(`[senpi-skills-manager] handleMajorAvailable — major-update notification sent | skill=${skillName} version=${remoteVersion}`);
759
+ }
760
+ catch (err) {
761
+ this.options.logger.warn(`[senpi-skills-manager] failed to send major-update notification for "${skillName}": ${formatErr(err)}`);
762
+ // Leave dedup key unchanged — retry on next tick.
763
+ }
764
+ }
765
+ /**
766
+ * Send an aggregated notification summarising the outcome of this tick's
767
+ * updates. Successful installs and failures are shown in separate sections
768
+ * so the user can tell which skills still need attention. Sections with no
769
+ * entries are omitted. If neither section has entries, no notification is
770
+ * sent.
771
+ *
772
+ * Format (markdown source — see `formatSkillBlock` for why markdown
773
+ * rather than HTML):
774
+ *
775
+ * Senpi skills update:
776
+ *
777
+ * Updated:
778
+ *
779
+ * **skill-a**
780
+ * • v1.0.0 → v1.0.1
781
+ * • description: …
782
+ *
783
+ * **skill-b**
784
+ * • v2.0.0 → v2.0.1
785
+ * • description: …
786
+ *
787
+ * Failed to update:
788
+ *
789
+ * **skill-c**
790
+ * • v1.0.0 (install failed)
791
+ * • error: clone failed: …
792
+ */
793
+ async sendUpdateSummary(succeededSkillNames, failedSkills) {
794
+ if (succeededSkillNames.length === 0 && failedSkills.length === 0)
795
+ return;
796
+ const sections = [];
797
+ if (succeededSkillNames.length > 0) {
798
+ const blocks = succeededSkillNames.map((name) => this.formatSkillBlock(name, this.latestVersions.get(name) ?? null));
799
+ sections.push(`Updated:\n\n${blocks.join("\n\n")}`);
800
+ }
801
+ if (failedSkills.length > 0) {
802
+ const blocks = failedSkills.map(({ name, reason }) => this.formatSkillBlock(name, null, reason));
803
+ sections.push(`Failed to update:\n\n${blocks.join("\n\n")}`);
804
+ }
805
+ try {
806
+ await this.options.notify(`Senpi skills update:\n\n${sections.join("\n\n")}`);
807
+ this.options.logger.info(`[senpi-skills-manager] sendUpdateSummary — notification sent | succeeded=${succeededSkillNames.length} failed=${failedSkills.length}`);
808
+ }
809
+ catch (err) {
810
+ this.options.logger.warn(`[senpi-skills-manager] failed to send update summary notification: ${formatErr(err)}`);
811
+ }
812
+ }
813
+ /**
814
+ * Return the version-check function for this coordinator: either the
815
+ * injected `deps.checkSkillVersion` (unit tests) or the real
816
+ * `checkSkillVersion` with the default `fetchImpl`.
817
+ *
818
+ * Extracted so the three call sites (`updateSkill`, `updateAll`, `runTick`)
819
+ * don't repeat the same resolve-and-wrap lambda — a change to the real
820
+ * `checkSkillVersion` signature now only has to land here.
821
+ */
822
+ resolveCheckFn() {
823
+ return (this.options.deps?.checkSkillVersion ??
824
+ ((skillsDirs, skillName, rawBaseUrl, logger) => checkSkillVersion(skillsDirs, skillName, rawBaseUrl, undefined, logger)));
825
+ }
826
+ /**
827
+ * Resolve the list of skill names to check this tick.
828
+ * Uses `config.skills` when non-empty; otherwise discovers all immediate
829
+ * subdirectories across every dir in the `skillsDir` search path,
830
+ * deduped by name and sorted.
831
+ *
832
+ * Per-dir read errors (other than ENOENT) are logged but do not abort the
833
+ * scan — a misconfigured secondary dir cannot mask skills present in the
834
+ * primary.
835
+ */
836
+ async resolveSkillNames() {
837
+ if (this.options.config.skills.length > 0) {
838
+ return this.options.config.skills;
839
+ }
840
+ const seen = new Set();
841
+ let anySucceeded = false;
842
+ for (const dir of this.options.config.skillsDir) {
843
+ try {
844
+ const entries = await readdir(dir, { withFileTypes: true });
845
+ anySucceeded = true;
846
+ for (const entry of entries) {
847
+ if (entry.isDirectory() && !entry.name.startsWith(".")) {
848
+ seen.add(entry.name);
849
+ }
850
+ }
851
+ }
852
+ catch (err) {
853
+ // ENOENT for a dir that hasn't been created yet is benign — only
854
+ // log the noisier failure modes so operators can diagnose them.
855
+ if (err.code !== "ENOENT") {
856
+ this.options.logger.warn(`[senpi-skills-manager] resolveSkillNames — failed to read skillsDir, continuing | dir=${dir} err=${formatErr(err)}`);
857
+ }
858
+ }
859
+ }
860
+ if (!anySucceeded && seen.size === 0) {
861
+ // Every configured dir failed to read (or none exist). Previously the
862
+ // single-dir version warned in this case; preserve that signal so
863
+ // "no skills checked" is still distinguishable from "skillsDir
864
+ // configured wrong" in the logs.
865
+ this.options.logger.warn(`[senpi-skills-manager] resolveSkillNames — no readable skills dirs | dirs=${this.options.config.skillsDir.join(",")}`);
866
+ }
867
+ return Array.from(seen).sort();
868
+ }
869
+ /**
870
+ * Build the point-in-time snapshot returned by {@link getSnapshot}.
871
+ *
872
+ * The snapshot is the single serialisable view of the coordinator's state
873
+ * consumed by gateway RPCs (`senpi.skills.status`) and any health UI. It
874
+ * fuses three data sources:
875
+ * 1. Per-skill persisted state (`this.state.skills`) — installed version,
876
+ * last check time, consecutive failures, last failure reason.
877
+ * 2. In-memory `this.latestVersions` map — the most recent remote version
878
+ * observed during a version check (may not yet be installed).
879
+ * 3. Caller-supplied lifecycle metadata — `health`, `lastAction`,
880
+ * `lastError` describing the most recent tick / manual RPC outcome.
881
+ *
882
+ * This is called at every state-mutating boundary (start, tick complete,
883
+ * tick error, manual update complete, manual update skipped, manual update
884
+ * clone failed, stop/disable) so the next RPC response reflects the latest
885
+ * state rather than stale pre-action data.
886
+ */
887
+ buildSnapshot(health, lastAction, lastError = null) {
888
+ const skillSnapshots = Object.values(this.state.skills).map((skillState) => ({
889
+ name: skillState.name,
890
+ installedVersion: skillState.installedVersion,
891
+ latestVersion: this.latestVersions.get(skillState.name) ?? null,
892
+ lastCheckedAt: skillState.lastCheckedAt,
893
+ consecutiveFailures: skillState.consecutiveFailures,
894
+ lastFailureReason: skillState.lastFailureReason,
895
+ }));
896
+ return {
897
+ enabled: this.options.config.enabled,
898
+ // Snapshot is a serializable view consumed by gateway RPCs and the CLI;
899
+ // hand callers a defensive copy so their downstream mutations (e.g.
900
+ // sorting, push for display) can't poison the live config.
901
+ skillsDir: [...this.options.config.skillsDir],
902
+ health,
903
+ lastAction,
904
+ lastError,
905
+ skills: skillSnapshots,
906
+ };
907
+ }
908
+ async persistState() {
909
+ try {
910
+ await this.store.save(this.state);
911
+ }
912
+ catch (err) {
913
+ this.options.logger.warn(`[senpi-skills-manager] failed to persist state: ${formatErr(err)}`);
914
+ }
915
+ }
916
+ }
917
+ // `escapeHtml` was removed alongside the switch from HTML to markdown
918
+ // notification source — see `formatSkillBlock` for why. The openclaw
919
+ // Telegram channel runs `markdownToTelegramHtml` over our text and
920
+ // handles HTML escaping itself on the converter's output. Pre-escaping
921
+ // at this layer would double-escape (e.g. `&amp;` becomes `&amp;amp;`)
922
+ // and corrupt the rendered output.
923
+ //
924
+ // Markdown-special characters (`*`, `_`, `[`, `]`, backtick) in dynamic
925
+ // values aren't escaped either — descriptions that legitimately contain
926
+ // these would author them as markdown intentionally; skill names in the
927
+ // senpi-skills repo are kebab-case identifiers; error messages from
928
+ // `formatErr` are typically prose. If a future skill description ever
929
+ // breaks the rendering, the fix is to author the SKILL.md frontmatter
930
+ // using proper markdown.
931
+ //# sourceMappingURL=coordinator.js.map