dsh-spec-collab 0.1.6 → 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.
@@ -0,0 +1,138 @@
1
+ import type { ParticipantRole, RequirementView, ReviewKind } from '../protocol.ts'
2
+
3
+ export type TaskView = 'review' | 'patches' | 'ready'
4
+ export type WorkflowCommand =
5
+ | { kind: 'open'; view: TaskView; objectId?: string }
6
+ | { kind: 'bind-workspace' }
7
+ | { kind: 'request-review'; reviewKind: ReviewKind }
8
+ | { kind: 'advance' }
9
+ | { kind: 'confirm'; role: ParticipantRole }
10
+ | { kind: 'generate-ready' }
11
+ | { kind: 'none' }
12
+
13
+ export interface WorkflowState {
14
+ eyebrow: string
15
+ title: string
16
+ detail: string
17
+ actionLabel: string
18
+ command: WorkflowCommand
19
+ disabled?: boolean
20
+ disabledReason?: string
21
+ }
22
+
23
+ const reviewIsOpen = (status: RequirementView['reviewItems'][number]['status']): boolean => !['resolved', 'invalidated', 'non-blocking-verify'].includes(status)
24
+
25
+ export function workflowState(requirement: RequirementView, participantRole: ParticipantRole): WorkflowState {
26
+ const currentReviews = requirement.reviewItems.filter(item => item.commit === requirement.currentCommit)
27
+ const blockers = currentReviews.filter(item => item.severity === 'blocking' && reviewIsOpen(item.status))
28
+ const productBlockers = blockers.filter(item => item.status !== 'joint-review')
29
+ const unanswered = blockers.filter(item => item.status === 'open')
30
+ const currentPatches = requirement.patches.filter(item => item.baseCommit === requirement.currentCommit && item.status === 'pending')
31
+ const currentRuns = requirement.aiRuns.filter(run => run.commit === requirement.currentCommit)
32
+ const activeRun = currentRuns.slice().reverse().find(run => ['queued', 'running'].includes(run.status))
33
+ const completed = (kind: ReviewKind): boolean => currentRuns.some(run => run.kind === kind && run.status === 'completed')
34
+ const productConfirmed = requirement.confirmations.some(item => item.commit === requirement.currentCommit && item.role === 'product' && item.scope === 'version' && item.status === 'active')
35
+ const engineeringConfirmed = requirement.confirmations.some(item => item.commit === requirement.currentCommit && item.role === 'engineering' && item.scope === 'version' && item.status === 'active')
36
+ const failedChecks = requirement.readiness.filter(check => !check.passed)
37
+
38
+ if (!requirement.workspaceId) return {
39
+ eyebrow: '开始前', title: '关联需求所在的项目', detail: 'AI 会从这个项目读取代码、规范和团队知识,关联后不能中途切换。',
40
+ actionLabel: '选择项目', command: { kind: 'bind-workspace' },
41
+ }
42
+
43
+ if (activeRun) return {
44
+ eyebrow: 'AI 正在工作', title: activeRun.kind === 'engineering-precheck' ? '正在从研发视角检查需求' : '正在整理需求中的问题',
45
+ detail: '结果会自动出现在这里,可以先继续编辑正文。', actionLabel: '分析中', command: { kind: 'none' }, disabled: true,
46
+ }
47
+
48
+ if (requirement.stage === 'product-review') {
49
+ if (!completed('product-first')) return {
50
+ eyebrow: '需求澄清', title: '先让 AI 找出需求缺口', detail: 'AI 会检查目标、范围、验收标准、证据和潜在风险。',
51
+ actionLabel: '开始需求检查', command: { kind: 'request-review', reviewKind: 'product-first' },
52
+ }
53
+ if (unanswered.length > 0) return {
54
+ eyebrow: '需要你的判断', title: `回答 ${unanswered.length} 个关键问题`, detail: '可以连续回答;完成最后一项后,再让 AI 回读全部结论并整理正文。',
55
+ actionLabel: '回答下一题', command: { kind: 'open', view: 'review', objectId: unanswered[0]!.id },
56
+ }
57
+ if (currentPatches.length > 0) return {
58
+ eyebrow: 'AI 已整理改动', title: `审核 ${currentPatches.length} 份正文修改`, detail: '确认改动符合你的判断后,再写入正式需求版本。',
59
+ actionLabel: '查看改动', command: { kind: 'open', view: 'patches' },
60
+ }
61
+ if (productBlockers.length > 0 || !completed('product-second')) return {
62
+ eyebrow: '人工回答已完成', title: '下一步:让 AI 回读全部回答', detail: '点击下方按钮后,AI 会重新检查正文与回答,并生成可逐项审核的正文修改。此步骤不会自动开始。',
63
+ actionLabel: '让 AI 回读并生成修改', command: { kind: 'request-review', reviewKind: 'product-second' },
64
+ }
65
+ return {
66
+ eyebrow: '产品澄清完成', title: '进入产品确认', detail: '当前版本没有产品侧阻塞问题,下一步由产品负责人确认内容。',
67
+ actionLabel: '进入产品确认', command: { kind: 'advance' },
68
+ }
69
+ }
70
+
71
+ if (requirement.stage === 'product-confirmation') {
72
+ if (!productConfirmed) return {
73
+ eyebrow: '产品确认', title: '确认当前需求版本', detail: participantRole === 'product' ? '确认目标、范围、业务规则和验收标准准确反映了产品决策。' : '需要一位产品角色确认当前版本后才能继续。',
74
+ actionLabel: participantRole === 'product' ? '确认当前版本' : '等待产品确认', command: participantRole === 'product' ? { kind: 'confirm', role: 'product' } : { kind: 'none' },
75
+ ...(participantRole === 'product' ? {} : { disabled: true, disabledReason: '当前身份是研发,需由产品角色完成确认。' }),
76
+ }
77
+ return {
78
+ eyebrow: '产品已确认', title: '邀请研发共同检查', detail: '产品结论已经锁定到当前版本,可以进入研发可行性和测试约束检查。',
79
+ actionLabel: '进入产研共审', command: { kind: 'advance' },
80
+ }
81
+ }
82
+
83
+ if (requirement.stage === 'joint-review') {
84
+ if (!completed('engineering-precheck')) return {
85
+ eyebrow: '产研共审', title: '从研发视角检查可实施性', detail: '重点检查现有实现、影响范围、兼容性和测试落点。',
86
+ actionLabel: '开始研发检查', command: { kind: 'request-review', reviewKind: 'engineering-precheck' },
87
+ }
88
+ if (unanswered.length > 0) return {
89
+ eyebrow: '研发发现待确认项', title: `处理 ${unanswered.length} 个阻塞问题`, detail: '这些问题会影响实现或验收,需要在交付研发前明确。',
90
+ actionLabel: '处理下一题', command: { kind: 'open', view: 'review', objectId: unanswered[0]!.id },
91
+ }
92
+ if (currentPatches.length > 0) return {
93
+ eyebrow: '研发建议了改动', title: `审核 ${currentPatches.length} 份正文修改`, detail: '确认实现约束和测试条件已准确写回需求。',
94
+ actionLabel: '查看改动', command: { kind: 'open', view: 'patches' },
95
+ }
96
+ if (blockers.length > 0) return {
97
+ eyebrow: '仍有待收敛内容', title: '复核已回复的问题', detail: '已有回复尚未消除阻塞,请重新检查或让 AI 根据结论更新正文。',
98
+ actionLabel: '查看问题', command: { kind: 'open', view: 'review', objectId: blockers[0]!.id },
99
+ }
100
+ if (failedChecks.length > 0) return {
101
+ eyebrow: '交付条件未齐', title: `补齐 ${failedChecks.length} 项需求内容`, detail: '完成条件会指出正文缺少的目标、范围、验收标准或测试约束。',
102
+ actionLabel: '查看缺少内容', command: { kind: 'open', view: 'ready' },
103
+ }
104
+ if (!productConfirmed) return {
105
+ eyebrow: '等待角色确认', title: '请产品确认当前版本', detail: participantRole === 'product' ? '正文已通过检查,确认它准确反映最终产品结论。' : '需要产品角色确认同一个当前版本。',
106
+ actionLabel: participantRole === 'product' ? '以产品身份确认' : '等待产品确认', command: participantRole === 'product' ? { kind: 'confirm', role: 'product' } : { kind: 'none' },
107
+ ...(participantRole === 'product' ? {} : { disabled: true, disabledReason: '当前身份是研发,需由产品角色完成确认。' }),
108
+ }
109
+ if (!engineeringConfirmed) return {
110
+ eyebrow: '最后一步确认', title: '请研发确认当前版本', detail: participantRole === 'engineering' ? '确认实现边界、风险和测试约束已经足够明确。' : '需要研发角色确认同一个当前版本。',
111
+ actionLabel: participantRole === 'engineering' ? '以研发身份确认' : '等待研发确认', command: participantRole === 'engineering' ? { kind: 'confirm', role: 'engineering' } : { kind: 'none' },
112
+ ...(participantRole === 'engineering' ? {} : { disabled: true, disabledReason: '当前身份是产品,需由研发角色完成确认。' }),
113
+ }
114
+ return {
115
+ eyebrow: '可以交付研发', title: '生成就绪需求', detail: '产品和研发已确认同一个版本,所有完成条件均已通过。',
116
+ actionLabel: '生成就绪需求', command: { kind: 'generate-ready' },
117
+ }
118
+ }
119
+
120
+ return {
121
+ eyebrow: '需求已就绪', title: '这份需求可以进入研发', detail: '正文、确认人、关键决策和待验证项已固定在同一个版本中。',
122
+ actionLabel: '查看交付内容', command: { kind: 'open', view: 'ready' },
123
+ }
124
+ }
125
+
126
+ export function friendlyActionError(error: string): string {
127
+ const messages: Array<[string, string]> = [
128
+ ['product blocking review items remain', '还有阻塞问题未处理,请先完成待澄清事项。'],
129
+ ['product second review is required', '需要先让 AI 根据回复整理并复核正文。'],
130
+ ['product must confirm the current version', '需要产品角色确认当前版本后才能进入产研共审。'],
131
+ ['readiness gate is not satisfied', '需求内容还没有满足全部交付条件,请查看缺少内容。'],
132
+ ['current version needs product and engineering confirmation', '产品和研发需要分别确认同一个当前版本。'],
133
+ ['review workspace is required', '请选择需求所在的项目。'],
134
+ ['human participant is required', '这项操作需要由真实参与者完成。'],
135
+ ['role is required', '当前身份角色不能执行这项确认。'],
136
+ ]
137
+ return messages.find(([source]) => error.includes(source))?.[1] ?? error
138
+ }
package/src/index.ts CHANGED
@@ -8,14 +8,18 @@ import type {} from '@deepseek-ai/dsh-system-prompt'
8
8
  import type {} from '@deepseek-ai/dsh-tools'
9
9
  import { CollaborationEngine } from './engine.ts'
10
10
  import { GitRequirementStore } from './git-store.ts'
11
+ import { DEFAULT_REVIEW_PROMPTS, resolveReviewPrompts, type ReviewPromptConfig } from './prompts.ts'
11
12
  import { DshReviewCoordinator } from './review-runtime.ts'
12
13
  import { ReviewContextCatalog, type ReviewContextConfig } from './review-context.ts'
13
14
  import { makeRoutes } from './routes.ts'
14
15
  import { allSpecTools } from './tools.ts'
15
16
 
17
+ export { DEFAULT_REVIEW_PROMPTS, resolveReviewPrompts }
18
+ export type { ReviewPromptConfig }
19
+
16
20
  export const name = 'spec-collab'
17
21
  export const inject = ['webServer', 'apiProxy', 'tools', 'systemPrompt']
18
- export interface Config extends ReviewContextConfig { dataRoot?: string; repositoryPath?: string }
22
+ export interface Config extends ReviewContextConfig { dataRoot?: string; repositoryPath?: string; prompts?: ReviewPromptConfig }
19
23
 
20
24
  const stringList = () => Schema.array(Schema.string()).default([])
21
25
  const contextFields = () => ({
@@ -24,6 +28,7 @@ const contextFields = () => ({
24
28
  documentPaths: stringList().description('AI 分析前可读取的本地文件或目录路径;相对路径按需求工作区根目录解析。'),
25
29
  agentPreset: Schema.string().description('实际挂载这些 Skill/MCP 工具的 DSH Agent Preset ID。'),
26
30
  })
31
+ const promptText = (value: string, description: string) => Schema.string().role('textarea').default(value).description(description)
27
32
  export const Config: Schema<Config> = Schema.object({
28
33
  dataRoot: Schema.string().description('协作账本数据目录。'),
29
34
  repositoryPath: Schema.string().description('正式 Spec Git 仓库目录。'),
@@ -32,18 +37,31 @@ export const Config: Schema<Config> = Schema.object({
32
37
  workspaceId: Schema.string().required().description('需要追加项目专属 AI 上下文的 DSH workspaceId。'),
33
38
  ...contextFields(),
34
39
  })).default([]).description('按 DSH 工作区追加的 AI 上下文;未列出的工作区仍继承 defaultContext。'),
40
+ prompts: Schema.object({
41
+ system: promptText(DEFAULT_REVIEW_PROMPTS.system, '注入普通 DSH 会话的插件系统说明。'),
42
+ workspaceContext: promptText(DEFAULT_REVIEW_PROMPTS.workspaceContext, '工作区上下文模板。必须保留 {{WORKSPACE_SNAPSHOT}} 和 {{RESOURCE_INSTRUCTIONS}};还可使用 {{WORKSPACE_ID}}、{{WORKSPACE_TITLE}}、{{WORKSPACE_PATH}}。'),
43
+ resourceInstructions: promptText(DEFAULT_REVIEW_PROMPTS.resourceInstructions, 'Skill、MCP 和文档资源说明模板。可用变量:{{RESOURCE_DETAILS}}、{{SKILLS}}、{{MCP_SERVERS}}、{{DOCUMENT_PATHS}}。'),
44
+ common: promptText(DEFAULT_REVIEW_PROMPTS.common, '所有审核和评论分析共享的约束。'),
45
+ productFirst: promptText(DEFAULT_REVIEW_PROMPTS.productFirst, '产品 AI 初审任务提示词。'),
46
+ productSecond: promptText(DEFAULT_REVIEW_PROMPTS.productSecond, '产品回复后的二次审核任务提示词。'),
47
+ engineeringPrecheck: promptText(DEFAULT_REVIEW_PROMPTS.engineeringPrecheck, '研发智能预审任务提示词。'),
48
+ changeReview: promptText(DEFAULT_REVIEW_PROMPTS.changeReview, '保存新版本后的变更审核任务提示词。'),
49
+ comment: promptText(DEFAULT_REVIEW_PROMPTS.comment, '正文评论的 AI 分析任务提示词。'),
50
+ followUp: promptText(DEFAULT_REVIEW_PROMPTS.followUp, 'AI 会话追问模板,必须保留 {{CONTENT}}。'),
51
+ }).description('AI 提示词配置;未填写的字段使用插件内置默认值。'),
35
52
  }) as Schema<Config>
36
53
 
37
54
  export function apply(ctx: Context, config: Config = {}): void {
38
55
  const dataRoot = config.dataRoot ?? join(homedir(), '.dsh', 'spec-collab')
39
56
  const contexts = new ReviewContextCatalog(config)
57
+ const prompts = resolveReviewPrompts(config.prompts)
40
58
  const engine = new CollaborationEngine(join(dataRoot, 'collaboration-v2.json'), new GitRequirementStore(config.repositoryPath ?? join(dataRoot, 'repository')))
41
- const coordinator = new DshReviewCoordinator(ctx.apiProxy, contexts)
59
+ const coordinator = new DshReviewCoordinator(ctx.apiProxy, contexts, prompts)
42
60
  engine.setCoordinator(coordinator)
43
61
  ctx.effect(() => { const disposers = makeRoutes(engine, coordinator).map(route => ctx.webServer.register(route)); return () => { for (const dispose of disposers) dispose() } }, 'spec-collab: routes')
44
62
  ctx.effect(() => { const disposers = allSpecTools(engine).map(tool => ctx.tools.register(tool)); return () => { for (const dispose of disposers) dispose() } }, 'spec-collab: tools')
45
63
  ctx.effect(() => ctx.systemPrompt.section({
46
64
  name: 'plugin:spec-collab', order: 190,
47
- text: '本机已安装 dsh-spec-collab「AI 需求澄清与 Spec 共创工作台」。产品输入原始需求后,产品 AI 初审并生成结构化 Review Item,产品逐项回应,AI 二次审核并提出候选 patch;产品确认后进入产研与双方 AI 共审,最终通过 Ready 质量门输出 commit 绑定的 Ready Spec。正式 Spec 版本只存 Git+Markdown;AI 只能提出 Review Item、分析回复和候选 patch,不能确认产品/技术语义,也不能直接写 Git 或标记 Ready。该产品严格止于 Ready Spec,不执行代码开发、测试、worktree、部署或发布。使用 spec_list/spec_read 读取,spec_reply/spec_submit_review/spec_propose_patch 参与审核。',
65
+ text: prompts.system,
48
66
  }), 'spec-collab: prompt')
49
67
  }
package/src/prompts.ts ADDED
@@ -0,0 +1,100 @@
1
+ export interface ReviewPromptConfig {
2
+ system?: string
3
+ workspaceContext?: string
4
+ resourceInstructions?: string
5
+ common?: string
6
+ productFirst?: string
7
+ productSecond?: string
8
+ engineeringPrecheck?: string
9
+ changeReview?: string
10
+ comment?: string
11
+ followUp?: string
12
+ }
13
+
14
+ export type ResolvedReviewPrompts = Required<ReviewPromptConfig>
15
+
16
+ export const DEFAULT_REVIEW_PROMPTS: ResolvedReviewPrompts = {
17
+ system: '本机已安装 dsh-spec-collab「AI 需求澄清与 Spec 共创工作台」。产品输入原始需求后,产品 AI 初审并生成结构化 Review Item,产品逐项回应,AI 二次审核并提出候选 patch;产品确认后进入产研与双方 AI 共审,最终通过 Ready 质量门输出 commit 绑定的 Ready Spec。正式 Spec 版本只存 Git+Markdown;AI 只能提出 Review Item、分析回复和候选 patch,不能确认产品/技术语义,也不能直接写 Git 或标记 Ready。该产品严格止于 Ready Spec,不执行代码开发、测试、worktree、部署或发布。使用 spec_list/spec_read 读取,spec_reply/spec_submit_review/spec_propose_patch 参与审核。',
18
+ workspaceContext: [
19
+ '## 本次审核必须使用的上下文',
20
+ 'DSH 工作区:`{{WORKSPACE_ID}}`。当前 AI session 必须挂载该工作区,不得创建未分组会话。',
21
+ '工作区名称:{{WORKSPACE_TITLE}}',
22
+ '工作区根目录:`{{WORKSPACE_PATH}}`',
23
+ '',
24
+ '开始审核前必须先实际读取工作区上下文,不能只读取 Spec:',
25
+ '1. 检查工作区根目录,并读取存在的 AGENTS.md、CONTEXT.md、README/README.md 和 CONTRIBUTING.md。',
26
+ '2. 读取存在的项目清单与构建入口,例如 package.json、pyproject.toml、Cargo.toml、go.mod、pom.xml 或构建脚本。',
27
+ '3. 根据需求关键词定位相关代码、产品文档、测试和 Git 历史;结论引用具体文件路径及 commit 或其他可识别版本。',
28
+ '4. 不得把“已绑定工作区”等同于“已读取上下文”。无法访问文件或历史时,明确说明并使用 TO_VERIFY。',
29
+ '',
30
+ '{{WORKSPACE_SNAPSHOT}}',
31
+ '',
32
+ '{{RESOURCE_INSTRUCTIONS}}',
33
+ ].join('\n'),
34
+ resourceInstructions: [
35
+ '{{RESOURCE_DETAILS}}',
36
+ '任何已配置资源若在当前 Agent Preset 中不可用、无权限或读取失败,必须在结论中明确指出该资源并使用 TO_VERIFY;不得假装已经查询或把不可访问内容写成 FACT。',
37
+ ].join('\n'),
38
+ common: [
39
+ '所有面向用户的输出必须使用简体中文,包括 Review Item 的陈述、影响、问题、成熟度总结、候选 patch 摘要以及评论分析回复。仅保留代码标识、路径、commit SHA、AC ID、FACT / INFERENCE / ASSUMPTION / TO_VERIFY 等固定枚举为原文。',
40
+ '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.',
41
+ 'A FACT must cite an accessible, version-pinned source. If evidence is unavailable, use TO_VERIFY; never invent historical or implementation conflicts.',
42
+ 'Use spec_read to retrieve the exact current data. Do not modify files directly.',
43
+ '每个 Review Item 默认给出三个 recommendedOptions。每个选项只表达一个决定,使用“选择 + 直接结果”的短句,建议不超过 45 个汉字;三个选项必须有真实差异,不得只是“接受、拒绝、待验证”的同义改写。确有四种独立方案时才允许第四项。',
44
+ 'Review Item 的 question 只问一个可以直接回答的问题,建议不超过 40 个汉字。背景放在 statement,后果放在 impact,不要把背景、问题和多个子问题挤进 question 或选项。',
45
+ '每个 Review Item 必须提供 sourceAnchors:优先从当前 Spec 原文逐字复制 1 至 3 段能说明问题的短句,并填写所在 heading;不得改写或概括。问题来自正文缺失、没有可引用原文时,sourceAnchors 使用空数组,并通过 affectedSections / affectedAcceptanceIds 指明应补充的位置。',
46
+ '审核记录与正式文档必须分层:FACT / INFERENCE / ASSUMPTION / TO_VERIFY、commit SHA、run ID 等只用于结构化审核记录,不得堆入候选 Spec 正文。',
47
+ '候选 Spec 必须使用产品和研发都能直接理解的自然中文。避免行业黑话、审计腔和无必要的英文;英文缩写首次出现时必须同时写出中文含义,例如“行动按钮(CTA)”,后续优先使用中文。无法准确解释的缩写不要使用。',
48
+ '优先使用这些通俗说法:操作按钮(不用 CTA)、统一风格标识(不用 canonical key)、点赞(不用 like)、提示词(不用 prompt)、测试数据(不用 fixture)、最终判断依据(不用事实源)、完成状态(不用终态)、重复操作结果一致(不用幂等)。Upgrade、Download、Lite、Plus 等确为界面文案或套餐名时可保留,但首次出现要说明中文含义。',
49
+ '正文不要写“当前唯一可访问来源”“固定于某 commit”“统一记为 TO_VERIFY”这类过程说明。资料不足时,只在“待补充资料”章节按“资料名称:需要补充的内容;负责人(如已知)”列出,不重复背景、不写内部状态枚举。',
50
+ '每段只表达一个结论,优先使用短句和具体业务语言。删除不影响需求理解、研发实现或验收判断的元信息。',
51
+ '候选 patch 直接从文档标题开始,不写“本文为候选 patch”“不代表已确认决策”等免责声明。保留清晰的 Markdown 章节;身份与权限差异优先用表格,验收标准使用“前提 / 操作 / 预期结果”,不要使用 Given / When / Then。',
52
+ '合并重复内容:目标讲用户结果,范围只列做与不做,业务规则只定义规则,验收标准只写可验证场景。同一句规则不要再分别复制到目标、范围、术语、验收和风险章节。',
53
+ ].join('\n'),
54
+ productFirst: '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.',
55
+ productSecond: '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.',
56
+ engineeringPrecheck: '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.',
57
+ changeReview: '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.',
58
+ comment: '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.',
59
+ followUp: '请使用简体中文回答以下追问,并继续遵守当前 Spec 审核任务的证据、权限和结构化回写约束。\n\n{{CONTENT}}',
60
+ }
61
+
62
+ export function resolveReviewPrompts(config: ReviewPromptConfig = {}): ResolvedReviewPrompts {
63
+ const prompts = { ...DEFAULT_REVIEW_PROMPTS, ...config }
64
+ validateTemplate('workspaceContext', prompts.workspaceContext,
65
+ ['WORKSPACE_ID', 'WORKSPACE_TITLE', 'WORKSPACE_PATH', 'WORKSPACE_SNAPSHOT', 'RESOURCE_INSTRUCTIONS'],
66
+ ['WORKSPACE_SNAPSHOT', 'RESOURCE_INSTRUCTIONS'])
67
+ validateTemplate('resourceInstructions', prompts.resourceInstructions,
68
+ ['RESOURCE_DETAILS', 'SKILLS', 'MCP_SERVERS', 'DOCUMENT_PATHS'])
69
+ validateTemplate('followUp', prompts.followUp, ['CONTENT'], ['CONTENT'])
70
+ for (const name of ['system', 'common', 'productFirst', 'productSecond', 'engineeringPrecheck', 'changeReview', 'comment'] as const) {
71
+ validateTemplate(name, prompts[name], [])
72
+ }
73
+ return prompts
74
+ }
75
+
76
+ export function renderPrompt(template: string, values: Record<string, string>): string {
77
+ return template.replace(/\{\{([A-Z_]+)\}\}/g, (placeholder, key: string) => values[key] ?? placeholder)
78
+ }
79
+
80
+ export function extractPromptValue(rendered: string, template: string, placeholder: string): string | undefined {
81
+ const token = `{{${placeholder}}}`
82
+ const index = template.indexOf(token)
83
+ if (index < 0) return undefined
84
+ const prefix = template.slice(0, index)
85
+ const suffix = template.slice(index + token.length)
86
+ if (!rendered.startsWith(prefix) || !rendered.endsWith(suffix)) return undefined
87
+ return rendered.slice(prefix.length, rendered.length - suffix.length)
88
+ }
89
+
90
+ function validateTemplate(name: keyof ResolvedReviewPrompts, template: string, allowed: string[], requiredOnce: string[] = []): void {
91
+ const counts = new Map<string, number>()
92
+ for (const match of template.matchAll(/\{\{([A-Z_]+)\}\}/g)) {
93
+ const placeholder = match[1]!
94
+ if (!allowed.includes(placeholder)) throw new Error(`${name} prompt contains unsupported placeholder {{${placeholder}}}`)
95
+ counts.set(placeholder, (counts.get(placeholder) ?? 0) + 1)
96
+ }
97
+ for (const placeholder of requiredOnce) {
98
+ if (counts.get(placeholder) !== 1) throw new Error(`${name} prompt must contain {{${placeholder}}} exactly once`)
99
+ }
100
+ }
package/src/protocol.ts CHANGED
@@ -18,9 +18,11 @@ export interface ParticipantSnapshot { participantId: string; nickname: string;
18
18
  export interface SourceReference { id: string; sourceType: 'text' | 'markdown' | 'prototype' | 'meeting' | 'data' | 'link' | 'feedback' | 'code-scope'; label: string; stableId?: string; version?: string; accessStatus: 'available' | 'unverified' | 'missing' }
19
19
  export interface RequirementVersion { commit: string; parentCommit?: string; markdown: string; author: ParticipantSnapshot; summary: string; createdAt: number }
20
20
  export interface ReviewEvidence { statement: string; source: string; version?: string; accessible: boolean }
21
+ export interface ReviewSourceAnchor { quote: string; heading?: string }
21
22
  export interface ReviewItem {
22
23
  id: string; requirementId: string; commit: string; reviewKind: ReviewKind; type: ReviewItemType; severity: Severity; statement: string
23
24
  evidence: ReviewEvidence[]; epistemicStatus: EpistemicStatus; impact: string; question: string; affectedSections: string[]; affectedAcceptanceIds: string[]
25
+ sourceAnchors?: ReviewSourceAnchor[]
24
26
  recommendedOptions?: string[]
25
27
  ownerRole: ParticipantRole; ownerParticipantId?: string; status: ReviewItemStatus
26
28
  response?: { participant: ParticipantSnapshot; disposition: 'context' | 'evidence' | 'accept' | 'accept-modified' | 'reject' | 'to-verify' | 'joint-review'; body: string; createdAt: number }
@@ -1,5 +1,6 @@
1
1
  import { homedir } from 'node:os'
2
2
  import { normalize, resolve } from 'node:path'
3
+ import { DEFAULT_REVIEW_PROMPTS, renderPrompt } from './prompts.ts'
3
4
 
4
5
  export interface ReviewContextResources {
5
6
  skills?: string[]
@@ -56,17 +57,33 @@ export class ReviewContextCatalog {
56
57
  }
57
58
  }
58
59
 
59
- export function reviewContextPrompt(context: ResolvedReviewContext): string {
60
- const rows = [
61
- '## 本次审核必须使用的上下文',
62
- `DSH 工作区:\`${context.workspaceId}\`。当前 AI session 必须挂载该工作区,不得创建未分组会话。`,
63
- ]
60
+ export interface ReviewContextPromptOptions {
61
+ workspace?: { title: string; path: string }
62
+ workspaceSnapshot?: string
63
+ workspaceTemplate?: string
64
+ resourceTemplate?: string
65
+ }
66
+
67
+ export function reviewContextPrompt(context: ResolvedReviewContext, options: ReviewContextPromptOptions = {}): string {
68
+ const workspace = options.workspace ?? { title: context.workspaceId, path: '未提供' }
69
+ const rows: string[] = []
64
70
  if (context.skills.length > 0) rows.push(`Skills:先调用 skill 工具加载 ${context.skills.map(value => `\`${value}\``).join('、')},读取完整说明后再分析。`)
65
71
  if (context.mcpServers.length > 0) rows.push(`MCP:需要事实查询时优先使用 ${context.mcpServers.map(value => `\`mcp__${value}__*\``).join('、')} namespace 下的工具。`)
66
72
  if (context.documentPaths.length > 0) rows.push('本地参考文档:分析前先读取与本需求相关的路径;相对路径基于当前 DSH 工作区根目录,引用时必须带具体文件路径和可识别版本。', ...context.documentPaths.map(value => `- \`${value}\``))
67
73
  if (context.skills.length === 0 && context.mcpServers.length === 0 && context.documentPaths.length === 0) rows.push('当前未配置额外 Skill、MCP 或本地参考文档。')
68
- rows.push('任何已配置资源若在当前 Agent Preset 中不可用、无权限或读取失败,必须在结论中明确指出该资源并使用 TO_VERIFY;不得假装已经查询或把不可访问内容写成 FACT。')
69
- return rows.join('\n')
74
+ const resourceInstructions = renderPrompt(options.resourceTemplate ?? DEFAULT_REVIEW_PROMPTS.resourceInstructions, {
75
+ RESOURCE_DETAILS: rows.join('\n'),
76
+ SKILLS: formatValues(context.skills),
77
+ MCP_SERVERS: formatValues(context.mcpServers.map(value => `mcp__${value}__*`)),
78
+ DOCUMENT_PATHS: formatValues(context.documentPaths),
79
+ })
80
+ return renderPrompt(options.workspaceTemplate ?? DEFAULT_REVIEW_PROMPTS.workspaceContext, {
81
+ WORKSPACE_ID: context.workspaceId,
82
+ WORKSPACE_TITLE: workspace.title,
83
+ WORKSPACE_PATH: workspace.path,
84
+ WORKSPACE_SNAPSHOT: options.workspaceSnapshot ?? '工作区快照尚未生成。',
85
+ RESOURCE_INSTRUCTIONS: resourceInstructions,
86
+ })
70
87
  }
71
88
 
72
89
  function normalizeResources(value: ReviewContextResources | undefined): NormalizedReviewContext {
@@ -80,6 +97,7 @@ function normalizeResources(value: ReviewContextResources | undefined): Normaliz
80
97
 
81
98
  function cleanList(values: string[] | undefined): string[] { return unique((values ?? []).map(value => value.trim()).filter(Boolean)) }
82
99
  function unique(values: string[]): string[] { return [...new Set(values)] }
100
+ function formatValues(values: string[]): string { return values.length > 0 ? values.map(value => `\`${value}\``).join('、') : '未配置' }
83
101
  function resolveDocumentPath(value: string): string {
84
102
  if (value === '~') return homedir()
85
103
  if (value.startsWith('~/') || value.startsWith('~\\')) return normalize(resolve(homedir(), value.slice(2)))
@@ -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
  })