dsh-spec-collab 0.2.0 → 0.2.1

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.
@@ -1,28 +1,38 @@
1
1
  import type { ApiProxy, RpcId } from '@deepseek-ai/dsh-host-apiproxy'
2
2
  import type { AiCoordinator } from './engine.ts'
3
3
  import type { AiReviewRun, CommentThread, RequirementView, ReviewWorkspaceSummary } from './protocol.ts'
4
+ import { DEFAULT_REVIEW_PROMPTS, extractPromptValue, renderPrompt, resolveReviewPrompts, type ResolvedReviewPrompts, type ReviewPromptConfig } from './prompts.ts'
4
5
  import { ReviewContextCatalog, reviewContextPrompt } from './review-context.ts'
6
+ import { readWorkspaceSnapshot } from './workspace-context.ts'
5
7
 
6
8
  function request<T>(payload: T) { return { rpcId: `spec-collab-${crypto.randomUUID()}` as RpcId, payload } }
7
9
  function failure(error: { code: string; message: string }): Error { return new Error(`${error.code}: ${error.message}`) }
10
+ const FOLLOW_UP_METADATA = '\n\n<!-- dsh-spec-collab-follow-up:'
8
11
 
9
12
  export class DshReviewCoordinator implements AiCoordinator {
10
- constructor(private readonly api: ApiProxy, private readonly contexts = new ReviewContextCatalog()) {}
13
+ private readonly prompts: ResolvedReviewPrompts
14
+ constructor(private readonly api: ApiProxy, private readonly contexts = new ReviewContextCatalog(), prompts: ReviewPromptConfig = {}) {
15
+ this.prompts = resolveReviewPrompts(prompts)
16
+ }
11
17
  async reviewWorkspaces(): Promise<ReviewWorkspaceSummary[]> {
12
18
  const listed = await this.api.workspace.list(request({}))
13
19
  if (!listed.result.ok) throw failure(listed.result.error)
14
20
  return listed.result.value.items.map(item => ({ workspaceId: item.workspaceId, title: item.title, path: item.path }))
15
21
  }
16
22
  async assertWorkspaceAvailable(workspaceId: string): Promise<void> {
17
- if (!(await this.reviewWorkspaces()).some(item => item.workspaceId === workspaceId)) throw new Error(`workspace not found: ${workspaceId}`)
23
+ await this.resolveWorkspace(workspaceId)
18
24
  }
19
- requestReview(input: { requirement: RequirementView; run: AiReviewRun }): Promise<string> {
25
+ async requestReview(input: { requirement: RequirementView; run: AiReviewRun }): Promise<string> {
20
26
  const context = this.contexts.resolve(input.requirement.workspaceId)
21
- return this.launch(`Spec ${input.run.kind}: ${input.requirement.title}`, reviewPrompt(input.requirement, input.run, context), context.workspaceId, context.agentPreset)
27
+ const workspace = await this.resolveWorkspace(context.workspaceId)
28
+ const snapshot = await readWorkspaceSnapshot(workspace.path, context.documentPaths)
29
+ return this.launch(`Spec ${input.run.kind}: ${input.requirement.title}`, reviewPrompt(input.requirement, input.run, context, workspace, snapshot, this.prompts), context.workspaceId, context.agentPreset)
22
30
  }
23
- requestCommentReply(input: { requirement: RequirementView; comment: CommentThread }): Promise<string> {
31
+ async requestCommentReply(input: { requirement: RequirementView; comment: CommentThread }): Promise<string> {
24
32
  const context = this.contexts.resolve(input.requirement.workspaceId)
25
- return this.launch(`Spec comment analysis: ${input.requirement.title}`, commentPrompt(input.requirement, input.comment, context), context.workspaceId, context.agentPreset)
33
+ const workspace = await this.resolveWorkspace(context.workspaceId)
34
+ const snapshot = await readWorkspaceSnapshot(workspace.path, context.documentPaths)
35
+ return this.launch(`Spec comment analysis: ${input.requirement.title}`, commentPrompt(input.requirement, input.comment, context, workspace, snapshot, this.prompts), context.workspaceId, context.agentPreset)
26
36
  }
27
37
  async conversation(sessionId: string): Promise<Array<{ role: 'user' | 'assistant'; text: string }>> {
28
38
  const history = await this.api.sessions.history(request({ sessionId: sessionId as never }))
@@ -37,9 +47,11 @@ export class DshReviewCoordinator implements AiCoordinator {
37
47
  const content = isObject(message) && 'content' in message ? message.content : message
38
48
  let messageText = collectText(content).join('\n').trim()
39
49
  if (entry.event.type === 'user/message') {
40
- const marker = '请使用简体中文回答以下追问,并继续遵守当前 Spec 审核任务的证据、权限和结构化回写约束。'
41
- if (!messageText.startsWith(marker)) continue
42
- messageText = messageText.slice(marker.length).trim()
50
+ const followUp = storedFollowUp(messageText)
51
+ ?? extractPromptValue(messageText, this.prompts.followUp.trim(), 'CONTENT')
52
+ ?? extractPromptValue(messageText, DEFAULT_REVIEW_PROMPTS.followUp, 'CONTENT')
53
+ if (followUp === undefined) continue
54
+ messageText = followUp.trim()
43
55
  }
44
56
  if (messageText !== '') rows.push({ role: entry.event.type === 'user/message' ? 'user' : 'assistant', text: messageText })
45
57
  }
@@ -48,11 +60,12 @@ export class DshReviewCoordinator implements AiCoordinator {
48
60
  async followUp(sessionId: string, text: string): Promise<void> {
49
61
  const content = text.trim()
50
62
  if (content === '') throw new Error('追问内容不能为空')
51
- const prompted = await this.api.sessions.prompt(request({ sessionId: sessionId as never, mode: 'queue' as const, content: [{ type: 'text' as const, text: `请使用简体中文回答以下追问,并继续遵守当前 Spec 审核任务的证据、权限和结构化回写约束。\n\n${content}` }] }))
63
+ const metadata = Buffer.from(content, 'utf8').toString('base64url')
64
+ const promptText = `${renderPrompt(this.prompts.followUp, { CONTENT: content }).trim()}${FOLLOW_UP_METADATA}${metadata} -->`
65
+ const prompted = await this.api.sessions.prompt(request({ sessionId: sessionId as never, mode: 'queue' as const, content: [{ type: 'text' as const, text: promptText }] }))
52
66
  if (!prompted.result.ok) throw failure(prompted.result.error)
53
67
  }
54
68
  private async launch(title: string, promptText: string, workspaceId: string, agentPreset?: string): Promise<string> {
55
- await this.assertWorkspaceAvailable(workspaceId)
56
69
  if (agentPreset !== undefined) {
57
70
  const presets = await this.api.agentPresets.list(request({}))
58
71
  if (!presets.result.ok) throw failure(presets.result.error)
@@ -68,6 +81,19 @@ export class DshReviewCoordinator implements AiCoordinator {
68
81
  if (!prompted.result.ok) throw failure(prompted.result.error)
69
82
  return sessionId
70
83
  }
84
+ private async resolveWorkspace(workspaceId: string): Promise<ReviewWorkspaceSummary> {
85
+ const workspace = (await this.reviewWorkspaces()).find(item => item.workspaceId === workspaceId)
86
+ if (workspace === undefined) throw new Error(`workspace not found: ${workspaceId}`)
87
+ return workspace
88
+ }
89
+ }
90
+
91
+ function storedFollowUp(message: string): string | undefined {
92
+ const index = message.lastIndexOf(FOLLOW_UP_METADATA)
93
+ if (index < 0 || !message.endsWith(' -->')) return undefined
94
+ const encoded = message.slice(index + FOLLOW_UP_METADATA.length, -4)
95
+ if (!/^[A-Za-z0-9_-]+$/.test(encoded)) return undefined
96
+ try { return Buffer.from(encoded, 'base64url').toString('utf8') } catch { return undefined }
71
97
  }
72
98
 
73
99
  function isObject(value: unknown): value is Record<string, unknown> { return typeof value === 'object' && value !== null }
@@ -78,37 +104,30 @@ function collectText(value: unknown): string[] {
78
104
  return 'content' in value ? collectText(value.content) : []
79
105
  }
80
106
 
81
- function common(requirement: RequirementView, context: ReturnType<ReviewContextCatalog['resolve']>): string {
107
+ function common(requirement: RequirementView, context: ReturnType<ReviewContextCatalog['resolve']>, workspace: ReviewWorkspaceSummary, workspaceSnapshot: string, prompts: ResolvedReviewPrompts): string {
82
108
  return [
83
109
  `Requirement ID: ${requirement.id}`,
84
110
  `Pinned commit: ${requirement.currentCommit}`,
85
111
  '',
86
- reviewContextPrompt(context),
112
+ reviewContextPrompt(context, {
113
+ workspace,
114
+ workspaceSnapshot,
115
+ workspaceTemplate: prompts.workspaceContext,
116
+ resourceTemplate: prompts.resourceInstructions,
117
+ }),
87
118
  '',
88
- '所有面向用户的输出必须使用简体中文,包括 Review Item 的陈述、影响、问题、成熟度总结、候选 patch 摘要以及评论分析回复。仅保留代码标识、路径、commit SHA、AC ID、FACT / INFERENCE / ASSUMPTION / TO_VERIFY 等固定枚举为原文。',
89
- 'You are a review worker for a requirements clarification product. You must not implement code, generate downstream test delivery, create worktrees, deploy, or mark the requirement Ready. AI output is proposal data only and requires human confirmation.',
90
- 'A FACT must cite an accessible, version-pinned source. If evidence is unavailable, use TO_VERIFY; never invent historical or implementation conflicts.',
91
- 'Use spec_read to retrieve the exact current data. Do not modify files directly.',
92
- '每个 Review Item 默认给出三个 recommendedOptions。每个选项只表达一个决定,使用“选择 + 直接结果”的短句,建议不超过 45 个汉字;三个选项必须有真实差异,不得只是“接受、拒绝、待验证”的同义改写。确有四种独立方案时才允许第四项。',
93
- 'Review Item 的 question 只问一个可以直接回答的问题,建议不超过 40 个汉字。背景放在 statement,后果放在 impact,不要把背景、问题和多个子问题挤进 question 或选项。',
94
- '审核记录与正式文档必须分层:FACT / INFERENCE / ASSUMPTION / TO_VERIFY、commit SHA、run ID 等只用于结构化审核记录,不得堆入候选 Spec 正文。',
95
- '候选 Spec 必须使用产品和研发都能直接理解的自然中文。避免行业黑话、审计腔和无必要的英文;英文缩写首次出现时必须同时写出中文含义,例如“行动按钮(CTA)”,后续优先使用中文。无法准确解释的缩写不要使用。',
96
- '优先使用这些通俗说法:操作按钮(不用 CTA)、统一风格标识(不用 canonical key)、点赞(不用 like)、提示词(不用 prompt)、测试数据(不用 fixture)、最终判断依据(不用事实源)、完成状态(不用终态)、重复操作结果一致(不用幂等)。Upgrade、Download、Lite、Plus 等确为界面文案或套餐名时可保留,但首次出现要说明中文含义。',
97
- '正文不要写“当前唯一可访问来源”“固定于某 commit”“统一记为 TO_VERIFY”这类过程说明。资料不足时,只在“待补充资料”章节按“资料名称:需要补充的内容;负责人(如已知)”列出,不重复背景、不写内部状态枚举。',
98
- '每段只表达一个结论,优先使用短句和具体业务语言。删除不影响需求理解、研发实现或验收判断的元信息。',
99
- '候选 patch 直接从文档标题开始,不写“本文为候选 patch”“不代表已确认决策”等免责声明。保留清晰的 Markdown 章节;身份与权限差异优先用表格,验收标准使用“前提 / 操作 / 预期结果”,不要使用 Given / When / Then。',
100
- '合并重复内容:目标讲用户结果,范围只列做与不做,业务规则只定义规则,验收标准只写可验证场景。同一句规则不要再分别复制到目标、范围、术语、验收和风险章节。',
119
+ prompts.common,
101
120
  ].join('\n')
102
121
  }
103
- function reviewPrompt(requirement: RequirementView, run: AiReviewRun, context: ReturnType<ReviewContextCatalog['resolve']>): string {
122
+ function reviewPrompt(requirement: RequirementView, run: AiReviewRun, context: ReturnType<ReviewContextCatalog['resolve']>, workspace: ReviewWorkspaceSummary, workspaceSnapshot: string, prompts: ResolvedReviewPrompts): string {
104
123
  const tasks: Record<AiReviewRun['kind'], string> = {
105
- 'product-first': 'Perform the initial product review across goal, evidence, history-conflict, current-implementation, scope, semantics, completeness, acceptance, and risk. Submit structured findings with spec_submit_review. If the draft needs changes, also submit a candidate patch with spec_propose_patch. The candidate document must follow the plain-language and audit-metadata separation rules above.',
106
- 'product-second': 'Review product responses against their original Review Items. Do not close vague answers. Submit remaining/new findings with spec_submit_review and a reviewable candidate patch with spec_propose_patch. Rewrite awkward inherited wording instead of copying internal review terminology into the document.',
107
- 'engineering-precheck': 'Read the product-confirmed Spec and inspect relevant current code/history available in the workspace. Find implementation fact conflicts, affected entries/roles/states, technical ambiguity, compatibility/permission/data boundaries, and unverifiable acceptance criteria. Submit with spec_submit_review and propose a patch only when needed.',
108
- 'change-review': 'Review only the latest saved commit against its parent. Identify materiality, affected sections/ACs, confirmations or decisions that need reconfirmation, and new conflicts. Submit with spec_submit_review; propose a patch only when needed.',
124
+ 'product-first': prompts.productFirst,
125
+ 'product-second': prompts.productSecond,
126
+ 'engineering-precheck': prompts.engineeringPrecheck,
127
+ 'change-review': prompts.changeReview,
109
128
  }
110
- return [common(requirement, context), `Review run ID: ${run.id}`, `Review kind: ${run.kind}`, `AI session ID: {{SESSION_ID}}`, '', tasks[run.kind]].join('\n')
129
+ return [common(requirement, context, workspace, workspaceSnapshot, prompts), `Review run ID: ${run.id}`, `Review kind: ${run.kind}`, `AI session ID: {{SESSION_ID}}`, '', tasks[run.kind]].join('\n')
111
130
  }
112
- function commentPrompt(requirement: RequirementView, comment: CommentThread, context: ReturnType<ReviewContextCatalog['resolve']>): string {
113
- return [common(requirement, context), `Comment ID: ${comment.id}`, `Anchor quote: ${comment.anchor.quote}`, `Human comment: ${comment.body}`, `AI session ID: {{SESSION_ID}}`, '', 'Analyze this substantive comment. First query any code/document facts you can obtain. Then use spec_reply exactly once with your understanding, versioned evidence or TO_VERIFY status, affected sections/ACs, and recommended disposition. Do not silently modify the Spec or choose between conflicting product and engineering positions.'].join('\n')
131
+ function commentPrompt(requirement: RequirementView, comment: CommentThread, context: ReturnType<ReviewContextCatalog['resolve']>, workspace: ReviewWorkspaceSummary, workspaceSnapshot: string, prompts: ResolvedReviewPrompts): string {
132
+ return [common(requirement, context, workspace, workspaceSnapshot, prompts), `Comment ID: ${comment.id}`, `Anchor quote: ${comment.anchor.quote}`, `Human comment: ${comment.body}`, `AI session ID: {{SESSION_ID}}`, '', prompts.comment].join('\n')
114
133
  }
package/src/tools.ts CHANGED
@@ -25,7 +25,7 @@ export function specReadTool(engine: CollaborationEngine) {
25
25
  const include = new Set(args.include ?? ['spec', 'review-items', 'comments', 'decisions', 'confirmations', 'sources', 'readiness'])
26
26
  const rows = [`# ${view.title}`, `stage: ${view.stage}`, `commit: ${view.currentCommit}`]
27
27
  if (include.has('spec')) rows.push('', '## Spec', view.version.markdown)
28
- if (include.has('review-items')) rows.push('', '## Review Items', ...view.reviewItems.map(item => `- ${item.id} [${item.severity}/${item.status}/${item.epistemicStatus}] ${item.statement}\n Question: ${item.question}\n Recommended options: ${(item.recommendedOptions ?? []).join(' / ') || 'none'}\n Evidence: ${item.evidence.map(evidence => `${evidence.source}${evidence.version ? `@${evidence.version}` : ''}`).join(', ') || 'none'}`))
28
+ if (include.has('review-items')) rows.push('', '## Review Items', ...view.reviewItems.map(item => `- ${item.id} [${item.severity}/${item.status}/${item.epistemicStatus}] ${item.statement}\n Question: ${item.question}\n Spec anchors: ${(item.sourceAnchors ?? []).map(anchor => `${anchor.heading ? `${anchor.heading}: ` : ''}${anchor.quote}`).join(' / ') || 'none'}\n Recommended options: ${(item.recommendedOptions ?? []).join(' / ') || 'none'}\n Evidence: ${item.evidence.map(evidence => `${evidence.source}${evidence.version ? `@${evidence.version}` : ''}`).join(', ') || 'none'}`))
29
29
  if (include.has('comments')) rows.push('', '## Comments', ...view.comments.map(item => `- ${item.id} [${item.status}] “${item.anchor.quote}” ${item.author.nickname}: ${item.body}\n Replies: ${item.replies.map(reply => `${reply.author.nickname}: ${reply.body}`).join(' / ') || 'none'}`))
30
30
  if (include.has('decisions')) rows.push('', '## Decisions', ...view.decisions.map(item => `- ${item.id} [${item.status}] ${item.question}: ${item.decision}`))
31
31
  if (include.has('confirmations')) rows.push('', '## Confirmations', ...view.confirmations.map(item => `- ${item.role}/${item.scope}/${item.scopeId ?? 'document'} [${item.status}] ${item.participant.nickname} @ ${item.commit}`))
@@ -52,7 +52,7 @@ export function specSubmitReviewTool(engine: CollaborationEngine) {
52
52
  requirementId: { type: 'string', required: true }, commit: { type: 'string', required: true }, runId: { type: 'string', required: true }, reviewKind: { type: 'string', required: true, enum: ['product-first', 'product-second', 'engineering-precheck', 'change-review'] },
53
53
  nickname: { type: 'string', required: true }, role: { type: 'string', required: true, enum: ['product', 'engineering'] }, sessionId: { type: 'string', required: true }, maturitySummary: { type: 'string', required: true },
54
54
  items: { type: 'array', required: true, items: { type: 'object', additionalProperties: false, properties: {
55
- type: { type: 'string', required: true, enum: ['goal', 'evidence', 'history-conflict', 'current-implementation', 'scope', 'semantics', 'completeness', 'acceptance', 'risk'] }, severity: { type: 'string', required: true, enum: ['blocking', 'major', 'minor'] }, statement: { type: 'string', required: true }, epistemicStatus: { type: 'string', required: true, enum: ['FACT', 'INFERENCE', 'ASSUMPTION', 'TO_VERIFY'] }, impact: { type: 'string', required: true }, question: { type: 'string', required: true, description: '只问一个可直接回答的问题,使用简洁中文。' }, recommendedOptions: { type: 'array', required: true, items: { type: 'string' }, description: '默认三个、最多四个互有取舍的中文选项;每项只表达一个决定,建议不超过 45 个汉字。' }, affectedSections: { type: 'array', required: true, items: { type: 'string' } }, affectedAcceptanceIds: { type: 'array', required: true, items: { type: 'string' } }, ownerRole: { type: 'string', required: true, enum: ['product', 'engineering'] }, status: { type: 'string', required: true, enum: ['open', 'joint-review', 'non-blocking-verify'] }, evidence: { type: 'array', required: true, items: { type: 'object', additionalProperties: false, properties: { statement: { type: 'string', required: true }, source: { type: 'string', required: true }, version: { type: 'string' }, accessible: { type: 'boolean', required: true } } } },
55
+ type: { type: 'string', required: true, enum: ['goal', 'evidence', 'history-conflict', 'current-implementation', 'scope', 'semantics', 'completeness', 'acceptance', 'risk'] }, severity: { type: 'string', required: true, enum: ['blocking', 'major', 'minor'] }, statement: { type: 'string', required: true }, epistemicStatus: { type: 'string', required: true, enum: ['FACT', 'INFERENCE', 'ASSUMPTION', 'TO_VERIFY'] }, impact: { type: 'string', required: true }, question: { type: 'string', required: true, description: '只问一个可直接回答的问题,使用简洁中文。' }, recommendedOptions: { type: 'array', required: true, items: { type: 'string' }, description: '默认三个、最多四个互有取舍的中文选项;每项只表达一个决定,建议不超过 45 个汉字。' }, sourceAnchors: { type: 'array', required: true, description: '直接从当前 Spec 原文复制 1-3 段精确短句;问题来自缺失内容时可为空数组。', items: { type: 'object', additionalProperties: false, properties: { quote: { type: 'string', required: true }, heading: { type: 'string' } } } }, affectedSections: { type: 'array', required: true, items: { type: 'string' } }, affectedAcceptanceIds: { type: 'array', required: true, items: { type: 'string' } }, ownerRole: { type: 'string', required: true, enum: ['product', 'engineering'] }, status: { type: 'string', required: true, enum: ['open', 'joint-review', 'non-blocking-verify'] }, evidence: { type: 'array', required: true, items: { type: 'object', additionalProperties: false, properties: { statement: { type: 'string', required: true }, source: { type: 'string', required: true }, version: { type: 'string' }, accessible: { type: 'boolean', required: true } } } },
56
56
  } } },
57
57
  },
58
58
  output: contentOutput('Review submission result.'),
@@ -65,7 +65,7 @@ export function specSubmitReviewTool(engine: CollaborationEngine) {
65
65
  if ([...item.question.trim()].length > 80) throw new Error('review questions must be concise (80 characters maximum)')
66
66
  if (item.epistemicStatus === 'FACT' && !item.evidence.some(evidence => evidence.accessible && typeof evidence.version === 'string' && evidence.version !== '')) throw new Error('FACT requires accessible versioned evidence')
67
67
  }
68
- engine.submitReview({ requirementId: args.requirementId, commit: args.commit, runId: args.runId, ai: ai(args.nickname, args.role as ParticipantRole, args.sessionId), maturitySummary: args.maturitySummary, items: args.items.map(item => ({ type: item.type as ReviewItemType, severity: item.severity as Severity, statement: item.statement, evidence: item.evidence, epistemicStatus: item.epistemicStatus as EpistemicStatus, impact: item.impact, question: item.question, recommendedOptions: item.recommendedOptions, affectedSections: item.affectedSections, affectedAcceptanceIds: item.affectedAcceptanceIds, ownerRole: item.ownerRole as ParticipantRole, status: item.status as ReviewItemStatus })) })
68
+ engine.submitReview({ requirementId: args.requirementId, commit: args.commit, runId: args.runId, ai: ai(args.nickname, args.role as ParticipantRole, args.sessionId), maturitySummary: args.maturitySummary, items: args.items.map(item => ({ type: item.type as ReviewItemType, severity: item.severity as Severity, statement: item.statement, evidence: item.evidence, epistemicStatus: item.epistemicStatus as EpistemicStatus, impact: item.impact, question: item.question, recommendedOptions: item.recommendedOptions, sourceAnchors: item.sourceAnchors.map(anchor => ({ quote: anchor.quote.trim(), ...(anchor.heading?.trim() ? { heading: anchor.heading.trim() } : {}) })).filter(anchor => anchor.quote), affectedSections: item.affectedSections, affectedAcceptanceIds: item.affectedAcceptanceIds, ownerRole: item.ownerRole as ParticipantRole, status: item.status as ReviewItemStatus })) })
69
69
  return { content: `submitted ${args.items.length} review items for ${args.commit}` }
70
70
  },
71
71
  })
@@ -0,0 +1,114 @@
1
+ import { readdir, readFile, stat } from 'node:fs/promises'
2
+ import { extname, isAbsolute, relative, resolve } from 'node:path'
3
+
4
+ const MAX_FILES = 20
5
+ const MAX_FILE_BYTES = 16 * 1024
6
+ const MAX_TOTAL_BYTES = 64 * 1024
7
+ const MAX_DIRECTORY_DEPTH = 4
8
+ const MAX_ROOT_ENTRIES = 80
9
+
10
+ const PROJECT_CONTEXT_FILES = new Set([
11
+ 'agents.md', 'context.md', 'contributing.md', 'package.json', 'pyproject.toml', 'cargo.toml',
12
+ 'go.mod', 'pom.xml', 'build.gradle', 'build.gradle.kts', 'requirements.txt', 'gemfile',
13
+ ])
14
+ const TEXT_EXTENSIONS = new Set([
15
+ '.md', '.mdx', '.txt', '.json', '.jsonc', '.yaml', '.yml', '.toml', '.xml', '.ini', '.cfg',
16
+ '.conf', '.properties', '.gradle', '.kts', '.mod', '.rst', '.adoc',
17
+ ])
18
+ const SKIP_DIRECTORIES = new Set(['.git', 'node_modules', 'dist', 'build', 'lib', 'coverage', '.next', '.cache'])
19
+
20
+ interface CandidateFile { path: string; displayPath: string }
21
+
22
+ export async function readWorkspaceSnapshot(workspaceRoot: string, documentPaths: string[]): Promise<string> {
23
+ const root = resolve(workspaceRoot)
24
+ const rows = ['## 插件已读取的工作区快照', `工作区根目录:\`${root}\``]
25
+ const notices: string[] = []
26
+ const candidates: CandidateFile[] = []
27
+ const seen = new Set<string>()
28
+
29
+ try {
30
+ const rootEntries = await readdir(root, { withFileTypes: true })
31
+ const visibleEntries = rootEntries
32
+ .filter(entry => !SKIP_DIRECTORIES.has(entry.name))
33
+ .sort((left, right) => left.name.localeCompare(right.name))
34
+ .slice(0, MAX_ROOT_ENTRIES)
35
+ .map(entry => entry.isDirectory() ? `${entry.name}/` : entry.name)
36
+ rows.push(`根目录条目:${visibleEntries.join('、') || '空目录'}`)
37
+ for (const entry of rootEntries) {
38
+ if (!entry.isFile() || !isProjectContextFile(entry.name)) continue
39
+ addCandidate(candidates, seen, resolve(root, entry.name), entry.name)
40
+ }
41
+ } catch (error) {
42
+ rows.push('根目录条目:无法读取')
43
+ notices.push(`- 工作区根目录无法读取:${errorMessage(error)}`)
44
+ }
45
+
46
+ for (const configuredPath of documentPaths) {
47
+ const path = isAbsolute(configuredPath) ? resolve(configuredPath) : resolve(root, configuredPath)
48
+ const displayPath = displayWorkspacePath(root, path)
49
+ try {
50
+ const value = await stat(path)
51
+ if (value.isFile()) addCandidate(candidates, seen, path, displayPath)
52
+ else if (value.isDirectory()) await collectDirectory(path, root, candidates, seen, 0)
53
+ else notices.push(`- 无法读取 \`${displayPath}\`:不是普通文件或目录。`)
54
+ } catch (error) {
55
+ notices.push(`- 无法读取 \`${displayPath}\`:${errorMessage(error)}`)
56
+ }
57
+ }
58
+
59
+ let totalBytes = 0
60
+ let renderedFiles = 0
61
+ for (const candidate of candidates) {
62
+ if (renderedFiles >= MAX_FILES || totalBytes >= MAX_TOTAL_BYTES) break
63
+ try {
64
+ const buffer = await readFile(candidate.path)
65
+ if (buffer.subarray(0, Math.min(buffer.length, 4096)).includes(0)) {
66
+ notices.push(`- 跳过二进制文件 \`${candidate.displayPath}\`。`)
67
+ continue
68
+ }
69
+ const availableBytes = Math.min(MAX_FILE_BYTES, MAX_TOTAL_BYTES - totalBytes)
70
+ const content = buffer.subarray(0, availableBytes).toString('utf8')
71
+ const truncated = buffer.length > availableBytes
72
+ rows.push('', `### \`${candidate.displayPath}\``, '<workspace-file>', content, truncated ? '\n[内容已截断]' : '', '</workspace-file>')
73
+ totalBytes += Buffer.byteLength(content)
74
+ renderedFiles += 1
75
+ } catch (error) {
76
+ notices.push(`- 无法读取 \`${candidate.displayPath}\`:${errorMessage(error)}`)
77
+ }
78
+ }
79
+ if (candidates.length > renderedFiles) notices.push(`- 工作区快照达到上限,仅注入前 ${renderedFiles} 个可读文本文件。`)
80
+ if (renderedFiles === 0) rows.push('', '未发现可注入的标准项目上下文文件。')
81
+ if (notices.length > 0) rows.push('', '### 读取说明', ...notices)
82
+ return rows.join('\n')
83
+ }
84
+
85
+ async function collectDirectory(directory: string, root: string, candidates: CandidateFile[], seen: Set<string>, depth: number): Promise<void> {
86
+ if (depth > MAX_DIRECTORY_DEPTH || candidates.length >= MAX_FILES) return
87
+ const entries = await readdir(directory, { withFileTypes: true })
88
+ for (const entry of entries.sort((left, right) => left.name.localeCompare(right.name))) {
89
+ if (candidates.length >= MAX_FILES) return
90
+ const path = resolve(directory, entry.name)
91
+ if (entry.isDirectory() && !SKIP_DIRECTORIES.has(entry.name)) await collectDirectory(path, root, candidates, seen, depth + 1)
92
+ else if (entry.isFile() && isTextFile(entry.name)) addCandidate(candidates, seen, path, displayWorkspacePath(root, path))
93
+ }
94
+ }
95
+
96
+ function addCandidate(candidates: CandidateFile[], seen: Set<string>, path: string, displayPath: string): void {
97
+ if (seen.has(path) || candidates.length >= MAX_FILES) return
98
+ seen.add(path)
99
+ candidates.push({ path, displayPath })
100
+ }
101
+
102
+ function isProjectContextFile(name: string): boolean {
103
+ const lower = name.toLowerCase()
104
+ return PROJECT_CONTEXT_FILES.has(lower) || lower === 'readme' || lower.startsWith('readme.')
105
+ }
106
+ function isTextFile(name: string): boolean { return isProjectContextFile(name) || TEXT_EXTENSIONS.has(extname(name).toLowerCase()) }
107
+ function displayWorkspacePath(root: string, path: string): string {
108
+ const value = relative(root, path)
109
+ return value !== '' && !value.startsWith('..') ? value : path
110
+ }
111
+ function errorMessage(error: unknown): string {
112
+ if (error instanceof Error && 'code' in error && typeof error.code === 'string') return error.code
113
+ return error instanceof Error ? error.message : String(error)
114
+ }