dsh-spec-collab 0.4.0 → 0.5.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.
- package/CHANGELOG.md +14 -0
- package/README.md +16 -16
- package/docs/assets/demo-01-workspace.png +0 -0
- package/docs/assets/demo-02-ai-review.png +0 -0
- package/docs/assets/demo-03-patches.png +0 -0
- package/docs/assets/demo-04-decisions.png +0 -0
- package/docs/assets/demo-05-ready.png +0 -0
- package/docs/core-refactor-ablation.md +59 -0
- package/docs/usage-walkthrough.md +7 -7
- package/lib/client.js +247 -236
- package/lib/index.js +1481 -1376
- package/lib/types/collaboration-ledger.d.ts +14 -0
- package/lib/types/collaboration-ledger.d.ts.map +1 -0
- package/lib/types/engine.d.ts +19 -29
- package/lib/types/engine.d.ts.map +1 -1
- package/lib/types/git-store.d.ts +24 -10
- package/lib/types/git-store.d.ts.map +1 -1
- package/lib/types/insights.d.ts +29 -0
- package/lib/types/insights.d.ts.map +1 -0
- package/lib/types/ready-admission.d.ts +1 -0
- package/lib/types/ready-admission.d.ts.map +1 -1
- package/lib/types/review-runtime.d.ts +32 -2
- package/lib/types/review-runtime.d.ts.map +1 -1
- package/lib/types/routes.d.ts.map +1 -1
- package/lib/types/spec-lifecycle.d.ts +18 -0
- package/lib/types/spec-lifecycle.d.ts.map +1 -0
- package/package.json +34 -29
- package/src/collaboration-ledger.ts +168 -0
- package/src/engine.ts +306 -516
- package/src/git-store.ts +212 -141
- package/src/insights.ts +186 -0
- package/src/ready-admission.ts +5 -1
- package/src/review-runtime.ts +37 -3
- package/src/routes.ts +6 -4
- package/src/spec-lifecycle.ts +126 -0
package/src/review-runtime.ts
CHANGED
|
@@ -7,8 +7,18 @@ import { DEFAULT_REVIEW_PROMPTS, extractPromptValue, renderPrompt, resolveReview
|
|
|
7
7
|
import { ReviewContextCatalog, reviewContextPrompt } from './review-context.ts'
|
|
8
8
|
import { readWorkspaceSnapshot } from './workspace-context.ts'
|
|
9
9
|
|
|
10
|
+
interface ReviewHistoryEvent { type: string; data: unknown }
|
|
11
|
+
interface ReviewHistoryPage {
|
|
12
|
+
cursor: number
|
|
13
|
+
records: readonly { type: 'event'; event: ReviewHistoryEvent & { seq: number } }[]
|
|
14
|
+
hasMore: boolean
|
|
15
|
+
}
|
|
16
|
+
interface ReviewHistoryReader {
|
|
17
|
+
events?(request: { address: { kind: 'session'; sessionId: SessionPromptRequest['sessionId'] }; maxMessages: number; throughSeq?: number; beforeSeq?: number }, signal: AbortSignal): Promise<ReviewHistoryPage>
|
|
18
|
+
inspect?(sessionId: SessionPromptRequest['sessionId'], signal: AbortSignal): Promise<{ events: readonly ReviewHistoryEvent[] }>
|
|
19
|
+
}
|
|
10
20
|
export interface DshReviewHost {
|
|
11
|
-
sessionController: Pick<SessionController, 'create' | 'rename' | 'prompt'
|
|
21
|
+
sessionController: Pick<SessionController, 'create' | 'rename' | 'prompt'> & ReviewHistoryReader
|
|
12
22
|
workspaceRegistry: Pick<WorkspaceRegistry, 'list'>
|
|
13
23
|
agentPresets: Pick<AgentPresetRegistry, 'list'>
|
|
14
24
|
}
|
|
@@ -45,10 +55,10 @@ export class DshReviewCoordinator implements AiCoordinator {
|
|
|
45
55
|
})
|
|
46
56
|
}
|
|
47
57
|
async conversation(sessionId: string): Promise<Array<{ role: 'user' | 'assistant'; text: string }>> {
|
|
48
|
-
const
|
|
58
|
+
const events = await this.conversationEvents(sessionId as SessionPromptRequest['sessionId'])
|
|
49
59
|
const rows: Array<{ role: 'user' | 'assistant'; text: string }> = []
|
|
50
60
|
let skippedOrchestrationPrompt = false
|
|
51
|
-
for (const entry of
|
|
61
|
+
for (const entry of events) {
|
|
52
62
|
if (entry.type !== 'user/message' && entry.type !== 'assistant/message') continue
|
|
53
63
|
if (entry.type === 'user/message' && !skippedOrchestrationPrompt) { skippedOrchestrationPrompt = true; continue }
|
|
54
64
|
const value = entry.data as unknown
|
|
@@ -66,6 +76,30 @@ export class DshReviewCoordinator implements AiCoordinator {
|
|
|
66
76
|
}
|
|
67
77
|
return rows
|
|
68
78
|
}
|
|
79
|
+
private async conversationEvents(sessionId: SessionPromptRequest['sessionId']): Promise<readonly ReviewHistoryEvent[]> {
|
|
80
|
+
const controller = this.host.sessionController
|
|
81
|
+
if (controller.events !== undefined) {
|
|
82
|
+
const pages: ReviewHistoryEvent[][] = []
|
|
83
|
+
let throughSeq: number | undefined
|
|
84
|
+
let beforeSeq: number | undefined
|
|
85
|
+
for (;;) {
|
|
86
|
+
this.lifetime.signal.throwIfAborted()
|
|
87
|
+
const page = await controller.events({
|
|
88
|
+
address: { kind: 'session', sessionId }, maxMessages: 100,
|
|
89
|
+
...(throughSeq === undefined ? {} : { throughSeq }),
|
|
90
|
+
...(beforeSeq === undefined ? {} : { beforeSeq }),
|
|
91
|
+
}, this.lifetime.signal)
|
|
92
|
+
throughSeq ??= page.cursor
|
|
93
|
+
pages.push(page.records.map(record => record.event))
|
|
94
|
+
if (!page.hasMore) return pages.reverse().flat()
|
|
95
|
+
const firstSeq = page.records[0]?.event.seq
|
|
96
|
+
if (firstSeq === undefined || !Number.isSafeInteger(firstSeq) || firstSeq < 0 || (beforeSeq !== undefined && firstSeq >= beforeSeq)) throw new Error('history pagination did not advance')
|
|
97
|
+
beforeSeq = firstSeq
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
if (controller.inspect !== undefined) return (await controller.inspect(sessionId, this.lifetime.signal)).events
|
|
101
|
+
throw new Error('DSH Session history API is unavailable')
|
|
102
|
+
}
|
|
69
103
|
async followUp(sessionId: string, text: string): Promise<void> {
|
|
70
104
|
const content = text.trim()
|
|
71
105
|
if (content === '') throw new Error('追问内容不能为空')
|
package/src/routes.ts
CHANGED
|
@@ -16,11 +16,13 @@ export function makeRoutes(engine: CollaborationEngine, coordinator: DshReviewCo
|
|
|
16
16
|
return [
|
|
17
17
|
{ kind: 'exact', path: `${API_PREFIX}/state`, handler: (req, res) => {
|
|
18
18
|
if (req.method !== 'GET') return json(res, 405, { ok: false, error: 'method-not-allowed' }); if (!guard(req, res)) return
|
|
19
|
-
const
|
|
20
|
-
const
|
|
19
|
+
const overview = engine.overview()
|
|
20
|
+
const url = new URL(req.url ?? '', `http://${req.headers.host ?? '127.0.0.1'}`)
|
|
21
|
+
const requestedId = url.searchParams.get('requirementId')
|
|
22
|
+
const currentId = requestedId ?? overview.requirements.find(item => item.archivedAt === undefined)?.id ?? overview.requirements[0]?.id
|
|
21
23
|
let requirement
|
|
22
24
|
try { requirement = currentId ? engine.view(currentId) : undefined } catch {}
|
|
23
|
-
json(res, 200, {
|
|
25
|
+
json(res, 200, { ...overview, ...(requirement ? { requirement } : {}) })
|
|
24
26
|
} },
|
|
25
27
|
{ kind: 'exact', path: `${API_PREFIX}/directory`, handler: (req, res) => { if (req.method !== 'GET') return json(res, 405, { ok: false, error: 'method-not-allowed' }); if (!guard(req, res)) return; json(res, 200, { ok: true, participants: engine.directory() }) } },
|
|
26
28
|
{ kind: 'exact', path: `${API_PREFIX}/notifications`, handler: (req, res) => {
|
|
@@ -76,6 +78,6 @@ export function makeRoutes(engine: CollaborationEngine, coordinator: DshReviewCo
|
|
|
76
78
|
return json(res, 405, { ok: false, error: 'method-not-allowed' })
|
|
77
79
|
} catch (error) { return json(res, 400, { ok: false, error: error instanceof Error ? error.message : String(error) }) }
|
|
78
80
|
} },
|
|
79
|
-
{ 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 = (event: CollaborationEvent): void => { res.write(`data: ${JSON.stringify(event)}\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({ types: ['state.synced'], revision: engine.
|
|
81
|
+
{ 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 = (event: CollaborationEvent): void => { res.write(`data: ${JSON.stringify(event)}\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({ types: ['state.synced'], revision: engine.revision }) } },
|
|
80
82
|
]
|
|
81
83
|
}
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto'
|
|
2
|
+
import type { ActionItem, CollaborationAction, ParticipantSnapshot, ReadinessCheck, RequirementRecord } from './protocol.ts'
|
|
3
|
+
import { currentVersionConfirmations, hasCompletedCurrentReview, hasVersionConfirmation } from './ready-admission.ts'
|
|
4
|
+
|
|
5
|
+
type DecisionSourceAnchor = NonNullable<Extract<CollaborationAction, { kind: 'decision.create' }>['sourceAnchors']>[number]
|
|
6
|
+
|
|
7
|
+
export function enterStage(record: RequirementRecord, stage: RequirementRecord['stage']): void {
|
|
8
|
+
if (record.stage === stage) return
|
|
9
|
+
record.stage = stage
|
|
10
|
+
record.stageCycle += 1
|
|
11
|
+
}
|
|
12
|
+
export function advance(record: RequirementRecord, participant: ParticipantSnapshot): void {
|
|
13
|
+
if (record.stage === 'product-review') {
|
|
14
|
+
if (record.reviewItems.some(item => item.commit === record.currentCommit && item.severity === 'blocking' && !['resolved', 'non-blocking-verify', 'joint-review'].includes(item.status))) throw new Error('product blocking review items remain')
|
|
15
|
+
if (!hasCompletedCurrentReview(record, 'product-second')) throw new Error('product second review is required')
|
|
16
|
+
enterStage(record, 'product-confirmation'); return
|
|
17
|
+
}
|
|
18
|
+
if (record.stage === 'product-confirmation') {
|
|
19
|
+
if (participant.role !== 'product' || !hasVersionConfirmation(record, 'product')) throw new Error('product must confirm the current version')
|
|
20
|
+
enterStage(record, 'joint-review'); return
|
|
21
|
+
}
|
|
22
|
+
throw new Error('stage cannot advance directly')
|
|
23
|
+
}
|
|
24
|
+
function sections(markdown: string): Map<string, string> { const result = new Map<string, string>(); let heading = ''; for (const line of markdown.split('\n')) { if (/^##\s+/.test(line)) { heading = line.replace(/^##\s+/, '').trim(); result.set(heading, '') } else if (heading) result.set(heading, `${result.get(heading) ?? ''}\n${line}`) } return result }
|
|
25
|
+
function acceptance(markdown: string): Map<string, string> { const result = new Map<string, string>(); for (const match of markdown.matchAll(/\*\*(AC-[A-Za-z0-9-]+)(?:\s+[^*]+)?\*\*\s*[::]\s*(.+)/g)) result.set(match[1]!, match[2]!.trim()); return result }
|
|
26
|
+
function changedScopes(before: string, after: string): { sections: string[]; acceptanceIds: string[] } { const a = sections(before); const b = sections(after); const sectionNames = new Set([...a.keys(), ...b.keys()]); const acA = acceptance(before); const acB = acceptance(after); const acNames = new Set([...acA.keys(), ...acB.keys()]); return { sections: [...sectionNames].filter(key => a.get(key) !== b.get(key)), acceptanceIds: [...acNames].filter(key => acA.get(key) !== acB.get(key)) } }
|
|
27
|
+
function intersects(left: string[], right: string[]): boolean { return left.some(item => right.includes(item)) }
|
|
28
|
+
export function normalizeAnchorText(value: string): string { return value.replace(/[`*_>#\[\]()~-]/g, '').replace(/\s+/g, '').toLocaleLowerCase() }
|
|
29
|
+
function headingForLine(lines: string[], index: number): string | undefined {
|
|
30
|
+
for (let cursor = index; cursor >= 0; cursor -= 1) {
|
|
31
|
+
const match = /^#{1,4}\s+(.+)$/.exec(lines[cursor] ?? '')
|
|
32
|
+
if (match?.[1]) return match[1].trim()
|
|
33
|
+
}
|
|
34
|
+
return undefined
|
|
35
|
+
}
|
|
36
|
+
export function decisionScopeAnchors(markdown: string, affectedSections: string[], affectedAcceptanceIds: string[]): DecisionSourceAnchor[] {
|
|
37
|
+
const anchors: DecisionSourceAnchor[] = []
|
|
38
|
+
const sectionMap = sections(markdown)
|
|
39
|
+
for (const section of affectedSections.map(value => value.trim()).filter(Boolean)) {
|
|
40
|
+
const quote = sectionMap.get(section)?.split('\n').map(line => line.trim()).find(line => line && !/^#+\s+/.test(line))
|
|
41
|
+
if (quote) anchors.push({ heading: section, quote })
|
|
42
|
+
}
|
|
43
|
+
const lines = markdown.split('\n')
|
|
44
|
+
for (const acceptanceId of affectedAcceptanceIds.map(value => value.trim()).filter(Boolean)) {
|
|
45
|
+
const index = lines.findIndex(line => normalizeAnchorText(line).includes(normalizeAnchorText(acceptanceId)))
|
|
46
|
+
if (index >= 0) {
|
|
47
|
+
const heading = headingForLine(lines, index)
|
|
48
|
+
anchors.push({ ...(heading ? { heading } : {}), quote: lines[index]!.trim() })
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
return anchors
|
|
52
|
+
}
|
|
53
|
+
function decisionAnchorStillExists(markdown: string, anchor: DecisionSourceAnchor): boolean {
|
|
54
|
+
const quote = normalizeAnchorText(anchor.quote)
|
|
55
|
+
if (!quote) return false
|
|
56
|
+
const sectionMap = sections(markdown)
|
|
57
|
+
const candidates = anchor.heading?.trim() ? [sectionMap.get(anchor.heading.trim()) ?? ''] : [markdown]
|
|
58
|
+
const context = normalizeAnchorText(`${anchor.prefix ?? ''}${anchor.quote}${anchor.suffix ?? ''}`)
|
|
59
|
+
return candidates.some(candidate => {
|
|
60
|
+
const normalized = normalizeAnchorText(candidate)
|
|
61
|
+
return normalized.includes(context) || normalized.includes(quote)
|
|
62
|
+
})
|
|
63
|
+
}
|
|
64
|
+
export function invalidateAffected(record: RequirementRecord, changedSections: string[], changedAcceptanceIds: string[], currentMarkdown?: string): void {
|
|
65
|
+
for (const confirmation of record.confirmations) {
|
|
66
|
+
if (confirmation.status !== 'active') continue
|
|
67
|
+
const affected = confirmation.scope === 'version' || (confirmation.scope === 'section' && confirmation.scopeId !== undefined && changedSections.includes(confirmation.scopeId)) || (confirmation.scope === 'acceptance-criterion' && confirmation.scopeId !== undefined && changedAcceptanceIds.includes(confirmation.scopeId))
|
|
68
|
+
if (affected) { confirmation.status = 'invalidated'; record.actionItems.push({ id: randomUUID(), requirementId: record.id, sourceType: 'confirmation', sourceId: confirmation.id, type: 'reconfirm', assigneeRole: confirmation.role, blocking: true, status: 'pending', dueStage: record.stage, createdAt: Date.now(), updatedAt: Date.now() }) }
|
|
69
|
+
}
|
|
70
|
+
record.reviewItems.filter(item => item.status === 'resolved' && (intersects(item.affectedSections, changedSections) || intersects(item.affectedAcceptanceIds, changedAcceptanceIds))).forEach(item => { item.status = 'invalidated'; item.updatedAt = Date.now() })
|
|
71
|
+
record.decisions.filter(item => item.status === 'active' && (intersects(item.affectedSections, changedSections) || intersects(item.affectedAcceptanceIds, changedAcceptanceIds))).forEach(item => { item.status = 'invalidated' })
|
|
72
|
+
if (currentMarkdown !== undefined) record.decisions.filter(item => item.status === 'active' && item.sourceAnchors?.some(anchor => !decisionAnchorStillExists(currentMarkdown, anchor))).forEach(item => { item.status = 'invalidated' })
|
|
73
|
+
}
|
|
74
|
+
export function readiness(markdown: string, record: RequirementRecord): ReadinessCheck[] {
|
|
75
|
+
const sectionMap = sections(markdown); const ac = acceptance(markdown)
|
|
76
|
+
const meaningful = (name: string): boolean => { const value = sectionMap.get(name)?.replace(/<!--.*?-->/gs, '').trim() ?? ''; return value.length >= 12 && !/待澄清|待补充|TODO/i.test(value) }
|
|
77
|
+
const blockers = record.reviewItems.filter(item => item.commit === record.currentCommit && item.severity === 'blocking' && !['resolved', 'non-blocking-verify'].includes(item.status)).map(item => item.statement)
|
|
78
|
+
return [
|
|
79
|
+
{ key: 'goal', passed: meaningful('目标与用户结果'), reasons: meaningful('目标与用户结果') ? [] : ['缺少可观察的目标与用户结果'] },
|
|
80
|
+
{ key: 'acceptance', passed: ac.size > 0 && [...ac.values()].every(value => !/待澄清|待补充|TODO/i.test(value)), reasons: ac.size === 0 ? ['缺少稳定 AC ID 与可判定结果'] : [...ac.values()].some(value => /待澄清|待补充|TODO/i.test(value)) ? ['验收标准仍含占位内容'] : [] },
|
|
81
|
+
{ key: 'scope', passed: meaningful('范围与非范围'), reasons: meaningful('范围与非范围') ? [] : ['范围与非范围不完整'] },
|
|
82
|
+
{ key: 'semantics', passed: meaningful('业务术语与规则'), reasons: meaningful('业务术语与规则') ? [] : ['关键术语和规则不完整'] },
|
|
83
|
+
{ key: 'evidence', passed: record.sources.every(source => source.accessStatus !== 'missing') && blockers.length === 0, reasons: [...record.sources.filter(source => source.accessStatus === 'missing').map(source => `来源不可访问:${source.label}`), ...blockers] },
|
|
84
|
+
{ key: 'test-constraints', passed: meaningful('测试约束'), reasons: meaningful('测试约束') ? [] : ['测试环境、账号、权限或 fixture 约束不完整'] },
|
|
85
|
+
]
|
|
86
|
+
}
|
|
87
|
+
export function versionChanged(record: RequirementRecord, previousMarkdown: string, version: { commit: string; markdown: string }, now: number): void {
|
|
88
|
+
const impact = changedScopes(previousMarkdown, version.markdown)
|
|
89
|
+
record.currentCommit = version.commit
|
|
90
|
+
record.updatedAt = now
|
|
91
|
+
delete record.readyPackage
|
|
92
|
+
if (record.stage === 'ready') enterStage(record, 'joint-review')
|
|
93
|
+
for (const patch of record.patches) {
|
|
94
|
+
if (patch.status !== 'pending') continue
|
|
95
|
+
patch.status = 'stale'
|
|
96
|
+
retireActionItems(record, 'patch', patch.id, 'invalidated', now)
|
|
97
|
+
}
|
|
98
|
+
invalidateAffected(record, impact.sections, impact.acceptanceIds, version.markdown)
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export function retireActionItems(record: RequirementRecord, sourceType: ActionItem['sourceType'], sourceId: string, status: 'handled' | 'invalidated', now: number): void {
|
|
102
|
+
for (const task of record.actionItems) {
|
|
103
|
+
if (task.sourceType === sourceType && task.sourceId === sourceId && task.status === 'pending') {
|
|
104
|
+
task.status = status
|
|
105
|
+
task.updatedAt = now
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
export function readyMarkdown(record: RequirementRecord, markdown: string): string {
|
|
111
|
+
const signers = (role: ParticipantSnapshot['role']) => [...new Set(currentVersionConfirmations(record, role).map(item => item.participant.nickname))].join('、')
|
|
112
|
+
const open = record.reviewItems.filter(item => item.status === 'non-blocking-verify')
|
|
113
|
+
const sourceStatus = { available: '可查阅', unverified: '待核对', missing: '待补充' } as const
|
|
114
|
+
return [
|
|
115
|
+
`# 就绪需求:${record.title}`, '', '## 版本信息', '',
|
|
116
|
+
`- 需求编号:${record.id}`, `- 文档版本:${record.currentCommit}`,
|
|
117
|
+
`- 产品确认:${signers('product')}`, `- 研发确认:${signers('engineering')}`,
|
|
118
|
+
'', markdown, '', '## 已确认决策',
|
|
119
|
+
...record.decisions.filter(item => item.status === 'active').map(item => `- ${item.question}:${item.decision}(原因:${item.rationale})`),
|
|
120
|
+
'', '## 参考资料',
|
|
121
|
+
...record.sources.map(source => `- [${sourceStatus[source.accessStatus]}] ${source.label}${source.stableId ? `:${source.stableId}` : ''}${source.version ? `(版本:${source.version})` : ''}`),
|
|
122
|
+
'', '## 待确认问题',
|
|
123
|
+
...open.map(item => `- ${item.question};负责人:${item.ownerParticipantId ?? (item.ownerRole === 'product' ? '产品' : '研发')};影响:${item.impact}`),
|
|
124
|
+
'',
|
|
125
|
+
].join('\n')
|
|
126
|
+
}
|