feat: Reader Skill 支持版本自检与自助更新

微信机器人回复剥离引用编号、列表改用空行分隔,失败通知补失败时刻
 问问微信关键词检索在索引落后时按单会话直读原始记录兜底
 关闭窗口支持记住选择并在设置中修改
 退群监控刷新列表
This commit is contained in:
Wxw-Gu committed 2026-10-14 10:31:01 +08:00
1 parent fd7d5016a8
commit eaa25cd29e
33 files changed
+1401 -154

No files matched your search

@@ -149,9 +149,22 @@ describe('GroupExitMonitorWorkspace', () => {
monitoredRoomIds: ['研发群@chatroom'],
monitoredGroupCount: 1
}
const setGroups = vi.fn().mockResolvedValue(savedState)
const setGroups = vi.fn(async (roomIds: string[]) => {
current = {
...configuredState,
monitoredRoomIds: roomIds,
monitoredGroupCount: roomIds.length
}
return current
})
/**
* 真实服务的 `getState()` 返回的是**内存里的当前状态** —— 保存之后再拉一次,
* 拿到的必然是保存后的值。mock 用可变变量体现这一点:
* 否则"切回事件页时重新拉取"会把它覆盖成保存前的旧值,那是 mock 的失真,不是实现的问题。
*/
let current: GroupExitMonitorState = configuredState
window.api = {
getGroupExitMonitorState: vi.fn().mockResolvedValue(configuredState),
getGroupExitMonitorState: vi.fn(async () => current),
onGroupExitMonitorState: vi.fn(() => () => undefined),
setGroupExitMonitorGroups: setGroups,
checkGroupExitMonitorNow: vi.fn().mockResolvedValue(savedState),
@@ -0,0 +1,110 @@
import { act, render, waitFor } from '@testing-library/react'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { ToastProvider } from '../../src/renderer/src/components/ui'
import { MessageInsertSwitches } from '../../src/renderer/src/features/automation/MessageInsertSwitches'
import type { MsgInsertSwitchesSnapshot } from '../../src/shared/msg-insert-switch'
/**
* 自动化页右上角的两个开关 —— 只钉**运行期刷新时机**。
*
* 背景:微信运行期间会新建 `message_N.db`,目标会话集合随之变化,而规则补齐此前
* 只在启动时跑过一次。渲染层如果只在挂载时拉一次,用户看到的就是"计数对不上、
* 而且不会自己变好"。所以要在窗口重新聚焦时问一次(主进程侧再用分片指纹决定要不要补)。
*/
function makeSnapshot(ready: number, total: number): MsgInsertSwitchesSnapshot {
return {
success: true,
helperAvailable: true,
switches: {
recall_notice: {
name: 'recall_notice',
mode: 'rules',
desiredEnabled: true,
effectiveEnabled: ready === total,
readyInstallableRooms: ready,
totalInstallableRooms: total,
notReadyRooms: [],
totalShards: 1,
targetShards: 1
},
group_exit_notice: {
name: 'group_exit_notice',
mode: 'event',
desiredEnabled: true,
effectiveEnabled: true,
readyInstallableRooms: 1,
totalInstallableRooms: 1,
notReadyRooms: [],
totalShards: 0,
targetShards: 0
}
}
} as unknown as MsgInsertSwitchesSnapshot
}
function renderSwitches(): void {
render(
<ToastProvider>
<MessageInsertSwitches />
</ToastProvider>
)
}
describe('微信消息插入开关 · 运行期刷新', () => {
afterEach(() => {
vi.restoreAllMocks()
})
it('挂载只用 GET,不额外触发刷新', async () => {
const get = vi.fn().mockResolvedValue(makeSnapshot(1, 2))
const refresh = vi.fn().mockResolvedValue(makeSnapshot(2, 2))
window.api = {
getMsgInsertSwitches: get,
refreshMsgInsertSwitches: refresh
} as unknown as typeof window.api
renderSwitches()
await waitFor(() => expect(get).toHaveBeenCalled())
expect(refresh).not.toHaveBeenCalled()
})
it('窗口重新聚焦时刷新一次,并画出更新后的计数', async () => {
const get = vi.fn().mockResolvedValue(makeSnapshot(1, 2))
const refresh = vi.fn().mockResolvedValue(makeSnapshot(2, 2))
window.api = {
getMsgInsertSwitches: get,
refreshMsgInsertSwitches: refresh
} as unknown as typeof window.api
renderSwitches()
await waitFor(() => expect(document.body.textContent).toContain('1 / 2 已启用'))
await act(async () => {
window.dispatchEvent(new Event('focus'))
})
await waitFor(() => expect(refresh).toHaveBeenCalledTimes(1))
await waitFor(() => expect(document.body.textContent).toContain('2 / 2 已启用'))
})
it('刷新失败时保持已有状态,不打回禁用态', async () => {
const get = vi.fn().mockResolvedValue(makeSnapshot(1, 2))
const refresh = vi.fn().mockRejectedValue(new Error('boom'))
window.api = {
getMsgInsertSwitches: get,
refreshMsgInsertSwitches: refresh
} as unknown as typeof window.api
renderSwitches()
await waitFor(() => expect(document.body.textContent).toContain('1 / 2 已启用'))
await act(async () => {
window.dispatchEvent(new Event('focus'))
})
await waitFor(() => expect(refresh).toHaveBeenCalled())
expect(document.body.textContent).toContain('1 / 2 已启用')
})
})
+61 -3
View File
@@ -1,9 +1,11 @@
import fs from 'fs-extra'
import { join } from 'path'
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
const fixture = vi.hoisted(() => ({
root: `/tmp/wxe-local-api-auth-${process.pid}`,
storageAvailable: true,
skillVersion: '9.9.9',
contacts: [
{
m_nsUsrName: 'wxid_fixture',
@@ -29,7 +31,16 @@ const fixture = vi.hoisted(() => ({
}))
vi.mock('electron', () => ({
app: { getPath: () => fixture.root, getVersion: () => 'test-version' },
app: {
getPath: () => fixture.root,
getAppPath: () => fixture.root,
getVersion: () => 'test-version',
isPackaged: false
},
shell: {
openPath: async () => '',
openExternal: async () => undefined
},
safeStorage: {
isEncryptionAvailable: () => fixture.storageAvailable,
encryptString: (value: string) => Buffer.from(`encrypted:${value}`, 'utf8'),
@@ -99,7 +110,13 @@ async function startFixtureServer(
}
describe('Local API authentication', () => {
beforeAll(() => fs.ensureDirSync(fixture.root))
beforeAll(() => {
fs.ensureDirSync(fixture.root)
fs.outputFileSync(
join(fixture.root, 'docs', 'skill', 'tracememo-reader', 'SKILL.md'),
`---\nname: tracememo-reader\nversion: ${fixture.skillVersion}\ndescription: fixture\n---\n\n# TraceMemo Reader fixture\n`
)
})
beforeEach(() => {
fixture.storageAvailable = true
@@ -135,6 +152,46 @@ describe('Local API authentication', () => {
await expect(response.json()).resolves.toMatchObject({ count: 1 })
})
it('advertises the Reader Skill version on health and serves SKILL.md to authenticated agents', async () => {
const handle = await startFixtureServer()
const health = await (await fetch(`${baseUrl(handle)}/api/v1/health`)).json()
expect(health).toMatchObject({
ok: true,
skill: { name: 'tracememo-reader', version: fixture.skillVersion, available: true }
})
const path = `${baseUrl(handle)}/api/v1/skill/tracememo-reader`
expect((await fetch(path)).status).toBe(401)
const response = await fetch(path, { headers: { Authorization: `Bearer ${VALID_TOKEN}` } })
expect(response.status).toBe(200)
const body = await response.json()
expect(body).toMatchObject({ name: 'tracememo-reader', version: fixture.skillVersion })
expect(body.markdown).toContain(`version: ${fixture.skillVersion}`)
expect(body.contentHash).toMatch(/^[0-9a-f]{64}$/)
expect(JSON.stringify(body)).not.toMatch(/token|authorization|wxid|databasePath|provider/i)
})
// 外部 Agent 靠 health 上的 skill.version 判断 Skill 是否过期,
// 所以首选位置读不到时也必须正常回答(回退到下一个候选),不能整条 500。
it('falls back to the next Skill candidate and still answers health', async () => {
const handle = await startFixtureServer()
const skillPath = join(fixture.root, 'docs', 'skill', 'tracememo-reader', 'SKILL.md')
const backup = fs.readFileSync(skillPath, 'utf-8')
fs.removeSync(skillPath)
try {
const response = await fetch(`${baseUrl(handle)}/api/v1/health`)
expect(response.status).toBe(200)
const body = await response.json()
expect(body.ok).toBe(true)
expect(body.skill).toMatchObject({ name: 'tracememo-reader', available: true })
expect(body.skill.version).toMatch(/^\d+\.\d+\.\d+$/)
} finally {
fs.outputFileSync(skillPath, backup)
}
})
it.each([
['POST', '/api/v1/health', 'GET'],
['PATCH', '/api/v1/current_time', 'GET'],
@@ -217,7 +274,8 @@ describe('Local API authentication', () => {
['POST', '/api/v1/agent/send'],
['GET', '/api/v1/query/capabilities'],
['POST', '/api/v1/query/messages'],
['POST', '/api/v1/query/voice-transcribe']
['POST', '/api/v1/query/voice-transcribe'],
['GET', '/api/v1/skill/tracememo-reader']
])('protects every non-health route: %s %s', async (method, pathname) => {
const handle = await startFixtureServer()
const response = await fetch(`${baseUrl(handle)}${pathname}`, {
+2 -3
View File
@@ -1,6 +1,6 @@
{
"note": "测试文件类型检查基线:只允许下降,不允许上升。用 node scripts/typecheck-tests.cjs --update 下调。",
"total": 209,
"total": 203,
"files": {
"tests/component/ai-model-settings.test.tsx": 2,
"tests/component/ai-search-cache-consent.test.tsx": 3,
@@ -32,7 +32,6 @@
"tests/integration/image-text-index-synthetic-e2e.test.ts": 22,
"tests/integration/query-agent-image-ocr-text.test.ts": 16,
"tests/integration/query-agent-self-direction.test.ts": 7,
"tests/unit/agent-hub-routing.test.ts": 1,
"tests/unit/ai-search-pipeline-service.test.ts": 1,
"tests/unit/ai-search-provider-consent.test.ts": 5,
"tests/unit/ai-search-workspace-pure-functions.test.ts": 13,
@@ -40,7 +39,7 @@
"tests/unit/group-report.test.ts": 1,
"tests/unit/http-media-service.test.ts": 2,
"tests/unit/knowledge-freshness.test.ts": 1,
"tests/unit/local-query-api-service.test.ts": 51,
"tests/unit/local-query-api-service.test.ts": 46,
"tests/unit/message-state.test.ts": 1,
"tests/unit/query-agent-image-ocr-coverage.test.ts": 1,
"tests/unit/query-agent-service.test.ts": 4,
+61 -7
View File
@@ -1,5 +1,6 @@
import { describe, expect, it } from 'vitest'
import {
formatWechatReplyText,
matchGroupReportIntent,
matchRecentChatIntent,
queryAgentReplyText,
@@ -114,15 +115,46 @@ describe('Agent Hub 回复文案映射', () => {
outcome: 'answered' as const
}
/**
* 完整合法的 answered 结果。
* `evidence` / `stats` 是 contract 必填字段 —— 直接写字面量会缺字段报类型错。
*/
const answeredResult = (answer: string): AskWechatQueryResult => ({
engine: 'query-agent',
status: 'answered',
answer,
evidence: [],
stats: {
tools: [],
reads: { messageCount: 0, matchedCount: 0, overviewSourceCount: 0, evidenceCount: 0 },
modelCallCount: 0,
toolCallCount: 0,
totalMs: 0
},
diagnostics
})
it('answered → 直接用 Query Agent 的文本回答', () => {
expect(queryAgentReplyText(answeredResult('最近聊了两件事。'))).toBe('最近聊了两件事。')
})
it('answered → 剥离桌面 UI 的 [E#] 引用编号(微信里点不开,只剩噪音)', () => {
expect(
queryAgentReplyText({
engine: 'query-agent',
status: 'answered',
answer: '最近聊了两件事。',
diagnostics
})
).toBe('最近聊了两件事。')
queryAgentReplyText(
answeredResult('第一件事先看结论、第二件事要留缓冲[E6][E14],第三件不能直接上[E16]。')
)
).toBe('第一件事先看结论、第二件事要留缓冲,第三件不能直接上。')
})
it('独占一行的 [E#] 被移除,但不会把相邻两行粘成一行', () => {
expect(queryAgentReplyText(answeredResult('第一件事[E1]\n[E2]\n第二件事[E3]'))).toBe(
'第一件事\n\n第二件事'
)
})
it('整段只剩引用编号时原样兜底,绝不发空消息', () => {
// 防御分支:正常回答不会走到这里;真走到也宁可有内容,不能发一条空消息。
expect(queryAgentReplyText(answeredResult('[E1][E2]'))).toBe('[E1][E2]')
})
it('provider_unavailable / error → 使用安全文案', () => {
@@ -153,3 +185,25 @@ describe('Agent Hub 回复文案映射', () => {
expect(queryAgentReplyText(legacy)).toBe(QUERY_AGENT_UNAVAILABLE_TEXT)
})
})
describe('Agent Hub 微信文本排版 — 单换行会被压成空格', () => {
it('列表项之间改用空行,否则微信里连成一整段', () => {
expect(formatWechatReplyText('结论:两件事。\n• 做饭\n• 游戏')).toBe(
'结论:两件事。\n\n• 做饭\n\n• 游戏'
)
})
it('Markdown 列表标记归一成 • 后同样独立成行', () => {
expect(formatWechatReplyText('1. 先说结论\n- 做饭\n- 游戏')).toBe(
'1. 先说结论\n\n• 做饭\n\n• 游戏'
)
})
it('连续空行收敛成一个,不留多余空行', () => {
expect(formatWechatReplyText('A\n\n\n\nB')).toBe('A\n\nB')
})
it('水平线不会被误当成列表标记', () => {
expect(formatWechatReplyText('上文\n---\n下文')).toBe('上文\n---\n下文')
})
})
+124 -8
View File
@@ -247,7 +247,7 @@ describe('LocalQueryApiService', () => {
expect(result.sourceLatestAt).toBe(NOW - 1000)
expect(result.freshness).toEqual({ catchUp: 'pending' })
expect(knowledge.requestCatchUp).toHaveBeenCalledTimes(1)
expect(knowledge.waitForIndexingComplete).toHaveBeenCalledWith(2000)
expect(knowledge.waitForIndexingComplete).toHaveBeenCalledWith(15000)
})
it('追赶在预算内完成 → 用新索引重新检索(不能拿同步前的结果回答)', async () => {
@@ -315,7 +315,9 @@ describe('LocalQueryApiService', () => {
voiceCoverage: undefined
})
const result = await service.search({ target: { query: 'BOBO' }, timeRange: { kind: 'today' }, query: '健身' })
// 刻意**不带 target**:单会话现在会走直读兜底(结论句变成"已用直读补齐"),
// 而这条用例要守的是"索引落后且无法兜底时,结论句必须诚实说无法确认"。
const result = await service.search({ timeRange: { kind: 'today' }, query: '健身' })
expect(result.resolvedTimeRange?.endTime).toEqual(expect.any(Number))
// 请求边界(今天)晚于索引覆盖边界 4 分钟 → 只能 partial。
@@ -324,16 +326,129 @@ describe('LocalQueryApiService', () => {
expect(result.indexCoverage?.summary).toContain('暂时无法确认')
})
it('已有索引任务在跑 → 复用而不阻塞本次查询', async () => {
it('已有索引任务在跑 → 同样等一个有界预算,等不到才按旧覆盖如实回答', async () => {
fixture.contacts.splice(1)
knowledge.search.mockResolvedValue({ ...staleIndex(), sourceLatestAt: NOW - 1000 })
knowledge.requestCatchUp.mockReturnValue({ triggered: false, inProgress: true })
knowledge.waitForIndexingComplete.mockResolvedValue(false)
const result = await service.search({ target: { query: 'BOBO' }, timeRange: { kind: 'all' }, query: '健身' })
const result = await service.search({
target: { query: 'BOBO' },
timeRange: { kind: 'all' },
query: '健身'
})
expect(result.freshness).toEqual({ catchUp: 'reused' })
expect(knowledge.waitForIndexingComplete).not.toHaveBeenCalled()
expect(result.coverage).toEqual({ state: 'partial' })
// 复用场景必须等:直接返回旧快照会出现「索引明明在追,却拿旧覆盖下结论」。
expect(knowledge.waitForIndexingComplete).toHaveBeenCalledWith(15000)
// 用 toMatchObject 而不是逐字段断言:search() 的返回是联合类型,
// 直接取属性会撞上这个文件既有的"未收窄"类型债(棘轮不允许新增)。
expect(result).toMatchObject({
freshness: { catchUp: 'reused' },
coverage: { state: 'partial' }
})
})
it('复用的索引任务在预算内追完 → 重新检索,不允许拿同步前的结果回答', async () => {
fixture.contacts.splice(1)
knowledge.search
.mockResolvedValueOnce({ ...staleIndex(), sourceLatestAt: NOW - 1000 })
.mockResolvedValueOnce({
state: 'ready',
indexLatestAt: NOW - 30 * 1000,
sourceLatestAt: NOW - 1000,
voiceCoverage: undefined,
evidence: [
{
conversationId: 'md5-bobo',
messageId: 'new-1',
timestamp: NOW - 60_000,
sender: 'BOBO',
sourceKind: 'text',
text: '最近开始健身了'
}
]
})
knowledge.requestCatchUp.mockReturnValue({ triggered: false, inProgress: true })
knowledge.waitForIndexingComplete.mockResolvedValue(true)
const result = await service.search({
target: { query: 'BOBO' },
timeRange: { kind: 'all' },
query: '健身'
})
expect(knowledge.search).toHaveBeenCalledTimes(2)
expect(result).toMatchObject({
freshness: { catchUp: 'completed' },
coverage: { state: 'complete' },
evidenceCount: 1
})
})
it('索引没覆盖 + 范围恰是一个会话 → 直读原始记录兜底(微信机器人拿得到新消息)', async () => {
fixture.contacts.splice(1)
knowledge.search.mockResolvedValue({ ...staleIndex(), sourceLatestAt: NOW - 1000 })
knowledge.requestCatchUp.mockReturnValue({ triggered: true, inProgress: true })
knowledge.waitForIndexingComplete.mockResolvedValue(false)
const listSpy = listMessagesAsync as unknown as Mock
// 直读必须落在 begin/end 让路窗口**之内**:窗口外后台索引会抢 WCDB,
// 把直读拖成几十秒。用调用顺序固定这个不变量。
const order: string[] = []
knowledge.beginInteractiveQuery.mockImplementation(() => void order.push('begin'))
knowledge.endInteractiveQuery.mockImplementation(() => void order.push('end'))
listSpy.mockImplementation(async () => {
order.push('directRead')
return [
{
id: 'm9',
type: '普通文本',
datetime: '2026/9/9 11:58:00',
content: '刚提到过这个探针词',
isSender: false,
name: 'BOBO',
createTime: Math.floor((NOW - 2 * 60 * 1000) / 1000)
}
]
})
const result = await service.search({
target: { query: 'BOBO' },
timeRange: { kind: 'all' },
query: '探针词'
})
// 直读读的是权威源,证据拿得到 —— 这是微信机器人"能拿到东西"的关键。
// 但 coverage 仍如实是 partial:直读只补了索引水位之后那一段,更早的区间还是索引说了算。
expect(listSpy).toHaveBeenCalledTimes(1)
expect(result).toMatchObject({
coverage: { state: 'partial' },
evidenceCount: 1,
evidence: [{ text: '刚提到过这个探针词', sender: 'BOBO' }]
})
// 结论句必须说明"这段已用直读补上",否则模型会一边拿着证据、一边说"暂时无法确认"。
const indexCoverage = (
result as unknown as { indexCoverage?: { covered: boolean; summary: string } }
).indexCoverage
expect(indexCoverage?.covered).toBe(false)
expect(indexCoverage?.summary).toContain('直读原始记录补齐')
expect(order).toEqual(['begin', 'directRead', 'end'])
})
it('索引没覆盖但范围跨多个会话 → 不直读兜底,仍如实 partial', async () => {
knowledge.search.mockResolvedValue({ ...staleIndex(), sourceLatestAt: NOW - 1000 })
knowledge.requestCatchUp.mockReturnValue({ triggered: true, inProgress: true })
knowledge.waitForIndexingComplete.mockResolvedValue(false)
const listSpy = listMessagesAsync as unknown as Mock
const result = await service.search({
timeRange: { kind: 'all' },
query: '探针词',
scope: { kind: 'all' }
})
// 跨会话直读要遍历上千个会话(大会话全量读一次 15s+),只能保持 partial。
expect(listSpy).not.toHaveBeenCalled()
expect(result).toMatchObject({ coverage: { state: 'partial' }, evidenceCount: 0 })
})
it('追平后 0 结果才允许 complete negative;落后时同一条件只能是 partial', async () => {
@@ -417,7 +532,8 @@ describe('LocalQueryApiService — indexCoverage 结论句', () => {
})
it('落后时给出可直接引用的本地时间结论,且明确"暂时无法确认"', async () => {
const result = await service2.search({ target: { query: 'BOBO' }, timeRange: { kind: 'all' }, query: '健身' })
// 同样刻意不带 target —— 见上一条:单会话已经会走直读兜底。
const result = await service2.search({ timeRange: { kind: 'all' }, query: '健身' })
expect(result.coverage).toEqual({ state: 'partial' })
// 8/30 12:00 的本地时间标签(固定时钟下可断言)
expect(result.indexCoverage?.covered).toBe(false)
@@ -323,6 +323,11 @@ describe('定时日报 · 微信异常通知', () => {
const text = sendNotification.mock.calls[0][0].text as string
expect(text).toContain('每日晚报')
expect(text).toContain('日报生成失败')
// 必须带**失败发生时刻**:同一批补发的多条失败文案可能一模一样,
// 只有这个时间戳能把它们区分开。
expect(text).toContain('8月27日 18:31')
// 必须用空行分隔:微信把单个换行压成空格,否则整条通知连成一行。
expect(text).toContain('定时日报执行失败\n\n日报生成失败')
const notifications = await service.listNotifications()
expect(notifications).toHaveLength(1)
+132 -24
View File
@@ -1,9 +1,12 @@
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'fs'
import { createHash } from 'crypto'
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs'
import { tmpdir } from 'os'
import { dirname, join, resolve } from 'path'
import { afterEach, describe, expect, it } from 'vitest'
import {
getSkillCandidates,
parseSkillFrontmatter,
readSkillDocument,
resolveSkillResourceStatus
} from '../../src/main/services/skill-resource-service'
@@ -25,9 +28,18 @@ function environment(root: string, packaged: boolean) {
}
}
function writeSkill(filePath: string): void {
function skillBody(version?: string): string {
const versionLine = version ? `version: ${version}\n` : ''
return `---\nname: tracememo-reader\n${versionLine}description: fixture\n---\n\n# TraceMemo Reader\n\n正文内容。\n`
}
function writeSkill(filePath: string, version?: string): void {
mkdirSync(dirname(filePath), { recursive: true })
writeFileSync(filePath, '# TraceMemo Reader\n', 'utf8')
writeFileSync(filePath, skillBody(version), 'utf8')
}
function sha256(content: string): string {
return createHash('sha256').update(content, 'utf8').digest('hex')
}
describe('Reader Skill resource resolution', () => {
@@ -39,44 +51,28 @@ describe('Reader Skill resource resolution', () => {
const root = fixtureRoot()
const runtime = environment(root, false)
const skillPath = join(runtime.cwd, 'docs', 'skill', 'tracememo-reader', 'SKILL.md')
writeSkill(skillPath)
writeSkill(skillPath, '1.3.0')
expect(resolveSkillResourceStatus(runtime)).toMatchObject({
available: true,
source: 'development',
version: 'v1.2',
name: 'tracememo-reader',
version: '1.3.0',
filePath: skillPath,
directoryPath: dirname(skillPath)
})
})
it('resolves the Reader Skill from this checkout', () => {
const workspace = resolve(__dirname, '../..')
const status = resolveSkillResourceStatus({
appPath: workspace,
cwd: workspace,
resourcesPath: join(workspace, 'node_modules', 'electron', 'resources'),
execPath: join(workspace, 'node_modules', 'electron', 'electron.exe'),
packaged: false
})
expect(status).toMatchObject({
available: true,
source: 'development',
version: 'v1.2',
filePath: join(workspace, 'docs', 'skill', 'tracememo-reader', 'SKILL.md')
})
})
it('uses the extraResources Skill directory in a packaged runtime', () => {
const root = fixtureRoot()
const runtime = environment(root, true)
const skillPath = join(runtime.resourcesPath, 'skill', 'tracememo-reader', 'SKILL.md')
writeSkill(skillPath)
writeSkill(skillPath, '1.3.0')
expect(resolveSkillResourceStatus(runtime)).toMatchObject({
available: true,
source: 'bundled',
version: '1.3.0',
filePath: skillPath
})
})
@@ -104,4 +100,116 @@ describe('Reader Skill resource resolution', () => {
expect(status).toMatchObject({ available: false, source: 'development' })
for (const candidate of candidates) expect(status.error).toContain(candidate.path)
})
it('omits the version when the frontmatter does not declare one', () => {
const root = fixtureRoot()
const runtime = environment(root, false)
const skillPath = join(runtime.cwd, 'docs', 'skill', 'tracememo-reader', 'SKILL.md')
writeSkill(skillPath)
const status = resolveSkillResourceStatus(runtime)
expect(status.available).toBe(true)
expect(status.version).toBeUndefined()
})
// /health 是外部 Agent 的自检入口:环境探测本身出错时只能降级,不能抛出。
it('degrades to unavailable instead of throwing when the environment is broken', () => {
const status = resolveSkillResourceStatus({
appPath: undefined as unknown as string,
cwd: undefined as unknown as string,
resourcesPath: '',
execPath: undefined as unknown as string,
packaged: false
})
expect(status.available).toBe(false)
expect(status.error).toContain('未找到 TraceMemo Reader Skill 文件')
expect(status.githubUrl).toContain('github.com')
})
})
describe('Reader Skill document identity', () => {
afterEach(() => {
while (roots.length) rmSync(roots.pop()!, { recursive: true, force: true })
})
it('exposes markdown, version and a content hash that matches the file bytes', () => {
const root = fixtureRoot()
const skillPath = join(root, 'docs', 'skill', 'tracememo-reader', 'SKILL.md')
writeSkill(skillPath, '1.3.0')
const content = readFileSync(skillPath, 'utf-8')
const document = readSkillDocument(skillPath)
expect(document).not.toBeNull()
expect(document?.version).toBe('1.3.0')
expect(document?.name).toBe('tracememo-reader')
expect(document?.markdown).toBe(content)
expect(document?.contentHash).toBe(sha256(content))
expect(document?.filePath).toBe(skillPath)
expect(Number.isNaN(Date.parse(document?.modifiedAt || ''))).toBe(false)
})
it('returns null for a missing file instead of throwing', () => {
const root = fixtureRoot()
expect(readSkillDocument(join(root, 'missing', 'SKILL.md'))).toBeNull()
})
// 自助更新的正确性依赖这条:Agent 覆盖 SKILL.md 后,health 必须立刻报出新版本。
it('invalidates the cache once the file on disk is replaced', () => {
const root = fixtureRoot()
const skillPath = join(root, 'docs', 'skill', 'tracememo-reader', 'SKILL.md')
writeSkill(skillPath, '1.3.0')
expect(readSkillDocument(skillPath)?.version).toBe('1.3.0')
writeSkill(skillPath, '1.4.0-with-a-longer-body-to-change-the-file-size')
const updated = readSkillDocument(skillPath)
expect(updated?.version).toBe('1.4.0-with-a-longer-body-to-change-the-file-size')
expect(updated?.contentHash).not.toBe(sha256(skillBody('1.3.0')))
})
})
describe('SKILL.md frontmatter contract', () => {
it('parses name and version from a plain frontmatter block', () => {
expect(parseSkillFrontmatter('---\nname: a\nversion: 2.1.0\n---\nbody')).toEqual({
name: 'a',
version: '2.1.0'
})
})
it('ignores files without frontmatter and tolerates CRLF, quotes and comments', () => {
expect(parseSkillFrontmatter('# no frontmatter\n')).toEqual({})
expect(parseSkillFrontmatter('---\r\n# comment\r\nversion: "3.0.1"\r\n---\r\n')).toEqual({
version: '3.0.1'
})
})
/**
* 防漂移契约:版本号只有一个真源,就是 SKILL.md 的 frontmatter。
* 这里独立地按行正则提取一次,与解析结果逐字比对 —— 任何"把版本写回源码常量"的
* 回归都会让这条测试变红。
*/
it('keeps the reader Skill version declared in the repository SKILL.md', () => {
const workspace = resolve(__dirname, '../..')
const skillPath = join(workspace, 'docs', 'skill', 'tracememo-reader', 'SKILL.md')
const content = readFileSync(skillPath, 'utf-8')
const declared = /^version:[ \t]*(\S+)[ \t]*$/m.exec(content)
expect(declared).not.toBeNull()
expect(parseSkillFrontmatter(content).version).toBe(declared![1])
expect(declared![1]).toMatch(/^\d+\.\d+\.\d+$/)
const status = resolveSkillResourceStatus({
appPath: workspace,
cwd: workspace,
resourcesPath: join(workspace, 'node_modules', 'electron', 'resources'),
execPath: join(workspace, 'node_modules', 'electron', 'electron.exe'),
packaged: false
})
expect(status).toMatchObject({
available: true,
source: 'development',
version: declared![1],
filePath: skillPath
})
})
})