fix(windows): stabilize native coverage watchers

This commit is contained in:
Tianyi Cui
2026-08-08 21:26:38 +08:00
parent ded7f8ffd1
commit b1ccca71ef
9 changed files with 58 additions and 30 deletions

View File

@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write packages/skill/skill-local/README.md
README.md: f85cc2e6fd0c32cb88f28a2914a03e22b3a20657
README.zh.md: 9ee09938737237df9e97e517c1dd44b511b7f596
README.md: 6d3d97ea34308ccc920d0b42c5a220dd7a9d6d73
README.zh.md: 9948369774bc08a4ddbd4e518b53134ddd7c6882

View File

@@ -44,7 +44,7 @@ When `ctx.fs` is available, discovery lists roots through `ctx.fs.listDir`, read
## Catalog Change Detection
Existing skill roots are watched with Chokidar. The provider observes direct bundle directory additions/removals, flat Markdown additions/removals, and direct `SKILL.md` additions/removals/changes; `change` exists to rediscover catalog frontmatter such as `name` and `description`. Changes below `references`, `scripts`, `assets`, or other bundle resources do not invalidate the catalog. Events delivered in the same microtask batch collapse to one provider invalidation.
Existing skill roots are watched with Chokidar. Before opening a native watcher, the provider realpaths the existing root or ancestor and restores the next missing segment; discovery and diagnostics retain the configured path, while Windows cannot mix an 8.3 alias with long-form libuv events. The provider observes direct bundle directory additions/removals, flat Markdown additions/removals, and direct `SKILL.md` additions/removals/changes; `change` exists to rediscover catalog frontmatter such as `name` and `description`. Changes below `references`, `scripts`, `assets`, or other bundle resources do not invalidate the catalog. Events delivered in the same microtask batch collapse to one provider invalidation.
A root that does not exist is followed from the nearest existing ancestor one missing path segment at a time. The next segment is probed with `fs.watchFile`; once `.agents`, `skills`, or the configured root appears, observation advances until Chokidar can attach to the real root. Root deletion reverses this process, so deleting and recreating an entire skills directory remains observable. Project-scoped watchers are bounded by `watchMaxProjects`; revisiting an evicted project reattaches observation during discovery.

View File

@@ -44,7 +44,7 @@
## 目录变更检测
现有 skill 根由 Chokidar 监视。提供方会观察直属 bundle 目录的添加/移除、平铺 Markdown 文件的添加/移除,以及直接 `SKILL.md` 的添加/移除/变更;`change` 事件用于重新发现 `name``description` 等目录 frontmatter。`references``scripts``assets` 或其他 bundle 资源下的变更不会使目录失效。同一微任务批次内送达的事件会合并为一次提供方失效。
现有 skill 根由 Chokidar 监视。打开原生 watcher 前,提供方会对现有根或祖先执行 realpath 解析,并拼回下一个缺失路径段;发现与诊断仍保留配置路径,从而避免 Windows 在 libuv 内部混用 8.3 别名与长格式事件路径。提供方会观察直属 bundle 目录的添加/移除、平铺 Markdown 文件的添加/移除,以及直接 `SKILL.md` 的添加/移除/变更;`change` 事件用于重新发现 `name``description` 等目录 frontmatter。`references``scripts``assets` 或其他 bundle 资源下的变更不会使目录失效。同一微任务批次内送达的事件会合并为一次提供方失效。
不存在的根会从最近的现有祖先开始,每次沿一个缺失路径段跟踪。系统使用 `fs.watchFile` 探测下一段;当 `.agents``skills` 或已配置的根出现后,观察会逐级推进,直至 Chokidar 可以附加到真实根。根删除时,该过程反向执行,因此删除再重建整个 skills 目录仍可被观察到。按项目划分的 watcher 数量受 `watchMaxProjects` 限制;再次访问已被驱逐的项目时,发现阶段会重新附加观察。

View File

@@ -19,7 +19,7 @@ import z from 'schemastery'
import type Schema from 'schemastery'
import { parse as parseYaml } from 'yaml'
import type { FileSystem, FsDirEntry, FsTarget } from '@deepseek-ai/dsh-fs'
import { resolveDshHome } from '@deepseek-ai/dsh-paths'
import { canonicalizeWatchPath, resolveDshHome } from '@deepseek-ai/dsh-paths'
import {
BUNDLED_SKILL_RANK,
isSkillName,
@@ -525,7 +525,7 @@ class SkillWatchManager {
readiness.resolve(undefined)
})
for (const event of ['add', 'addDir', 'change', 'unlink', 'unlinkDir'] as const) {
watcher.on(event, (path) => { this.handleWatchEvent(state, event, path) })
watcher.on(event, (path) => { this.handleWatchEvent(state, mode, event, path) })
}
try {
await readiness.promise
@@ -540,12 +540,14 @@ class SkillWatchManager {
private handleWatchEvent(
state: RootWatchState,
mode: Extract<RootWatchMode, { kind: 'root' }>,
event: SkillWatchEvent,
path: string,
): void {
if (this.closing || !isRelevantWatchEvent(state.root, event, resolve(path))) return
const target = resolve(path)
if (this.closing || !isRelevantWatchEvent({ ...state.root, path: mode.anchor }, event, target)) return
this.queueInvalidation()
if (resolve(path) === state.root.path && event === 'unlinkDir') {
if (target === mode.anchor && event === 'unlinkDir') {
state.unhealthy = true
this.scheduleRewatch(state)
}
@@ -625,11 +627,12 @@ async function resolveRootWatchMode(root: string): Promise<RootWatchMode> {
try {
const info = await stat(candidate)
if (info.isDirectory()) {
if (candidate === root) return { kind: 'root', anchor: root }
const anchor = await canonicalizeWatchPath(candidate)
if (candidate === root) return { kind: 'root', anchor }
const firstSegment = relative(candidate, root).split(sep)[0]
/* v8 ignore next -- candidate is a strict ancestor of root. */
if (firstSegment === undefined || firstSegment.length === 0) return { kind: 'root', anchor: root }
return { kind: 'ancestor', anchor: candidate, nextPath: join(candidate, firstSegment) }
if (firstSegment === undefined || firstSegment.length === 0) return { kind: 'root', anchor }
return { kind: 'ancestor', anchor, nextPath: join(anchor, firstSegment) }
}
} catch (error) {
/* v8 ignore next -- Non-absence stat failures are platform/permission-specific and propagate as incomplete discovery. */

View File

@@ -1,6 +1,6 @@
import { EventEmitter } from 'node:events'
import type { Stats } from 'node:fs'
import { mkdir, rm, writeFile } from 'node:fs/promises'
import { mkdir, realpath, rm, symlink, writeFile } from 'node:fs/promises'
import { join } from 'node:path'
import { tmpdir } from 'node:os'
import { beforeEach, describe, expect, it, vi } from 'vitest'
@@ -11,6 +11,7 @@ interface FakeWatcherControl {
emitter: EventEmitter
closeCalls: number
options: Record<string, unknown>
path: string
}
interface FakeWatchFileControl {
@@ -63,9 +64,9 @@ vi.mock('node:fs/promises', async (importOriginal) => {
vi.mock('chokidar', () => ({
default: {
watch(_path: unknown, options: Record<string, unknown>) {
watch(path: unknown, options: Record<string, unknown>) {
const emitter = new EventEmitter() as EventEmitter & { close(): Promise<void> }
const control: FakeWatcherControl = { emitter, closeCalls: 0, options }
const control: FakeWatcherControl = { emitter, closeCalls: 0, options, path: String(path) }
emitter.close = async () => {
control.closeCalls += 1
if (watcherHarness.closeErrors > 0) {
@@ -114,6 +115,26 @@ beforeEach(() => {
})
describe('skill-local watcher failures', () => {
it('canonicalizes an existing root before opening its native watcher', async () => {
const target = await tempDir('skill-watch-canonical-target')
const aliasParent = await tempDir('skill-watch-canonical-alias')
const alias = join(aliasParent, 'alias')
await symlink(target, alias, process.platform === 'win32' ? 'junction' : 'dir')
const root = join(alias, '.dsh/skills')
await writeSkill(root, 'canonical-skill')
const ctx = new Context()
await ctx.plugin(SkillService)
const fiber = await ctx.plugin(SkillLocal, {
dshHome: join(alias, '.dsh'),
agentsHome: join(alias, '.agents'),
watch: true,
})
expect((await ctx.skills.list()).map(skill => skill.name)).toEqual(['canonical-skill'])
expect(watcherHarness.watchers[0]?.path).toBe(await realpath(root))
await fiber.dispose()
})
it('ignores missing-path probes until the observed path actually changes', async () => {
const home = await tempDir('skill-watch-missing-stable')
const ctx = new Context()
@@ -205,24 +226,22 @@ describe('skill-local watcher failures', () => {
const first = watcherHarness.watchers[0]
if (first === undefined) throw new Error('expected a root watcher')
first.emitter.emit('change', join(root, 'notes.txt'))
first.emitter.emit('change', join(first.path, 'notes.txt'))
first.emitter.emit('change', join(home, 'outside.md'))
first.emitter.emit('change', join(root, 'watched-skill/references.md'))
first.emitter.emit('change', join(root, '.system/SKILL.md'))
first.emitter.emit('change', join(first.path, 'watched-skill/references.md'))
first.emitter.emit('change', join(first.path, '.system/SKILL.md'))
await settle()
expect(invalidations).toBe(0)
first.emitter.emit('change', join(root, 'watched-skill/SKILL.md'))
first.emitter.emit('change', join(root, 'watched-skill/SKILL.md'))
first.emitter.emit('change', join(first.path, 'watched-skill/SKILL.md'))
first.emitter.emit('change', join(first.path, 'watched-skill/SKILL.md'))
await settle()
expect(invalidations).toBe(1)
watcherHarness.closeErrors = 1
watcherHarness.startupErrors.push(new Error('runtime rewatch failed'))
first.emitter.emit('error', new Error('runtime watch failed'))
await settle()
await settle()
expect(watcherHarness.watchers.length).toBeGreaterThanOrEqual(2)
await vi.waitFor(() => { expect(watcherHarness.watchers.length).toBeGreaterThanOrEqual(2) })
expect(invalidations).toBeGreaterThanOrEqual(2)
expect(await ctx.skills.snapshot()).toMatchObject({
skills: [{ name: 'watched-skill' }],
@@ -230,7 +249,7 @@ describe('skill-local watcher failures', () => {
})
await fiber.dispose()
first.emitter.emit('change', join(root, 'watched-skill/SKILL.md'))
first.emitter.emit('change', join(first.path, 'watched-skill/SKILL.md'))
first.emitter.emit('error', new Error('late error'))
await settle()
})
@@ -254,9 +273,11 @@ describe('skill-local watcher failures', () => {
if (original === undefined) throw new Error('expected a root watcher')
await rm(root, { recursive: true })
original.emitter.emit('unlinkDir', root)
original.emitter.emit('unlinkDir', original.path)
await vi.waitFor(() => { expect(original.closeCalls).toBeGreaterThan(0) })
expect(watcherHarness.watchFiles.some(control => control.path === root)).toBe(true)
await vi.waitFor(() => {
expect(watcherHarness.watchFiles.some(control => control.path === original.path)).toBe(true)
})
await fiber.dispose()
})
@@ -280,11 +301,11 @@ describe('skill-local watcher failures', () => {
if (original === undefined) throw new Error('expected a root watcher')
await rm(root, { recursive: true })
original.emitter.emit('unlink', join(root, 'old-skill/SKILL.md'))
original.emitter.emit('unlink', join(original.path, 'old-skill/SKILL.md'))
await settle()
expect(await ctx.skills.snapshot()).toEqual({ skills: [], complete: true })
const missingRoot = watcherHarness.watchFiles.find(control => control.path === root)
const missingRoot = watcherHarness.watchFiles.find(control => control.path === original.path)
expect(missingRoot).toBeDefined()
await writeSkill(root, 'recreated-skill')
missingRoot!.listener({} as Stats, {} as Stats)

View File

@@ -1055,7 +1055,7 @@ describe('SubagentService.listDescendants', () => {
})
it('walks a deeply nested ordinary-session chain without consuming the call stack', async () => {
it('walks a deeply nested ordinary-session chain without consuming the call stack', { timeout: 20_000 }, async () => {
const { ctx, parent } = await setup([])
const depth = 10_000
let parentId = parent.id