更新 src/skill-admin.ts

This commit is contained in:
QQ 2026-11-11 11:34:14 +08:00
parent 6078ac6566
commit 63ef47b79d
1 changed files with 14 additions and 84 deletions

View File

@ -1,6 +1,6 @@
/**
* Local skill management, built into the plugin: list, enable/disable,
* delete-to-trash with restore, and install from a git repository.
* real delete, and install from a git repository.
*
* This covers the everyday subset of a full skills manager. It manages
* only the DSH skills root (plus its own parking and trash areas) — the
@ -14,12 +14,13 @@
* mistaken for deletions, and a parked cloud skill still receives its
* cloud updates in place.
*
* Deletes are never final here: removing a skill moves it into the
* plugin trash (`$DSH_HOME/cloud-memory-trash/`) with an index entry,
* and restore puts it back exactly where it was.
* Delete is a real delete: the folder is removed recursively. The
* cloud copy is unaffected — local deletion never propagates to the
* center (the sync engine remembers the removal, so the same cloud
* version is not pulled back down either).
*/
import { execFile } from 'node:child_process'
import { cp, mkdir, readFile, readdir, rename, rm, stat, writeFile } from 'node:fs/promises'
import { cp, mkdir, readFile, readdir, rename, rm, stat } from 'node:fs/promises'
import { basename, join } from 'node:path'
import { parseSkillFrontmatter } from './skill-sync.ts'
import { dshHome } from './store.ts'
@ -29,11 +30,6 @@ export function skillsHoldingDir(): string {
return join(dshHome(), 'skills-disabled')
}
/** The plugin trash directory. */
export function skillsTrashDir(): string {
return join(dshHome(), 'cloud-memory-trash')
}
/** A management failure with a stable machine-readable code. */
export class SkillAdminError extends Error {
constructor(readonly code: string, message: string) {
@ -57,20 +53,10 @@ export interface AdminSkill {
files: number
}
/** One trashed skill, restorable until the user empties the trash by hand. */
export interface TrashEntry {
id: string
folder: string
name: string
from: 'root' | 'holding'
removedAt: string
}
/** Dependencies of one admin instance. */
export interface SkillAdminDeps {
skillsRoot: () => string
holdingDir: () => string
trashDir: () => string
/** The sync sidecar (read-only here) for origin and revision facts. */
syncStatePath: () => string
/** True while a sync pass is running; mutations refuse meanwhile. */
@ -78,10 +64,6 @@ export interface SkillAdminDeps {
log: (message: string) => void
}
interface TrashIndex {
entries: TrashEntry[]
}
async function isDirectory(path: string): Promise<boolean> {
return stat(path).then((s) => s.isDirectory()).catch(() => false)
}
@ -169,8 +151,8 @@ export class SkillAdmin {
}
}
/** Inventory of the skills root, the parking area, and the trash. */
async list(): Promise<{ skills: AdminSkill[]; trash: TrashEntry[] }> {
/** Inventory of the skills root and the parking area. */
async list(): Promise<{ skills: AdminSkill[] }> {
const uploaded = await this.syncUploaded()
const skills: AdminSkill[] = []
const scan = async (area: string, enabled: boolean): Promise<void> => {
@ -183,7 +165,7 @@ export class SkillAdmin {
await scan(this.deps.skillsRoot(), true)
await scan(this.deps.holdingDir(), false)
skills.sort((a, b) => (a.folder < b.folder ? -1 : 1))
return { skills, trash: (await this.readTrashIndex()).entries }
return { skills }
}
/** Locate a skill folder across the root and the parking area. */
@ -212,67 +194,15 @@ export class SkillAdmin {
return { folder, enabled }
}
private async readTrashIndex(): Promise<TrashIndex> {
try {
const parsed: unknown = JSON.parse(await readFile(join(this.deps.trashDir(), 'index.json'), 'utf8'))
if (parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)) {
const entries = (parsed as { entries?: unknown }).entries
if (Array.isArray(entries)) return { entries: entries as TrashEntry[] }
}
} catch {
// No trash yet.
}
return { entries: [] }
}
private async writeTrashIndex(index: TrashIndex): Promise<void> {
await mkdir(this.deps.trashDir(), { recursive: true })
await writeFile(join(this.deps.trashDir(), 'index.json'), JSON.stringify(index, null, 2))
}
/** Move one skill into the trash (never a hard delete). */
async remove(folderInput: unknown): Promise<TrashEntry> {
/** Delete one skill for real: its folder is removed recursively. */
async remove(folderInput: unknown): Promise<{ folder: string }> {
this.guardSync()
const folder = checkFolder(folderInput)
const found = await this.locate(folder)
if (found === undefined) fail('not_found', `没有找到技能:${folder}`)
const described = await this.describe(folder, found.dir, found.area === 'root', {})
const stamp = new Date().toISOString().replace(/[:.]/g, '-')
const id = `${folder.replace(/[<>:"/\\|?*]/g, '_')}--${stamp}`
await mkdir(this.deps.trashDir(), { recursive: true })
await rename(found.dir, join(this.deps.trashDir(), id))
const entry: TrashEntry = {
id,
folder,
name: described?.name ?? folder,
from: found.area,
removedAt: new Date().toISOString(),
}
const index = await this.readTrashIndex()
index.entries.push(entry)
await this.writeTrashIndex(index)
this.deps.log(`skill trashed: ${folder}`)
return entry
}
/** Put one trashed skill back where it was removed from. */
async restore(idInput: unknown): Promise<{ folder: string }> {
this.guardSync()
if (typeof idInput !== 'string' || idInput === '' || idInput.includes('/') || idInput.includes('\\')) {
fail('invalid_name', '回收站条目无效。')
}
const index = await this.readTrashIndex()
const entry = index.entries.find((item) => item.id === idInput)
if (entry === undefined) fail('not_found', '回收站里没有这条记录。')
const targetRoot = entry.from === 'holding' ? this.deps.holdingDir() : this.deps.skillsRoot()
await mkdir(targetRoot, { recursive: true })
const target = join(targetRoot, entry.folder)
if (await isDirectory(target)) fail('collision', `已有同名技能占用了位置:${entry.folder}`)
await rename(join(this.deps.trashDir(), entry.id), target)
index.entries = index.entries.filter((item) => item.id !== entry.id)
await this.writeTrashIndex(index)
this.deps.log(`skill restored: ${entry.folder}`)
return { folder: entry.folder }
await rm(found.dir, { recursive: true, force: true })
this.deps.log(`skill deleted: ${folder}`)
return { folder }
}
/**