dsh-spec-collab 0.1.0

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.
Files changed (45) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +106 -0
  3. package/cordis.patch.yml +3 -0
  4. package/lib/client.js +41298 -0
  5. package/lib/index.js +1986 -0
  6. package/lib/types/client/SpecWorkbench.d.ts +6 -0
  7. package/lib/types/client/SpecWorkbench.d.ts.map +1 -0
  8. package/lib/types/client/api.d.ts +20 -0
  9. package/lib/types/client/api.d.ts.map +1 -0
  10. package/lib/types/client/index.d.ts +4 -0
  11. package/lib/types/client/index.d.ts.map +1 -0
  12. package/lib/types/client/mount.d.ts +4 -0
  13. package/lib/types/client/mount.d.ts.map +1 -0
  14. package/lib/types/engine.d.ts +67 -0
  15. package/lib/types/engine.d.ts.map +1 -0
  16. package/lib/types/git-store.d.ts +40 -0
  17. package/lib/types/git-store.d.ts.map +1 -0
  18. package/lib/types/index.d.ts +12 -0
  19. package/lib/types/index.d.ts.map +1 -0
  20. package/lib/types/protocol.d.ts +358 -0
  21. package/lib/types/protocol.d.ts.map +1 -0
  22. package/lib/types/review-context.d.ts +32 -0
  23. package/lib/types/review-context.d.ts.map +1 -0
  24. package/lib/types/review-runtime.d.ts +26 -0
  25. package/lib/types/review-runtime.d.ts.map +1 -0
  26. package/lib/types/routes.d.ts +5 -0
  27. package/lib/types/routes.d.ts.map +1 -0
  28. package/lib/types/tools.d.ts +8 -0
  29. package/lib/types/tools.d.ts.map +1 -0
  30. package/package.json +96 -0
  31. package/src/client/SpecWorkbench.tsx +293 -0
  32. package/src/client/api.ts +12 -0
  33. package/src/client/css-modules.d.ts +1 -0
  34. package/src/client/index.ts +16 -0
  35. package/src/client/mount.tsx +73 -0
  36. package/src/client/toast-ui.d.ts +25 -0
  37. package/src/client/workbench.module.css +275 -0
  38. package/src/engine.ts +358 -0
  39. package/src/git-store.ts +133 -0
  40. package/src/index.ts +49 -0
  41. package/src/protocol.ts +108 -0
  42. package/src/review-context.ts +87 -0
  43. package/src/review-runtime.ts +106 -0
  44. package/src/routes.ts +52 -0
  45. package/src/tools.ts +80 -0
@@ -0,0 +1,108 @@
1
+ export const API_PREFIX = '/api/spec-collab'
2
+ export const SCHEMA_VERSION = 2 as const
3
+
4
+ export type ParticipantRole = 'product' | 'engineering'
5
+ export type ParticipantKind = 'human' | 'ai'
6
+ export type RequirementStage = 'product-review' | 'product-confirmation' | 'joint-review' | 'ready'
7
+ export type ReviewKind = 'product-first' | 'product-second' | 'engineering-precheck' | 'change-review'
8
+ export type ReviewItemType = 'goal' | 'evidence' | 'history-conflict' | 'current-implementation' | 'scope' | 'semantics' | 'completeness' | 'acceptance' | 'risk'
9
+ export type Severity = 'blocking' | 'major' | 'minor'
10
+ export type EpistemicStatus = 'FACT' | 'INFERENCE' | 'ASSUMPTION' | 'TO_VERIFY'
11
+ export type ReviewItemStatus = 'open' | 'answered' | 'resolved' | 'joint-review' | 'non-blocking-verify' | 'invalidated'
12
+ export type CommentResolution = 'written-back' | 'decision' | 'rejected' | 'open-question'
13
+ export type ConfirmationScope = 'version' | 'section' | 'acceptance-criterion' | 'decision'
14
+ export type ActionItemStatus = 'pending' | 'handled' | 'invalidated' | 'cancelled'
15
+ export type AiTaskStatus = 'queued' | 'running' | 'completed' | 'failed'
16
+
17
+ export interface ParticipantSnapshot { participantId: string; nickname: string; role: ParticipantRole; kind: ParticipantKind; sessionId?: string }
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
+ export interface RequirementVersion { commit: string; parentCommit?: string; markdown: string; author: ParticipantSnapshot; summary: string; createdAt: number }
20
+ export interface ReviewEvidence { statement: string; source: string; version?: string; accessible: boolean }
21
+ export interface ReviewItem {
22
+ id: string; requirementId: string; commit: string; reviewKind: ReviewKind; type: ReviewItemType; severity: Severity; statement: string
23
+ evidence: ReviewEvidence[]; epistemicStatus: EpistemicStatus; impact: string; question: string; affectedSections: string[]; affectedAcceptanceIds: string[]
24
+ recommendedOptions?: string[]
25
+ ownerRole: ParticipantRole; ownerParticipantId?: string; status: ReviewItemStatus
26
+ response?: { participant: ParticipantSnapshot; disposition: 'context' | 'evidence' | 'accept' | 'accept-modified' | 'reject' | 'to-verify' | 'joint-review'; body: string; createdAt: number }
27
+ createdAt: number; updatedAt: number
28
+ }
29
+ export interface CommentReply { id: string; author: ParticipantSnapshot; body: string; createdAt: number }
30
+ export interface CommentThread {
31
+ id: string; requirementId: string; commit: string; anchor: { heading?: string; quote: string; prefix?: string; suffix?: string }
32
+ author: ParticipantSnapshot; body: string; replies: CommentReply[]; aiStatus: AiTaskStatus; aiSessionId?: string
33
+ status: 'open' | 'resolved' | 'orphaned' | 'invalidated'; resolution?: CommentResolution; createdAt: number; updatedAt: number
34
+ }
35
+ export interface CandidatePatch {
36
+ id: string; requirementId: string; baseCommit: string; reviewKind: ReviewKind; proposedMarkdown: string; summary: string
37
+ affectedReviewItemIds: string[]; affectedSections: string[]; affectedAcceptanceIds: string[]; createdBy: ParticipantSnapshot
38
+ status: 'pending' | 'accepted' | 'rejected' | 'stale'; createdAt: number
39
+ }
40
+ export interface Decision {
41
+ id: string; requirementId: string; commit: string; question: string; options: string[]; decision: string; rationale: string
42
+ confirmer: ParticipantSnapshot; affectedSections: string[]; affectedAcceptanceIds: string[]; createdAt: number; status: 'active' | 'invalidated'
43
+ }
44
+ export interface Confirmation { id: string; requirementId: string; commit: string; role: ParticipantRole; participant: ParticipantSnapshot; scope: ConfirmationScope; scopeId?: string; status: 'active' | 'invalidated'; createdAt: number }
45
+ export interface ActionItem {
46
+ id: string; requirementId: string; sourceType: 'review-item' | 'comment' | 'patch' | 'decision' | 'confirmation'; sourceId: string
47
+ type: 'reply' | 'confirm' | 'review' | 'reconfirm'; assigneeRole: ParticipantRole; assigneeParticipantId?: string; blocking: boolean
48
+ status: ActionItemStatus; dueStage: RequirementStage; createdAt: number; updatedAt: number
49
+ }
50
+ export interface AiReviewRun { id: string; requirementId: string; commit: string; kind: ReviewKind; status: AiTaskStatus; requestedBy: ParticipantSnapshot; sessionId?: string; error?: string; maturitySummary?: string; createdAt: number; updatedAt: number }
51
+ export interface ReadinessCheck { key: 'goal' | 'acceptance' | 'scope' | 'semantics' | 'evidence' | 'test-constraints'; passed: boolean; reasons: string[] }
52
+ export interface ReadyPackage { requirementId: string; commit: string; packageHash: string; generatedAt: number; generatedBy: ParticipantSnapshot; markdown: string }
53
+ export interface ReviewWorkspaceSummary { workspaceId: string; title: string; path: string }
54
+ export interface RequirementRecord {
55
+ id: string; title: string; stage: RequirementStage; currentCommit: string; productConfirmedCommit?: string; jointConfirmedCommit?: string
56
+ workspaceId?: string
57
+ archivedAt?: number
58
+ sources: SourceReference[]; reviewItems: ReviewItem[]; comments: CommentThread[]; patches: CandidatePatch[]; decisions: Decision[]
59
+ confirmations: Confirmation[]; actionItems: ActionItem[]; aiRuns: AiReviewRun[]; readyPackage?: ReadyPackage; createdAt: number; updatedAt: number
60
+ }
61
+ export interface CollaborationState { schemaVersion: typeof SCHEMA_VERSION; revision: number; participants: ParticipantSnapshot[]; requirements: RequirementRecord[] }
62
+ export interface RequirementView extends RequirementRecord { version: RequirementVersion; history: Array<Omit<RequirementVersion, 'markdown'>>; readiness: ReadinessCheck[] }
63
+ export interface SaveConflict {
64
+ requirementId: string; baseCommit: string; currentCommit: string; baseMarkdown: string; currentMarkdown: string; draftMarkdown: string
65
+ baseToCurrentDiff: string; baseToDraftDiff: string
66
+ }
67
+ export type MyItemCategory = 'awaiting-my-response' | 'awaiting-my-confirmation' | 'initiated-by-me' | 'possibly-mine-by-ip'
68
+ export interface MyActionItem extends ActionItem { category: MyItemCategory; requirementTitle: string; target: { tab: 'review' | 'discussion' | 'patches' | 'decisions' | 'ready'; objectId: string } }
69
+
70
+ export type CollaborationAction =
71
+ | { kind: 'requirement.create'; participant: ParticipantSnapshot; title: string; rawRequirement: string; sources: SourceReference[]; workspaceId: string }
72
+ | { kind: 'requirement.bind-workspace'; participant: ParticipantSnapshot; requirementId: string; workspaceId: string }
73
+ | { kind: 'requirement.rename'; participant: ParticipantSnapshot; requirementId: string; title: string }
74
+ | { kind: 'requirement.archive'; participant: ParticipantSnapshot; requirementId: string; archived: boolean }
75
+ | { kind: 'requirement.delete'; participant: ParticipantSnapshot; requirementId: string }
76
+ | { kind: 'version.save'; participant: ParticipantSnapshot; requirementId: string; baseCommit: string; markdown: string; summary: string }
77
+ | { kind: 'review.request'; participant: ParticipantSnapshot; requirementId: string; reviewKind: ReviewKind }
78
+ | { kind: 'review.respond'; participant: ParticipantSnapshot; requirementId: string; reviewItemId: string; disposition: NonNullable<ReviewItem['response']>['disposition']; body: string }
79
+ | { kind: 'comment.create'; participant: ParticipantSnapshot; requirementId: string; commit: string; anchor: CommentThread['anchor']; body: string }
80
+ | { kind: 'comment.reply'; participant: ParticipantSnapshot; requirementId: string; commentId: string; body: string }
81
+ | { kind: 'comment.resolve'; participant: ParticipantSnapshot; requirementId: string; commentId: string; resolution: CommentResolution }
82
+ | { kind: 'patch.accept'; participant: ParticipantSnapshot; requirementId: string; patchId: string; summary: string }
83
+ | { kind: 'patch.reject'; participant: ParticipantSnapshot; requirementId: string; patchId: string }
84
+ | { kind: 'decision.create'; participant: ParticipantSnapshot; requirementId: string; question: string; options: string[]; decision: string; rationale: string; affectedSections: string[]; affectedAcceptanceIds: string[] }
85
+ | { kind: 'confirmation.create'; participant: ParticipantSnapshot; requirementId: string; role: ParticipantRole; scope: ConfirmationScope; scopeId?: string }
86
+ | { kind: 'stage.advance'; participant: ParticipantSnapshot; requirementId: string }
87
+ | { kind: 'ready.generate'; participant: ParticipantSnapshot; requirementId: string }
88
+ | { kind: 'downstream.return'; participant: ParticipantSnapshot; requirementId: string; summary: string; evidence: ReviewEvidence[]; affectedSections: string[]; affectedAcceptanceIds: string[] }
89
+
90
+ export interface ActionEnvelope { requestId: string; action: CollaborationAction }
91
+ export type ActionResult = { ok: true; revision: number; requirement: RequirementView; deletedRequirementId?: string } | { ok: false; revision: number; error: string; conflict?: SaveConflict }
92
+
93
+ export function isParticipant(value: unknown): value is ParticipantSnapshot {
94
+ if (typeof value !== 'object' || value === null) return false
95
+ const row = value as Record<string, unknown>
96
+ return typeof row.participantId === 'string' && row.participantId.length >= 8
97
+ && typeof row.nickname === 'string' && row.nickname.trim().length >= 2 && row.nickname.length <= 40
98
+ && ['product', 'engineering'].includes(String(row.role)) && ['human', 'ai'].includes(String(row.kind))
99
+ && (row.kind !== 'ai' || typeof row.sessionId === 'string')
100
+ }
101
+ export function parseEnvelope(value: unknown): ActionEnvelope | undefined {
102
+ if (typeof value !== 'object' || value === null) return undefined
103
+ const row = value as Record<string, unknown>
104
+ if (typeof row.requestId !== 'string' || row.requestId.trim() === '' || typeof row.action !== 'object' || row.action === null) return undefined
105
+ const action = row.action as Record<string, unknown>
106
+ if (typeof action.kind !== 'string' || !isParticipant(action.participant)) return undefined
107
+ return { requestId: row.requestId, action: action as unknown as CollaborationAction }
108
+ }
@@ -0,0 +1,87 @@
1
+ import { homedir } from 'node:os'
2
+ import { normalize, resolve } from 'node:path'
3
+
4
+ export interface ReviewContextResources {
5
+ skills?: string[]
6
+ mcpServers?: string[]
7
+ documentPaths?: string[]
8
+ agentPreset?: string
9
+ }
10
+
11
+ export interface ReviewWorkspaceContextConfig extends ReviewContextResources { workspaceId: string }
12
+
13
+ export interface ReviewContextConfig {
14
+ defaultContext?: ReviewContextResources
15
+ workspaces?: ReviewWorkspaceContextConfig[]
16
+ }
17
+
18
+ interface NormalizedReviewContext {
19
+ skills: string[]
20
+ mcpServers: string[]
21
+ documentPaths: string[]
22
+ agentPreset?: string
23
+ }
24
+
25
+ export interface ResolvedReviewContext extends NormalizedReviewContext { workspaceId: string }
26
+
27
+ const MCP_SERVER = /^[A-Za-z0-9_-]{1,32}$/
28
+
29
+ export class ReviewContextCatalog {
30
+ private readonly defaults: NormalizedReviewContext
31
+ private readonly workspaces = new Map<string, ReviewWorkspaceContextConfig>()
32
+
33
+ constructor(config: ReviewContextConfig = {}) {
34
+ this.defaults = normalizeResources(config.defaultContext)
35
+ for (const value of config.workspaces ?? []) {
36
+ const workspaceId = value.workspaceId.trim()
37
+ if (workspaceId === '') throw new Error('review workspace id is required')
38
+ if (this.workspaces.has(workspaceId)) throw new Error(`duplicate review workspace id: ${workspaceId}`)
39
+ this.workspaces.set(workspaceId, { ...normalizeResources(value), workspaceId })
40
+ }
41
+ }
42
+
43
+ workspaceIds(): string[] { return [...this.workspaces.keys()] }
44
+
45
+ resolve(workspaceId?: string): ResolvedReviewContext {
46
+ if (workspaceId === undefined || workspaceId.trim() === '') throw new Error('review workspace is required')
47
+ const workspace = this.workspaces.get(workspaceId)
48
+ const resources = normalizeResources(workspace)
49
+ return {
50
+ workspaceId,
51
+ skills: unique([...this.defaults.skills, ...resources.skills]),
52
+ mcpServers: unique([...this.defaults.mcpServers, ...resources.mcpServers]),
53
+ documentPaths: unique([...this.defaults.documentPaths, ...resources.documentPaths]),
54
+ ...(resources.agentPreset ?? this.defaults.agentPreset ? { agentPreset: resources.agentPreset ?? this.defaults.agentPreset } : {}),
55
+ }
56
+ }
57
+ }
58
+
59
+ export function reviewContextPrompt(context: ResolvedReviewContext): string {
60
+ const rows = [
61
+ '## 本次审核必须使用的上下文',
62
+ `DSH 工作区:\`${context.workspaceId}\`。当前 AI session 必须挂载该工作区,不得创建未分组会话。`,
63
+ ]
64
+ if (context.skills.length > 0) rows.push(`Skills:先调用 skill 工具加载 ${context.skills.map(value => `\`${value}\``).join('、')},读取完整说明后再分析。`)
65
+ if (context.mcpServers.length > 0) rows.push(`MCP:需要事实查询时优先使用 ${context.mcpServers.map(value => `\`mcp__${value}__*\``).join('、')} namespace 下的工具。`)
66
+ if (context.documentPaths.length > 0) rows.push('本地参考文档:分析前先读取与本需求相关的路径;相对路径基于当前 DSH 工作区根目录,引用时必须带具体文件路径和可识别版本。', ...context.documentPaths.map(value => `- \`${value}\``))
67
+ 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')
70
+ }
71
+
72
+ function normalizeResources(value: ReviewContextResources | undefined): NormalizedReviewContext {
73
+ const skills = cleanList(value?.skills)
74
+ const mcpServers = cleanList(value?.mcpServers)
75
+ for (const server of mcpServers) if (!MCP_SERVER.test(server)) throw new Error(`invalid MCP server name: ${server}`)
76
+ const documentPaths = unique(cleanList(value?.documentPaths).map(resolveDocumentPath))
77
+ const agentPreset = value?.agentPreset?.trim()
78
+ return { skills, mcpServers, documentPaths, ...(agentPreset ? { agentPreset } : {}) }
79
+ }
80
+
81
+ function cleanList(values: string[] | undefined): string[] { return unique((values ?? []).map(value => value.trim()).filter(Boolean)) }
82
+ function unique(values: string[]): string[] { return [...new Set(values)] }
83
+ function resolveDocumentPath(value: string): string {
84
+ if (value === '~') return homedir()
85
+ if (value.startsWith('~/') || value.startsWith('~\\')) return normalize(resolve(homedir(), value.slice(2)))
86
+ return normalize(value)
87
+ }
@@ -0,0 +1,106 @@
1
+ import type { ApiProxy, RpcId } from '@deepseek-ai/dsh-host-apiproxy'
2
+ import type { AiCoordinator } from './engine.ts'
3
+ import type { AiReviewRun, CommentThread, RequirementView, ReviewWorkspaceSummary } from './protocol.ts'
4
+ import { ReviewContextCatalog, reviewContextPrompt } from './review-context.ts'
5
+
6
+ function request<T>(payload: T) { return { rpcId: `spec-collab-${crypto.randomUUID()}` as RpcId, payload } }
7
+ function failure(error: { code: string; message: string }): Error { return new Error(`${error.code}: ${error.message}`) }
8
+
9
+ export class DshReviewCoordinator implements AiCoordinator {
10
+ constructor(private readonly api: ApiProxy, private readonly contexts = new ReviewContextCatalog()) {}
11
+ async reviewWorkspaces(): Promise<ReviewWorkspaceSummary[]> {
12
+ const listed = await this.api.workspace.list(request({}))
13
+ if (!listed.result.ok) throw failure(listed.result.error)
14
+ return listed.result.value.items.map(item => ({ workspaceId: item.workspaceId, title: item.title, path: item.path }))
15
+ }
16
+ async assertWorkspaceAvailable(workspaceId: string): Promise<void> {
17
+ if (!(await this.reviewWorkspaces()).some(item => item.workspaceId === workspaceId)) throw new Error(`workspace not found: ${workspaceId}`)
18
+ }
19
+ requestReview(input: { requirement: RequirementView; run: AiReviewRun }): Promise<string> {
20
+ 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)
22
+ }
23
+ requestCommentReply(input: { requirement: RequirementView; comment: CommentThread }): Promise<string> {
24
+ 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)
26
+ }
27
+ async conversation(sessionId: string): Promise<Array<{ role: 'user' | 'assistant'; text: string }>> {
28
+ const history = await this.api.sessions.history(request({ sessionId: sessionId as never }))
29
+ if (!history.result.ok) throw failure(history.result.error)
30
+ const rows: Array<{ role: 'user' | 'assistant'; text: string }> = []
31
+ let skippedOrchestrationPrompt = false
32
+ for (const entry of history.result.value.events) {
33
+ if (entry.event.type !== 'user/message' && entry.event.type !== 'assistant/message') continue
34
+ if (entry.event.type === 'user/message' && !skippedOrchestrationPrompt) { skippedOrchestrationPrompt = true; continue }
35
+ const value = entry.event.data as unknown
36
+ const message = isObject(value) && 'message' in value ? value.message : value
37
+ const content = isObject(message) && 'content' in message ? message.content : message
38
+ let messageText = collectText(content).join('\n').trim()
39
+ if (entry.event.type === 'user/message') {
40
+ const marker = '请使用简体中文回答以下追问,并继续遵守当前 Spec 审核任务的证据、权限和结构化回写约束。'
41
+ if (!messageText.startsWith(marker)) continue
42
+ messageText = messageText.slice(marker.length).trim()
43
+ }
44
+ if (messageText !== '') rows.push({ role: entry.event.type === 'user/message' ? 'user' : 'assistant', text: messageText })
45
+ }
46
+ return rows
47
+ }
48
+ async followUp(sessionId: string, text: string): Promise<void> {
49
+ const content = text.trim()
50
+ 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}` }] }))
52
+ if (!prompted.result.ok) throw failure(prompted.result.error)
53
+ }
54
+ private async launch(title: string, promptText: string, workspaceId: string, agentPreset?: string): Promise<string> {
55
+ await this.assertWorkspaceAvailable(workspaceId)
56
+ if (agentPreset !== undefined) {
57
+ const presets = await this.api.agentPresets.list(request({}))
58
+ if (!presets.result.ok) throw failure(presets.result.error)
59
+ const preset = presets.result.value.presets.find(item => item.id === agentPreset)
60
+ if (preset === undefined || preset.broken !== undefined) throw new Error('agent preset is unavailable')
61
+ }
62
+ const created = await this.api.sessions.create(request({ workspaceId: workspaceId as never, ...(agentPreset === undefined ? {} : { agentPreset }) }))
63
+ if (!created.result.ok) throw failure(created.result.error)
64
+ const sessionId = created.result.value.sessionId
65
+ const renamed = await this.api.sessions.rename(request({ sessionId, title }))
66
+ if (!renamed.result.ok) throw failure(renamed.result.error)
67
+ const prompted = await this.api.sessions.prompt(request({ sessionId, mode: 'queue' as const, content: [{ type: 'text' as const, text: promptText.replaceAll('{{SESSION_ID}}', sessionId) }] }))
68
+ if (!prompted.result.ok) throw failure(prompted.result.error)
69
+ return sessionId
70
+ }
71
+ }
72
+
73
+ function isObject(value: unknown): value is Record<string, unknown> { return typeof value === 'object' && value !== null }
74
+ function collectText(value: unknown): string[] {
75
+ if (Array.isArray(value)) return value.flatMap(collectText)
76
+ if (!isObject(value)) return []
77
+ if (value.type === 'text' && typeof value.text === 'string') return [value.text]
78
+ return 'content' in value ? collectText(value.content) : []
79
+ }
80
+
81
+ function common(requirement: RequirementView, context: ReturnType<ReviewContextCatalog['resolve']>): string {
82
+ return [
83
+ `Requirement ID: ${requirement.id}`,
84
+ `Pinned commit: ${requirement.currentCommit}`,
85
+ '',
86
+ reviewContextPrompt(context),
87
+ '',
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,供用户快速选择;不得只重复“接受、拒绝、待验证”这类通用状态。',
93
+ ].join('\n')
94
+ }
95
+ function reviewPrompt(requirement: RequirementView, run: AiReviewRun, context: ReturnType<ReviewContextCatalog['resolve']>): string {
96
+ const tasks: Record<AiReviewRun['kind'], string> = {
97
+ '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.',
98
+ '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.',
99
+ '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.',
100
+ '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.',
101
+ }
102
+ return [common(requirement, context), `Review run ID: ${run.id}`, `Review kind: ${run.kind}`, `AI session ID: {{SESSION_ID}}`, '', tasks[run.kind]].join('\n')
103
+ }
104
+ function commentPrompt(requirement: RequirementView, comment: CommentThread, context: ReturnType<ReviewContextCatalog['resolve']>): string {
105
+ 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')
106
+ }
package/src/routes.ts ADDED
@@ -0,0 +1,52 @@
1
+ import type { IncomingMessage, ServerResponse } from 'node:http'
2
+ import type { WebRoute } from '@deepseek-ai/dsh-host-webserver'
3
+ import type { CollaborationEngine } from './engine.ts'
4
+ import { API_PREFIX, parseEnvelope } from './protocol.ts'
5
+ import type { DshReviewCoordinator } from './review-runtime.ts'
6
+
7
+ const BODY_LIMIT = 2 * 1024 * 1024
8
+ const HEARTBEAT_MS = 15_000
9
+ function json(res: ServerResponse, status: number, body: unknown): void { res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store', 'referrer-policy': 'no-referrer' }); res.end(JSON.stringify(body)) }
10
+ function trusted(req: IncomingMessage): boolean { const remote = req.socket.remoteAddress; if (!(remote === '127.0.0.1' || remote === '::1' || remote === '::ffff:127.0.0.1')) return false; if (req.headers['sec-fetch-site'] === 'cross-site') return false; const origin = req.headers.origin; if (origin === undefined) return req.headers['sec-fetch-site'] === 'same-origin'; try { return new URL(origin).host === req.headers.host } catch { return false } }
11
+ async function readJson(req: IncomingMessage): Promise<unknown> { const chunks: Buffer[] = []; let size = 0; for await (const chunk of req) { const buffer = chunk as Buffer; size += buffer.length; if (size > BODY_LIMIT) throw new Error('body-too-large'); chunks.push(buffer) } return JSON.parse(Buffer.concat(chunks).toString('utf8')) }
12
+
13
+ export function makeRoutes(engine: CollaborationEngine, coordinator: DshReviewCoordinator): WebRoute[] {
14
+ const guard = (req: IncomingMessage, res: ServerResponse): boolean => { if (trusted(req)) return true; json(res, 403, { ok: false, error: 'forbidden' }); return false }
15
+ return [
16
+ { kind: 'exact', path: `${API_PREFIX}/state`, handler: (req, res) => { if (req.method !== 'GET') return json(res, 405, { ok: false, error: 'method-not-allowed' }); if (!guard(req, res)) return; const state = engine.snapshot(); json(res, 200, { revision: state.revision, participants: state.participants, requirements: engine.list() }) } },
17
+ { kind: 'exact', path: `${API_PREFIX}/review-workspaces`, handler: async (req, res) => { if (req.method !== 'GET') return json(res, 405, { ok: false, error: 'method-not-allowed' }); if (!guard(req, res)) return; try { json(res, 200, { ok: true, workspaces: await coordinator.reviewWorkspaces() }) } catch (error) { json(res, 400, { ok: false, error: error instanceof Error ? error.message : String(error) }) } } },
18
+ { kind: 'exact', path: `${API_PREFIX}/version`, handler: (req, res) => { if (req.method !== 'GET') return json(res, 405, { ok: false, error: 'method-not-allowed' }); if (!guard(req, res)) return; try { const url = new URL(req.url ?? '', `http://${req.headers.host ?? '127.0.0.1'}`); const requirementId = url.searchParams.get('requirementId') ?? ''; const commit = url.searchParams.get('commit') ?? ''; json(res, 200, { ok: true, version: engine.version(requirementId, commit) }) } catch (error) { json(res, 404, { ok: false, error: error instanceof Error ? error.message : String(error) }) } } },
19
+ { kind: 'exact', path: `${API_PREFIX}/my-items`, handler: (req, res) => {
20
+ if (req.method !== 'GET') return json(res, 405, { ok: false, error: 'method-not-allowed' })
21
+ if (!guard(req, res)) return
22
+ const url = new URL(req.url ?? '', `http://${req.headers.host ?? '127.0.0.1'}`)
23
+ const participantId = url.searchParams.get('participantId') ?? ''
24
+ const role = url.searchParams.get('role')
25
+ if (participantId.length < 8 || (role !== 'product' && role !== 'engineering')) return json(res, 400, { ok: false, error: 'invalid-participant-query' })
26
+ return json(res, 200, { ok: true, items: engine.myItems({ participantId, nickname: '当前参与者', role, kind: 'human' }) })
27
+ } },
28
+ { kind: 'exact', path: `${API_PREFIX}/action`, handler: async (req, res) => { if (req.method !== 'POST') return json(res, 405, { ok: false, error: 'method-not-allowed' }); if (!guard(req, res)) return; if (!(req.headers['content-type'] ?? '').toLowerCase().startsWith('application/json')) return json(res, 415, { ok: false, error: 'json-required' }); try { const envelope = parseEnvelope(await readJson(req)); if (envelope === undefined) return json(res, 400, { ok: false, error: 'invalid-action' }); if ((envelope.action.kind === 'requirement.create' || envelope.action.kind === 'requirement.bind-workspace') && typeof envelope.action.workspaceId === 'string' && envelope.action.workspaceId.trim() !== '') await coordinator.assertWorkspaceAvailable(envelope.action.workspaceId); const result = engine.apply(envelope.requestId, envelope.action); json(res, result.ok ? 200 : result.error === 'base-commit-conflict' ? 409 : 400, result) } catch (error) { const message = error instanceof Error ? error.message : String(error); json(res, message === 'body-too-large' ? 413 : 400, { ok: false, error: message }) } } },
29
+ { kind: 'exact', path: `${API_PREFIX}/ai-conversation`, handler: async (req, res) => {
30
+ if (!guard(req, res)) return
31
+ try {
32
+ if (req.method === 'GET') {
33
+ const url = new URL(req.url ?? '', `http://${req.headers.host ?? '127.0.0.1'}`)
34
+ const requirementId = url.searchParams.get('requirementId') ?? ''
35
+ const sessionId = url.searchParams.get('sessionId') ?? ''
36
+ if (!engine.hasAiSession(requirementId, sessionId)) return json(res, 404, { ok: false, error: 'AI 会话不属于该需求' })
37
+ return json(res, 200, { ok: true, messages: await coordinator.conversation(sessionId) })
38
+ }
39
+ if (req.method === 'POST') {
40
+ if (!(req.headers['content-type'] ?? '').toLowerCase().startsWith('application/json')) return json(res, 415, { ok: false, error: 'json-required' })
41
+ const body = await readJson(req) as { requirementId?: unknown; sessionId?: unknown; text?: unknown }
42
+ if (typeof body.requirementId !== 'string' || typeof body.sessionId !== 'string' || typeof body.text !== 'string') return json(res, 400, { ok: false, error: 'invalid-follow-up' })
43
+ if (!engine.hasAiSession(body.requirementId, body.sessionId)) return json(res, 404, { ok: false, error: 'AI 会话不属于该需求' })
44
+ await coordinator.followUp(body.sessionId, body.text)
45
+ return json(res, 202, { ok: true })
46
+ }
47
+ return json(res, 405, { ok: false, error: 'method-not-allowed' })
48
+ } catch (error) { return json(res, 400, { ok: false, error: error instanceof Error ? error.message : String(error) }) }
49
+ } },
50
+ { kind: 'exact', path: `${API_PREFIX}/events`, handler: (req, res) => { if (req.method !== 'GET') { res.writeHead(405); res.end(); return } if (!guard(req, res)) return; res.writeHead(200, { 'content-type': 'text/event-stream; charset=utf-8', 'cache-control': 'no-cache', connection: 'keep-alive' }); const push = (): void => { res.write(`data: ${JSON.stringify({ revision: engine.snapshot().revision })}\n\n`) }; const unsubscribe = engine.subscribe(push); const heartbeat = setInterval(() => { res.write(': ping\n\n') }, HEARTBEAT_MS); const close = (): void => { clearInterval(heartbeat); unsubscribe() }; req.once('close', close); res.once('close', close); push() } },
51
+ ]
52
+ }
package/src/tools.ts ADDED
@@ -0,0 +1,80 @@
1
+ import { defineTool } from '@deepseek-ai/dsh-tools'
2
+ import type { ContentBlock } from '@deepseek-ai/dsh-llm'
3
+ import { CollaborationEngine } from './engine.ts'
4
+ import type { EpistemicStatus, ParticipantRole, ParticipantSnapshot, ReviewItemStatus, ReviewItemType, ReviewKind, Severity } from './protocol.ts'
5
+
6
+ function text(value: string): ContentBlock[] { return [{ type: 'text', text: value }] }
7
+ function ai(nickname: string, role: ParticipantRole, sessionId: string): ParticipantSnapshot { return { participantId: `ai:${sessionId}`, nickname, role, kind: 'ai', sessionId } }
8
+ function contentOutput(description: string) { return { schema: { type: 'object' as const, additionalProperties: false as const, properties: { content: { type: 'string' as const, required: true as const, description } } }, render: (_args: unknown, value: { content: string }) => text(value.content) } as const }
9
+
10
+ export function specListTool(engine: CollaborationEngine) {
11
+ return defineTool({
12
+ name: 'spec_list', description: 'List shared collaborative requirements and their product-review, joint-review, or Ready stage. This product stops at Ready Spec.', parameters: {},
13
+ output: contentOutput('Requirement list.'),
14
+ async execute() { return { content: engine.list().map(item => `${item.id} | ${item.stage} | ${item.currentCommit.slice(0, 10)} | ${item.reviewItems.filter(review => review.severity === 'blocking' && review.status !== 'resolved').length} blockers | ${item.title}`).join('\n') || 'no requirements' } },
15
+ })
16
+ }
17
+
18
+ export function specReadTool(engine: CollaborationEngine) {
19
+ return defineTool({
20
+ name: 'spec_read', description: 'Read one requirement at its exact current Git commit, with selected collaboration context. Use this before any review submission.',
21
+ parameters: { requirementId: { type: 'string', required: true }, include: { type: 'array', items: { type: 'string', enum: ['spec', 'review-items', 'comments', 'decisions', 'confirmations', 'sources', 'readiness'] }, description: 'Sections to include; default includes all current context.' } },
22
+ output: contentOutput('Pinned requirement context.'),
23
+ async execute(args) {
24
+ const view = engine.view(args.requirementId)
25
+ const include = new Set(args.include ?? ['spec', 'review-items', 'comments', 'decisions', 'confirmations', 'sources', 'readiness'])
26
+ const rows = [`# ${view.title}`, `stage: ${view.stage}`, `commit: ${view.currentCommit}`]
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'}`))
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
+ if (include.has('decisions')) rows.push('', '## Decisions', ...view.decisions.map(item => `- ${item.id} [${item.status}] ${item.question}: ${item.decision}`))
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}`))
32
+ if (include.has('sources')) rows.push('', '## Sources', ...view.sources.map(item => `- ${item.id} [${item.accessStatus}] ${item.label}${item.version ? ` @ ${item.version}` : ''}`))
33
+ if (include.has('readiness')) rows.push('', '## Readiness', ...view.readiness.map(item => `- ${item.passed ? 'PASS' : 'FAIL'} ${item.key}: ${item.reasons.join('; ')}`))
34
+ return { content: rows.join('\n') }
35
+ },
36
+ })
37
+ }
38
+
39
+ export function specReplyTool(engine: CollaborationEngine) {
40
+ return defineTool({
41
+ name: 'spec_reply', description: 'Post the required AI analysis to one substantive Spec comment. Include understanding, evidence or TO_VERIFY, affected sections/AC IDs, and proposed disposition.',
42
+ parameters: { requirementId: { type: 'string', required: true }, commentId: { type: 'string', required: true }, body: { type: 'string', required: true }, nickname: { type: 'string', required: true }, role: { type: 'string', required: true, enum: ['product', 'engineering'] }, sessionId: { type: 'string', required: true } },
43
+ output: contentOutput('Reply result.'),
44
+ async execute(args) { engine.submitAiReply({ requirementId: args.requirementId, commentId: args.commentId, ai: ai(args.nickname, args.role as ParticipantRole, args.sessionId), body: args.body }); return { content: 'AI analysis posted' } },
45
+ })
46
+ }
47
+
48
+ export function specSubmitReviewTool(engine: CollaborationEngine) {
49
+ return defineTool({
50
+ name: 'spec_submit_review', description: 'Submit structured, commit-pinned AI Review Items. AI may propose findings but cannot confirm or mark Ready. FACT requires accessible versioned evidence.',
51
+ parameters: {
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
+ nickname: { type: 'string', required: true }, role: { type: 'string', required: true, enum: ['product', 'engineering'] }, sessionId: { type: 'string', required: true }, maturitySummary: { type: 'string', required: true },
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 }, recommendedOptions: { type: 'array', required: true, items: { type: 'string' }, description: '至少三个可直接供用户选择的具体中文建议,不得只是同义改写。' }, 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
+ } } },
57
+ },
58
+ output: contentOutput('Review submission result.'),
59
+ async execute(args) {
60
+ for (const item of args.items) {
61
+ const options = item.recommendedOptions.map(option => option.trim()).filter(Boolean)
62
+ if (options.length < 3 || new Set(options).size < 3) throw new Error('each review item requires at least three distinct recommended options')
63
+ if (item.epistemicStatus === 'FACT' && !item.evidence.some(evidence => evidence.accessible && typeof evidence.version === 'string' && evidence.version !== '')) throw new Error('FACT requires accessible versioned evidence')
64
+ }
65
+ 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 })) })
66
+ return { content: `submitted ${args.items.length} review items for ${args.commit}` }
67
+ },
68
+ })
69
+ }
70
+
71
+ export function specProposePatchTool(engine: CollaborationEngine) {
72
+ return defineTool({
73
+ name: 'spec_propose_patch', description: 'Propose a complete revised Markdown Spec against an exact base commit. This creates a reviewable candidate only; it never writes Git.',
74
+ parameters: { requirementId: { type: 'string', required: true }, baseCommit: { type: 'string', required: true }, reviewKind: { type: 'string', required: true, enum: ['product-first', 'product-second', 'engineering-precheck', 'change-review'] }, proposedMarkdown: { type: 'string', required: true }, summary: { type: 'string', required: true }, affectedReviewItemIds: { type: 'array', required: true, items: { type: 'string' } }, affectedSections: { type: 'array', required: true, items: { type: 'string' } }, affectedAcceptanceIds: { type: 'array', required: true, items: { type: 'string' } }, nickname: { type: 'string', required: true }, role: { type: 'string', required: true, enum: ['product', 'engineering'] }, sessionId: { type: 'string', required: true } },
75
+ output: contentOutput('Patch proposal result.'),
76
+ async execute(args) { engine.submitPatch({ requirementId: args.requirementId, baseCommit: args.baseCommit, reviewKind: args.reviewKind as ReviewKind, ai: ai(args.nickname, args.role as ParticipantRole, args.sessionId), proposedMarkdown: args.proposedMarkdown, summary: args.summary, affectedReviewItemIds: args.affectedReviewItemIds, affectedSections: args.affectedSections, affectedAcceptanceIds: args.affectedAcceptanceIds }); return { content: `candidate patch proposed for ${args.baseCommit}` } },
77
+ })
78
+ }
79
+
80
+ export function allSpecTools(engine: CollaborationEngine) { return [specListTool(engine), specReadTool(engine), specReplyTool(engine), specSubmitReviewTool(engine), specProposePatchTool(engine)] }