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.
- package/LICENSE +201 -0
- package/README.md +106 -0
- package/cordis.patch.yml +3 -0
- package/lib/client.js +41298 -0
- package/lib/index.js +1986 -0
- package/lib/types/client/SpecWorkbench.d.ts +6 -0
- package/lib/types/client/SpecWorkbench.d.ts.map +1 -0
- package/lib/types/client/api.d.ts +20 -0
- package/lib/types/client/api.d.ts.map +1 -0
- package/lib/types/client/index.d.ts +4 -0
- package/lib/types/client/index.d.ts.map +1 -0
- package/lib/types/client/mount.d.ts +4 -0
- package/lib/types/client/mount.d.ts.map +1 -0
- package/lib/types/engine.d.ts +67 -0
- package/lib/types/engine.d.ts.map +1 -0
- package/lib/types/git-store.d.ts +40 -0
- package/lib/types/git-store.d.ts.map +1 -0
- package/lib/types/index.d.ts +12 -0
- package/lib/types/index.d.ts.map +1 -0
- package/lib/types/protocol.d.ts +358 -0
- package/lib/types/protocol.d.ts.map +1 -0
- package/lib/types/review-context.d.ts +32 -0
- package/lib/types/review-context.d.ts.map +1 -0
- package/lib/types/review-runtime.d.ts +26 -0
- package/lib/types/review-runtime.d.ts.map +1 -0
- package/lib/types/routes.d.ts +5 -0
- package/lib/types/routes.d.ts.map +1 -0
- package/lib/types/tools.d.ts +8 -0
- package/lib/types/tools.d.ts.map +1 -0
- package/package.json +96 -0
- package/src/client/SpecWorkbench.tsx +293 -0
- package/src/client/api.ts +12 -0
- package/src/client/css-modules.d.ts +1 -0
- package/src/client/index.ts +16 -0
- package/src/client/mount.tsx +73 -0
- package/src/client/toast-ui.d.ts +25 -0
- package/src/client/workbench.module.css +275 -0
- package/src/engine.ts +358 -0
- package/src/git-store.ts +133 -0
- package/src/index.ts +49 -0
- package/src/protocol.ts +108 -0
- package/src/review-context.ts +87 -0
- package/src/review-runtime.ts +106 -0
- package/src/routes.ts +52 -0
- package/src/tools.ts +80 -0
package/src/engine.ts
ADDED
|
@@ -0,0 +1,358 @@
|
|
|
1
|
+
import { createHash, randomUUID } from 'node:crypto'
|
|
2
|
+
import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
|
|
3
|
+
import { dirname } from 'node:path'
|
|
4
|
+
import { GitRequirementStore, VersionConflictError } from './git-store.ts'
|
|
5
|
+
import { SCHEMA_VERSION, type ActionItem, type ActionResult, type AiReviewRun, type CandidatePatch, type CollaborationAction, type CollaborationState, type CommentThread, type MyActionItem, type MyItemCategory, type ParticipantSnapshot, type ReadinessCheck, type RequirementRecord, type RequirementVersion, type RequirementView, type ReviewItem, type ReviewKind, type SaveConflict } from './protocol.ts'
|
|
6
|
+
|
|
7
|
+
export interface AiCoordinator {
|
|
8
|
+
requestReview(input: { requirement: RequirementView; run: AiReviewRun }): Promise<string>
|
|
9
|
+
requestCommentReply(input: { requirement: RequirementView; comment: CommentThread }): Promise<string>
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
const emptyState = (): CollaborationState => ({ schemaVersion: SCHEMA_VERSION, revision: 0, participants: [], requirements: [] })
|
|
13
|
+
|
|
14
|
+
type EngineResult = ActionResult
|
|
15
|
+
|
|
16
|
+
export class CollaborationEngine {
|
|
17
|
+
private state: CollaborationState
|
|
18
|
+
private coordinator?: AiCoordinator
|
|
19
|
+
private readonly listeners = new Set<() => void>()
|
|
20
|
+
private readonly seen = new Map<string, EngineResult>()
|
|
21
|
+
|
|
22
|
+
constructor(private readonly eventPath: string, private readonly versions: GitRequirementStore) { this.state = this.load() }
|
|
23
|
+
setCoordinator(coordinator: AiCoordinator): void { this.coordinator = coordinator }
|
|
24
|
+
snapshot(): CollaborationState { return structuredClone(this.state) }
|
|
25
|
+
subscribe(listener: () => void): () => void { this.listeners.add(listener); return () => this.listeners.delete(listener) }
|
|
26
|
+
list(): RequirementView[] { return this.state.requirements.map(item => this.view(item.id)) }
|
|
27
|
+
version(requirementId: string, commit: string): RequirementVersion {
|
|
28
|
+
const record = this.record(requirementId)
|
|
29
|
+
if (!this.versions.history(record.id).some(version => version.commit === commit)) throw new Error('requirement version not found')
|
|
30
|
+
return this.versions.read(record.id, commit)
|
|
31
|
+
}
|
|
32
|
+
myItems(participant: ParticipantSnapshot, category?: MyItemCategory): MyActionItem[] {
|
|
33
|
+
const rows: MyActionItem[] = []
|
|
34
|
+
for (const record of this.state.requirements) {
|
|
35
|
+
for (const item of record.actionItems.filter(candidate => candidate.status === 'pending')) {
|
|
36
|
+
const categories: MyItemCategory[] = []
|
|
37
|
+
const assigned = item.assigneeParticipantId === participant.participantId || (item.assigneeParticipantId === undefined && item.assigneeRole === participant.role)
|
|
38
|
+
if (assigned) categories.push(item.type === 'confirm' || item.type === 'reconfirm' ? 'awaiting-my-confirmation' : 'awaiting-my-response')
|
|
39
|
+
if (sourceParticipantId(record, item) === participant.participantId) categories.push('initiated-by-me')
|
|
40
|
+
for (const current of categories) if (category === undefined || category === current) rows.push({ ...structuredClone(item), category: current, requirementTitle: record.title, target: actionTarget(item) })
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
return rows.sort((left, right) => Number(right.blocking) - Number(left.blocking) || right.updatedAt - left.updatedAt)
|
|
44
|
+
}
|
|
45
|
+
hasAiSession(requirementId: string, sessionId: string): boolean {
|
|
46
|
+
const record = this.record(requirementId)
|
|
47
|
+
return record.aiRuns.some(run => run.sessionId === sessionId) || record.comments.some(comment => comment.aiSessionId === sessionId)
|
|
48
|
+
}
|
|
49
|
+
view(id: string): RequirementView {
|
|
50
|
+
const record = this.record(id)
|
|
51
|
+
const version = this.versions.read(id, record.currentCommit)
|
|
52
|
+
return { ...structuredClone(record), version, history: this.versions.history(id), readiness: readiness(version.markdown, record) }
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
apply(requestId: string, action: CollaborationAction): EngineResult {
|
|
56
|
+
const cached = this.seen.get(requestId)
|
|
57
|
+
if (cached !== undefined) return structuredClone(cached)
|
|
58
|
+
let result: EngineResult
|
|
59
|
+
try {
|
|
60
|
+
const registered = action.participant.kind === 'human' ? this.state.participants.find(item => item.participantId === action.participant.participantId) : undefined
|
|
61
|
+
if (registered !== undefined && registered.role !== action.participant.role) throw new Error(`participant role is bound to ${registered.role}`)
|
|
62
|
+
result = this.applyFresh(action)
|
|
63
|
+
if (result.ok && action.participant.kind === 'human' && registered === undefined) {
|
|
64
|
+
this.state.participants.push(structuredClone(action.participant)); this.persist()
|
|
65
|
+
result = result.deletedRequirementId
|
|
66
|
+
? { ...result, revision: this.state.revision }
|
|
67
|
+
: { ok: true, revision: this.state.revision, requirement: this.view(result.requirement.id) }
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
catch (error) {
|
|
71
|
+
const conflict = error instanceof VersionConflictError && action.kind === 'version.save' ? this.saveConflict(action) : undefined
|
|
72
|
+
result = { ok: false, revision: this.state.revision, error: error instanceof Error ? error.message : String(error), ...(conflict === undefined ? {} : { conflict }) }
|
|
73
|
+
}
|
|
74
|
+
this.seen.set(requestId, result)
|
|
75
|
+
return structuredClone(result)
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
submitReview(input: { requirementId: string; commit: string; runId: string; ai: ParticipantSnapshot; items: Omit<ReviewItem, 'id' | 'requirementId' | 'commit' | 'reviewKind' | 'createdAt' | 'updatedAt'>[]; maturitySummary: string }): void {
|
|
79
|
+
const record = this.record(input.requirementId)
|
|
80
|
+
const run = record.aiRuns.find(item => item.id === input.runId)
|
|
81
|
+
if (run === undefined || run.commit !== input.commit || record.currentCommit !== input.commit) throw new Error('review run is stale')
|
|
82
|
+
assertChineseFeedback(input.maturitySummary)
|
|
83
|
+
const now = Date.now()
|
|
84
|
+
for (const item of input.items) {
|
|
85
|
+
assertChineseFeedback(item.statement, item.impact, item.question)
|
|
86
|
+
if (item.epistemicStatus === 'FACT' && !item.evidence.some(evidence => evidence.accessible && evidence.version !== undefined && evidence.version !== '')) throw new Error('FACT requires accessible versioned evidence')
|
|
87
|
+
const recommendedOptions = item.recommendedOptions?.map(option => option.trim()).filter(Boolean)
|
|
88
|
+
const created: ReviewItem = { ...item, ...(recommendedOptions ? { recommendedOptions } : {}), id: randomUUID(), requirementId: record.id, commit: input.commit, reviewKind: run.kind, createdAt: now, updatedAt: now }
|
|
89
|
+
record.reviewItems.push(created)
|
|
90
|
+
record.actionItems.push(actionForReview(created))
|
|
91
|
+
}
|
|
92
|
+
run.status = 'completed'; run.maturitySummary = input.maturitySummary; run.updatedAt = now
|
|
93
|
+
this.persist()
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
submitPatch(input: { requirementId: string; baseCommit: string; reviewKind: ReviewKind; ai: ParticipantSnapshot; proposedMarkdown: string; summary: string; affectedReviewItemIds: string[]; affectedSections: string[]; affectedAcceptanceIds: string[] }): void {
|
|
97
|
+
const record = this.record(input.requirementId)
|
|
98
|
+
if (record.currentCommit !== input.baseCommit) throw new Error('patch base commit is stale')
|
|
99
|
+
assertChineseFeedback(input.summary, input.proposedMarkdown)
|
|
100
|
+
const patch: CandidatePatch = { id: randomUUID(), requirementId: record.id, baseCommit: input.baseCommit, reviewKind: input.reviewKind, proposedMarkdown: input.proposedMarkdown, summary: input.summary, affectedReviewItemIds: input.affectedReviewItemIds, affectedSections: input.affectedSections, affectedAcceptanceIds: input.affectedAcceptanceIds, createdBy: input.ai, status: 'pending', createdAt: Date.now() }
|
|
101
|
+
record.patches.push(patch)
|
|
102
|
+
record.actionItems.push({ id: randomUUID(), requirementId: record.id, sourceType: 'patch', sourceId: patch.id, type: 'confirm', assigneeRole: input.reviewKind === 'engineering-precheck' ? 'engineering' : 'product', blocking: true, status: 'pending', dueStage: record.stage, createdAt: Date.now(), updatedAt: Date.now() })
|
|
103
|
+
this.persist()
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
submitAiReply(input: { requirementId: string; commentId: string; ai: ParticipantSnapshot; body: string }): void {
|
|
107
|
+
assertChineseFeedback(input.body)
|
|
108
|
+
const record = this.record(input.requirementId)
|
|
109
|
+
const comment = this.comment(record, input.commentId)
|
|
110
|
+
comment.replies.push({ id: randomUUID(), author: input.ai, body: input.body, createdAt: Date.now() })
|
|
111
|
+
comment.aiStatus = 'completed'; comment.updatedAt = Date.now()
|
|
112
|
+
this.persist()
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
markAiFailure(requirementId: string, sourceId: string, error: string): void {
|
|
116
|
+
const record = this.record(requirementId)
|
|
117
|
+
const run = record.aiRuns.find(item => item.id === sourceId)
|
|
118
|
+
if (run !== undefined) { run.status = 'failed'; run.error = error; run.updatedAt = Date.now() }
|
|
119
|
+
const comment = record.comments.find(item => item.id === sourceId)
|
|
120
|
+
if (comment !== undefined) { comment.aiStatus = 'failed'; comment.updatedAt = Date.now() }
|
|
121
|
+
this.persist()
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
private applyFresh(action: CollaborationAction): EngineResult {
|
|
125
|
+
const now = Date.now()
|
|
126
|
+
if (action.kind === 'requirement.create') {
|
|
127
|
+
requireHuman(action.participant)
|
|
128
|
+
const title = action.title.trim()
|
|
129
|
+
if (title === '' || action.rawRequirement.trim() === '') throw new Error('title and original requirement are required')
|
|
130
|
+
const workspaceId = action.workspaceId?.trim()
|
|
131
|
+
if (workspaceId === undefined || workspaceId === '') throw new Error('review workspace is required')
|
|
132
|
+
const created = this.versions.create({ title, rawRequirement: action.rawRequirement, sources: action.sources, participant: action.participant })
|
|
133
|
+
const record: RequirementRecord = { id: created.requirementId, title, stage: 'product-review', currentCommit: created.version.commit, workspaceId, sources: action.sources, reviewItems: [], comments: [], patches: [], decisions: [], confirmations: [], actionItems: [], aiRuns: [], createdAt: now, updatedAt: now }
|
|
134
|
+
this.state.requirements.unshift(record); this.persist()
|
|
135
|
+
this.enqueueReview(record, action.participant, 'product-first')
|
|
136
|
+
return { ok: true, revision: this.state.revision, requirement: this.view(record.id) }
|
|
137
|
+
}
|
|
138
|
+
const record = this.record(action.requirementId)
|
|
139
|
+
if (action.kind === 'requirement.bind-workspace') {
|
|
140
|
+
requireHuman(action.participant)
|
|
141
|
+
const workspaceId = action.workspaceId.trim()
|
|
142
|
+
if (workspaceId === '') throw new Error('review workspace is required')
|
|
143
|
+
if (record.workspaceId !== undefined) throw new Error('review workspace is already bound')
|
|
144
|
+
record.workspaceId = workspaceId; record.updatedAt = now; this.persist()
|
|
145
|
+
} else if (action.kind === 'requirement.rename') {
|
|
146
|
+
requireHuman(action.participant)
|
|
147
|
+
const title = action.title.trim()
|
|
148
|
+
if (title === '' || title.length > 120 || /[\r\n]/.test(title)) throw new Error('valid requirement title is required')
|
|
149
|
+
if (title === record.title) return { ok: true, revision: this.state.revision, requirement: this.view(record.id) }
|
|
150
|
+
const before = this.versions.read(record.id, record.currentCommit).markdown
|
|
151
|
+
const markdown = /^# .+$/m.test(before) ? before.replace(/^# .+$/m, `# ${title}`) : `# ${title}\n\n${before}`
|
|
152
|
+
const version = this.versions.save({ requirementId: record.id, baseCommit: record.currentCommit, markdown, participant: action.participant, summary: `Rename requirement: ${title}` })
|
|
153
|
+
record.title = title; record.currentCommit = version.commit; record.updatedAt = now
|
|
154
|
+
invalidateAffected(record, [], []); this.persist(); this.enqueueReview(record, action.participant, 'change-review')
|
|
155
|
+
} else if (action.kind === 'requirement.archive') {
|
|
156
|
+
requireHuman(action.participant)
|
|
157
|
+
if (action.archived) record.archivedAt = now
|
|
158
|
+
else delete record.archivedAt
|
|
159
|
+
record.updatedAt = now; this.persist()
|
|
160
|
+
} else if (action.kind === 'requirement.delete') {
|
|
161
|
+
requireHuman(action.participant)
|
|
162
|
+
const deleted = this.view(record.id)
|
|
163
|
+
this.versions.remove(record.id, action.participant)
|
|
164
|
+
this.state.requirements.splice(this.state.requirements.indexOf(record), 1)
|
|
165
|
+
this.persist()
|
|
166
|
+
return { ok: true, revision: this.state.revision, requirement: deleted, deletedRequirementId: record.id }
|
|
167
|
+
} else if (action.kind === 'version.save') {
|
|
168
|
+
requireHuman(action.participant)
|
|
169
|
+
const before = this.versions.read(record.id, record.currentCommit).markdown
|
|
170
|
+
const version = this.versions.save({ requirementId: record.id, baseCommit: action.baseCommit, markdown: action.markdown, participant: action.participant, summary: action.summary })
|
|
171
|
+
const impact = changedScopes(before, action.markdown)
|
|
172
|
+
record.currentCommit = version.commit; record.updatedAt = now; delete record.readyPackage
|
|
173
|
+
invalidateAffected(record, impact.sections, impact.acceptanceIds)
|
|
174
|
+
record.patches.filter(item => item.status === 'pending').forEach(item => { item.status = 'stale' })
|
|
175
|
+
if (record.stage === 'ready') record.stage = 'joint-review'
|
|
176
|
+
this.persist()
|
|
177
|
+
this.enqueueReview(record, action.participant, 'change-review')
|
|
178
|
+
} else if (action.kind === 'review.request') {
|
|
179
|
+
requireHuman(action.participant)
|
|
180
|
+
this.enqueueReview(record, action.participant, action.reviewKind)
|
|
181
|
+
} else if (action.kind === 'review.respond') {
|
|
182
|
+
requireHuman(action.participant)
|
|
183
|
+
const item = record.reviewItems.find(candidate => candidate.id === action.reviewItemId)
|
|
184
|
+
if (item === undefined) throw new Error('review item not found')
|
|
185
|
+
item.response = { participant: action.participant, disposition: action.disposition, body: action.body.trim(), createdAt: now }
|
|
186
|
+
item.status = action.disposition === 'joint-review' ? 'joint-review' : action.disposition === 'to-verify' ? 'non-blocking-verify' : 'answered'
|
|
187
|
+
item.updatedAt = now
|
|
188
|
+
record.actionItems.filter(task => task.sourceId === item.id && task.status === 'pending').forEach(task => { task.status = 'handled'; task.updatedAt = now })
|
|
189
|
+
this.persist()
|
|
190
|
+
} else if (action.kind === 'comment.create') {
|
|
191
|
+
requireHuman(action.participant)
|
|
192
|
+
if (action.commit !== record.currentCommit) throw new VersionConflictError(record.currentCommit)
|
|
193
|
+
const comment: CommentThread = { id: randomUUID(), requirementId: record.id, commit: action.commit, anchor: action.anchor, author: action.participant, body: action.body.trim(), replies: [], aiStatus: 'queued', status: 'open', createdAt: now, updatedAt: now }
|
|
194
|
+
if (comment.body === '' || comment.anchor.quote.trim() === '') throw new Error('comment and anchor are required')
|
|
195
|
+
record.comments.push(comment)
|
|
196
|
+
record.actionItems.push({ id: randomUUID(), requirementId: record.id, sourceType: 'comment', sourceId: comment.id, type: 'reply', assigneeRole: action.participant.role === 'product' ? 'engineering' : 'product', blocking: true, status: 'pending', dueStage: record.stage, createdAt: now, updatedAt: now })
|
|
197
|
+
this.persist()
|
|
198
|
+
const coordinator = this.coordinator
|
|
199
|
+
if (coordinator !== undefined) {
|
|
200
|
+
const view = this.view(record.id)
|
|
201
|
+
void coordinator.requestCommentReply({ requirement: view, comment }).then(sessionId => {
|
|
202
|
+
comment.aiStatus = 'running'; comment.aiSessionId = sessionId; comment.updatedAt = Date.now(); this.persist()
|
|
203
|
+
}, error => this.markAiFailure(record.id, comment.id, error instanceof Error ? error.message : String(error)))
|
|
204
|
+
}
|
|
205
|
+
} else if (action.kind === 'comment.reply') {
|
|
206
|
+
requireHuman(action.participant)
|
|
207
|
+
const comment = this.comment(record, action.commentId)
|
|
208
|
+
comment.replies.push({ id: randomUUID(), author: action.participant, body: action.body.trim(), createdAt: now }); comment.updatedAt = now; this.persist()
|
|
209
|
+
} else if (action.kind === 'comment.resolve') {
|
|
210
|
+
requireHuman(action.participant)
|
|
211
|
+
const comment = this.comment(record, action.commentId)
|
|
212
|
+
comment.status = 'resolved'; comment.resolution = action.resolution; comment.updatedAt = now
|
|
213
|
+
record.actionItems.filter(task => task.sourceId === comment.id && task.status === 'pending').forEach(task => { task.status = 'handled'; task.updatedAt = now }); this.persist()
|
|
214
|
+
} else if (action.kind === 'patch.accept') {
|
|
215
|
+
requireHuman(action.participant)
|
|
216
|
+
const patch = record.patches.find(item => item.id === action.patchId)
|
|
217
|
+
if (patch === undefined || patch.status !== 'pending') throw new Error('pending patch not found')
|
|
218
|
+
const version = this.versions.save({ requirementId: record.id, baseCommit: patch.baseCommit, markdown: patch.proposedMarkdown, participant: action.participant, summary: action.summary })
|
|
219
|
+
record.currentCommit = version.commit; patch.status = 'accepted'; record.updatedAt = now
|
|
220
|
+
for (const id of patch.affectedReviewItemIds) { const item = record.reviewItems.find(candidate => candidate.id === id); if (item !== undefined) { item.status = 'resolved'; item.updatedAt = now } }
|
|
221
|
+
record.actionItems.filter(task => task.sourceId === patch.id && task.status === 'pending').forEach(task => { task.status = 'handled'; task.updatedAt = now }); this.persist()
|
|
222
|
+
this.enqueueReview(record, action.participant, 'change-review')
|
|
223
|
+
} else if (action.kind === 'patch.reject') {
|
|
224
|
+
requireHuman(action.participant)
|
|
225
|
+
const patch = record.patches.find(item => item.id === action.patchId); if (patch === undefined) throw new Error('patch not found'); patch.status = 'rejected'; this.persist()
|
|
226
|
+
} else if (action.kind === 'decision.create') {
|
|
227
|
+
requireHuman(action.participant)
|
|
228
|
+
record.decisions.push({ id: randomUUID(), requirementId: record.id, commit: record.currentCommit, question: action.question, options: action.options, decision: action.decision, rationale: action.rationale, confirmer: action.participant, affectedSections: action.affectedSections, affectedAcceptanceIds: action.affectedAcceptanceIds, createdAt: now, status: 'active' }); this.persist()
|
|
229
|
+
} else if (action.kind === 'confirmation.create') {
|
|
230
|
+
requireHuman(action.participant)
|
|
231
|
+
if (action.participant.role !== action.role) throw new Error(`${action.role} role is required`)
|
|
232
|
+
record.confirmations.push({ id: randomUUID(), requirementId: record.id, commit: record.currentCommit, role: action.role, participant: action.participant, scope: action.scope, ...(action.scopeId === undefined ? {} : { scopeId: action.scopeId }), status: 'active', createdAt: now })
|
|
233
|
+
if (action.role === 'product' && action.scope === 'version') record.productConfirmedCommit = record.currentCommit
|
|
234
|
+
if (action.role === 'engineering' && action.scope === 'version') record.jointConfirmedCommit = record.currentCommit
|
|
235
|
+
this.persist()
|
|
236
|
+
} else if (action.kind === 'stage.advance') {
|
|
237
|
+
requireHuman(action.participant)
|
|
238
|
+
advance(record, action.participant); this.persist()
|
|
239
|
+
} else if (action.kind === 'ready.generate') {
|
|
240
|
+
requireHuman(action.participant)
|
|
241
|
+
const checks = readiness(this.versions.read(record.id, record.currentCommit).markdown, record)
|
|
242
|
+
if (record.stage !== 'joint-review' || checks.some(check => !check.passed)) throw new Error('readiness gate is not satisfied')
|
|
243
|
+
if (!hasVersionConfirmation(record, 'product') || !hasVersionConfirmation(record, 'engineering')) throw new Error('current version needs product and engineering confirmation')
|
|
244
|
+
const markdown = readyMarkdown(this.view(record.id))
|
|
245
|
+
record.readyPackage = { requirementId: record.id, commit: record.currentCommit, packageHash: createHash('sha256').update(markdown).digest('hex'), generatedAt: now, generatedBy: action.participant, markdown }
|
|
246
|
+
record.stage = 'ready'; this.persist()
|
|
247
|
+
} else if (action.kind === 'downstream.return') {
|
|
248
|
+
requireHuman(action.participant)
|
|
249
|
+
if (action.summary.trim() === '') throw new Error('downstream issue summary is required')
|
|
250
|
+
if (action.affectedSections.length === 0 && action.affectedAcceptanceIds.length === 0) throw new Error('downstream return requires an affected section or AC')
|
|
251
|
+
const item: ReviewItem = {
|
|
252
|
+
id: randomUUID(), requirementId: record.id, commit: record.currentCommit, reviewKind: 'change-review', type: 'semantics', severity: 'blocking',
|
|
253
|
+
statement: action.summary.trim(), evidence: action.evidence, epistemicStatus: action.evidence.some(evidence => evidence.accessible && evidence.version !== undefined) ? 'FACT' : 'TO_VERIFY',
|
|
254
|
+
impact: `下游发现影响 ${[...action.affectedSections, ...action.affectedAcceptanceIds].join('、')},需要重新澄清并确认。`, question: '应如何修订受影响的需求语义或验收标准?',
|
|
255
|
+
affectedSections: [...new Set(action.affectedSections)], affectedAcceptanceIds: [...new Set(action.affectedAcceptanceIds)], ownerRole: 'product', status: 'open', createdAt: now, updatedAt: now,
|
|
256
|
+
}
|
|
257
|
+
record.reviewItems.push(item)
|
|
258
|
+
record.actionItems.push(actionForReview(item))
|
|
259
|
+
invalidateAffected(record, item.affectedSections, item.affectedAcceptanceIds)
|
|
260
|
+
delete record.readyPackage
|
|
261
|
+
record.stage = 'joint-review'; record.updatedAt = now; this.persist()
|
|
262
|
+
this.enqueueReview(record, action.participant, 'change-review')
|
|
263
|
+
}
|
|
264
|
+
return { ok: true, revision: this.state.revision, requirement: this.view(record.id) }
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
private saveConflict(action: Extract<CollaborationAction, { kind: 'version.save' }>): SaveConflict {
|
|
268
|
+
const record = this.record(action.requirementId)
|
|
269
|
+
const baseMarkdown = this.versions.read(record.id, action.baseCommit).markdown
|
|
270
|
+
const currentMarkdown = this.versions.read(record.id, record.currentCommit).markdown
|
|
271
|
+
return { requirementId: record.id, baseCommit: action.baseCommit, currentCommit: record.currentCommit, baseMarkdown, currentMarkdown, draftMarkdown: action.markdown, baseToCurrentDiff: textDiff(baseMarkdown, currentMarkdown), baseToDraftDiff: textDiff(baseMarkdown, action.markdown) }
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
private enqueueReview(record: RequirementRecord, participant: ParticipantSnapshot, kind: ReviewKind): void {
|
|
275
|
+
const now = Date.now()
|
|
276
|
+
const run: AiReviewRun = { id: randomUUID(), requirementId: record.id, commit: record.currentCommit, kind, status: 'queued', requestedBy: participant, createdAt: now, updatedAt: now }
|
|
277
|
+
record.aiRuns.push(run)
|
|
278
|
+
this.persist()
|
|
279
|
+
const coordinator = this.coordinator
|
|
280
|
+
if (coordinator === undefined) { this.markAiFailure(record.id, run.id, 'AI coordinator unavailable'); return }
|
|
281
|
+
const view = this.view(record.id)
|
|
282
|
+
void coordinator.requestReview({ requirement: view, run }).then(sessionId => {
|
|
283
|
+
run.status = 'running'; run.sessionId = sessionId; run.updatedAt = Date.now(); this.persist()
|
|
284
|
+
}, error => this.markAiFailure(record.id, run.id, error instanceof Error ? error.message : String(error)))
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
private record(id: string): RequirementRecord { const value = this.state.requirements.find(item => item.id === id); if (value === undefined) throw new Error('requirement not found'); return value }
|
|
288
|
+
private comment(record: RequirementRecord, id: string): CommentThread { const value = record.comments.find(item => item.id === id); if (value === undefined) throw new Error('comment not found'); return value }
|
|
289
|
+
private persist(): void { this.state.revision += 1; mkdirSync(dirname(this.eventPath), { recursive: true, mode: 0o700 }); const tmp = `${this.eventPath}.tmp`; writeFileSync(tmp, JSON.stringify(this.state, null, 2), { mode: 0o600 }); renameSync(tmp, this.eventPath); for (const listener of this.listeners) listener() }
|
|
290
|
+
private load(): CollaborationState { try { const value = JSON.parse(readFileSync(this.eventPath, 'utf8')) as CollaborationState; if (value.schemaVersion === SCHEMA_VERSION) { value.participants ??= []; return value } } catch {} return emptyState() }
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
function sourceParticipantId(record: RequirementRecord, item: ActionItem): string | undefined {
|
|
294
|
+
if (item.sourceType === 'comment') return record.comments.find(value => value.id === item.sourceId)?.author.participantId
|
|
295
|
+
if (item.sourceType === 'patch') return record.patches.find(value => value.id === item.sourceId)?.createdBy.participantId
|
|
296
|
+
if (item.sourceType === 'decision') return record.decisions.find(value => value.id === item.sourceId)?.confirmer.participantId
|
|
297
|
+
if (item.sourceType === 'confirmation') return record.confirmations.find(value => value.id === item.sourceId)?.participant.participantId
|
|
298
|
+
return record.reviewItems.find(value => value.id === item.sourceId)?.response?.participant.participantId
|
|
299
|
+
}
|
|
300
|
+
function actionTarget(item: ActionItem): MyActionItem['target'] {
|
|
301
|
+
const tabs = { 'review-item': 'review', comment: 'discussion', patch: 'patches', decision: 'decisions', confirmation: 'ready' } as const
|
|
302
|
+
return { tab: tabs[item.sourceType], objectId: item.sourceId }
|
|
303
|
+
}
|
|
304
|
+
function textDiff(before: string, after: string): string {
|
|
305
|
+
if (before === after) return ''
|
|
306
|
+
const left = before.split('\n'); const right = after.split('\n')
|
|
307
|
+
let start = 0
|
|
308
|
+
while (start < left.length && start < right.length && left[start] === right[start]) start += 1
|
|
309
|
+
let leftEnd = left.length - 1; let rightEnd = right.length - 1
|
|
310
|
+
while (leftEnd >= start && rightEnd >= start && left[leftEnd] === right[rightEnd]) { leftEnd -= 1; rightEnd -= 1 }
|
|
311
|
+
const contextStart = Math.max(0, start - 2); const contextLeftEnd = Math.min(left.length - 1, leftEnd + 2); const contextRightEnd = Math.min(right.length - 1, rightEnd + 2)
|
|
312
|
+
return [`@@ -${contextStart + 1},${contextLeftEnd - contextStart + 1} +${contextStart + 1},${contextRightEnd - contextStart + 1} @@`, ...left.slice(contextStart, start).map(line => ` ${line}`), ...left.slice(start, leftEnd + 1).map(line => `-${line}`), ...right.slice(start, rightEnd + 1).map(line => `+${line}`), ...right.slice(rightEnd + 1, contextRightEnd + 1).map(line => ` ${line}`)].join('\n')
|
|
313
|
+
}
|
|
314
|
+
function assertChineseFeedback(...values: string[]): void {
|
|
315
|
+
if (values.some(value => !/[\u3400-\u9fff]/.test(value))) throw new Error('AI 评审反馈必须使用中文')
|
|
316
|
+
}
|
|
317
|
+
function requireHuman(participant: ParticipantSnapshot): void { if (participant.kind !== 'human') throw new Error('human participant is required') }
|
|
318
|
+
function actionForReview(item: ReviewItem): ActionItem { const now = Date.now(); return { id: randomUUID(), requirementId: item.requirementId, sourceType: 'review-item', sourceId: item.id, type: 'reply', assigneeRole: item.ownerRole, blocking: item.severity === 'blocking', status: 'pending', dueStage: item.reviewKind.startsWith('product') ? 'product-review' : 'joint-review', createdAt: now, updatedAt: now } }
|
|
319
|
+
function hasVersionConfirmation(record: RequirementRecord, role: 'product' | 'engineering'): boolean { return record.confirmations.some(item => item.role === role && item.scope === 'version' && item.commit === record.currentCommit && item.status === 'active') }
|
|
320
|
+
function advance(record: RequirementRecord, participant: ParticipantSnapshot): void {
|
|
321
|
+
if (record.stage === 'product-review') {
|
|
322
|
+
if (record.reviewItems.some(item => item.severity === 'blocking' && !['resolved', 'non-blocking-verify', 'joint-review'].includes(item.status))) throw new Error('product blocking review items remain')
|
|
323
|
+
if (!record.aiRuns.some(run => run.kind === 'product-second' && run.commit === record.currentCommit && run.status === 'completed')) throw new Error('product second review is required')
|
|
324
|
+
record.stage = 'product-confirmation'; return
|
|
325
|
+
}
|
|
326
|
+
if (record.stage === 'product-confirmation') {
|
|
327
|
+
if (participant.role !== 'product' || !hasVersionConfirmation(record, 'product')) throw new Error('product must confirm the current version')
|
|
328
|
+
record.stage = 'joint-review'; return
|
|
329
|
+
}
|
|
330
|
+
throw new Error('stage cannot advance directly')
|
|
331
|
+
}
|
|
332
|
+
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 }
|
|
333
|
+
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*(.+)/g)) result.set(match[1]!, match[2]!.trim()); return result }
|
|
334
|
+
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)) } }
|
|
335
|
+
function intersects(left: string[], right: string[]): boolean { return left.some(item => right.includes(item)) }
|
|
336
|
+
function invalidateAffected(record: RequirementRecord, changedSections: string[], changedAcceptanceIds: string[]): void {
|
|
337
|
+
for (const confirmation of record.confirmations) {
|
|
338
|
+
if (confirmation.status !== 'active') continue
|
|
339
|
+
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))
|
|
340
|
+
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() }) }
|
|
341
|
+
}
|
|
342
|
+
record.reviewItems.filter(item => item.status === 'resolved' && (intersects(item.affectedSections, changedSections) || intersects(item.affectedAcceptanceIds, changedAcceptanceIds))).forEach(item => { item.status = 'invalidated'; item.updatedAt = Date.now() })
|
|
343
|
+
record.decisions.filter(item => item.status === 'active' && (intersects(item.affectedSections, changedSections) || intersects(item.affectedAcceptanceIds, changedAcceptanceIds))).forEach(item => { item.status = 'invalidated' })
|
|
344
|
+
}
|
|
345
|
+
export function readiness(markdown: string, record: RequirementRecord): ReadinessCheck[] {
|
|
346
|
+
const sectionMap = sections(markdown); const ac = acceptance(markdown)
|
|
347
|
+
const meaningful = (name: string): boolean => { const value = sectionMap.get(name)?.replace(/<!--.*?-->/gs, '').trim() ?? ''; return value.length >= 12 && !/待澄清|待补充|TODO/i.test(value) }
|
|
348
|
+
const blockers = record.reviewItems.filter(item => item.severity === 'blocking' && !['resolved', 'non-blocking-verify'].includes(item.status)).map(item => item.statement)
|
|
349
|
+
return [
|
|
350
|
+
{ key: 'goal', passed: meaningful('目标与用户结果'), reasons: meaningful('目标与用户结果') ? [] : ['缺少可观察的目标与用户结果'] },
|
|
351
|
+
{ 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)) ? ['验收标准仍含占位内容'] : [] },
|
|
352
|
+
{ key: 'scope', passed: meaningful('范围与非范围'), reasons: meaningful('范围与非范围') ? [] : ['范围与非范围不完整'] },
|
|
353
|
+
{ key: 'semantics', passed: meaningful('业务术语与规则'), reasons: meaningful('业务术语与规则') ? [] : ['关键术语和规则不完整'] },
|
|
354
|
+
{ 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] },
|
|
355
|
+
{ key: 'test-constraints', passed: meaningful('测试约束'), reasons: meaningful('测试约束') ? [] : ['测试环境、账号、权限或 fixture 约束不完整'] },
|
|
356
|
+
]
|
|
357
|
+
}
|
|
358
|
+
function readyMarkdown(view: RequirementView): string { const open = view.reviewItems.filter(item => item.status === 'non-blocking-verify'); return [`# Ready Spec:${view.title}`, '', `- 需求 ID:${view.id}`, `- Commit:${view.currentCommit}`, `- 产品确认:${view.confirmations.filter(item => item.role === 'product' && item.status === 'active').map(item => item.participant.nickname).join('、')}`, `- 研发确认:${view.confirmations.filter(item => item.role === 'engineering' && item.status === 'active').map(item => item.participant.nickname).join('、')}`, '', view.version.markdown, '', '## Decisions', ...view.decisions.filter(item => item.status === 'active').map(item => `- ${item.question}:${item.decision}(${item.rationale})`), '', '## 证据来源与版本', ...view.sources.map(source => `- [${source.accessStatus}] ${source.label}${source.stableId ? ` — ${source.stableId}` : ''}${source.version ? ` @ ${source.version}` : ''}`), '', '## 非阻塞 Open Questions', ...open.map(item => `- ${item.question};负责人:${item.ownerParticipantId ?? item.ownerRole};影响:${item.impact}`), ''].join('\n') }
|
package/src/git-store.ts
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import { execFileSync } from 'node:child_process'
|
|
2
|
+
import { randomUUID } from 'node:crypto'
|
|
3
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
|
|
4
|
+
import { dirname, join } from 'node:path'
|
|
5
|
+
import type { ParticipantSnapshot, RequirementVersion, SourceReference } from './protocol.ts'
|
|
6
|
+
|
|
7
|
+
export class VersionConflictError extends Error {
|
|
8
|
+
constructor(readonly currentCommit: string) { super('base-commit-conflict'); this.name = 'VersionConflictError' }
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export interface CreateRequirementInput { title: string; rawRequirement: string; sources: SourceReference[]; participant: ParticipantSnapshot }
|
|
12
|
+
export interface SaveVersionInput { requirementId: string; baseCommit: string; markdown: string; participant: ParticipantSnapshot; summary: string }
|
|
13
|
+
|
|
14
|
+
export class GitRequirementStore {
|
|
15
|
+
constructor(readonly root: string) { this.ensureRepository() }
|
|
16
|
+
|
|
17
|
+
create(input: CreateRequirementInput): { requirementId: string; version: RequirementVersion } {
|
|
18
|
+
const requirementId = `${slug(input.title)}-${randomUUID().slice(0, 8)}`
|
|
19
|
+
const markdown = initialSpec(input.title, input.rawRequirement, input.sources)
|
|
20
|
+
const path = this.specPath(requirementId)
|
|
21
|
+
mkdirSync(dirname(path), { recursive: true })
|
|
22
|
+
writeFileSync(path, markdown, 'utf8')
|
|
23
|
+
const commit = this.commit(requirementId, input.participant, 'Create requirement')
|
|
24
|
+
return { requirementId, version: this.read(requirementId, commit) }
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
save(input: SaveVersionInput): RequirementVersion {
|
|
28
|
+
const current = this.head(input.requirementId)
|
|
29
|
+
if (current !== input.baseCommit) throw new VersionConflictError(current)
|
|
30
|
+
const onDisk = readFileSync(this.specPath(input.requirementId), 'utf8')
|
|
31
|
+
if (onDisk !== this.read(input.requirementId, current).markdown) throw new Error('spec has external uncommitted changes')
|
|
32
|
+
if (input.summary.trim() === '') throw new Error('change summary is required')
|
|
33
|
+
if (input.markdown.length > 2_000_000) throw new Error('spec exceeds 2 MB')
|
|
34
|
+
writeFileSync(this.specPath(input.requirementId), input.markdown, 'utf8')
|
|
35
|
+
this.git(['add', this.relativeSpecPath(input.requirementId)])
|
|
36
|
+
const staged = this.git(['diff', '--cached', '--quiet'], true)
|
|
37
|
+
if (staged.status === 0) throw new Error('no changes to save')
|
|
38
|
+
const commit = this.commitStaged(input.participant, input.summary.trim())
|
|
39
|
+
return this.read(input.requirementId, commit)
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
read(requirementId: string, commit?: string): RequirementVersion {
|
|
43
|
+
assertRequirementId(requirementId)
|
|
44
|
+
const resolved = commit ?? this.head(requirementId)
|
|
45
|
+
const markdown = this.gitText(['show', `${resolved}:${this.relativeSpecPath(requirementId)}`])
|
|
46
|
+
const fields = this.gitText(['show', '-s', '--format=%H%x1f%P%x1f%at%x1f%an%x1f%ae%x1f%B', resolved]).split('\x1f')
|
|
47
|
+
const [sha = resolved, parents = '', seconds = '0', nickname = 'unknown', email = '', ...bodyParts] = fields
|
|
48
|
+
const body = bodyParts.join('\x1f').trim()
|
|
49
|
+
const role = /DSH-Role:\s*(product|engineering)/.exec(body)?.[1] as ParticipantSnapshot['role'] | undefined
|
|
50
|
+
const summary = body.split('\n')[0] ?? 'Saved version'
|
|
51
|
+
return {
|
|
52
|
+
commit: sha,
|
|
53
|
+
...(parents.split(' ')[0] ? { parentCommit: parents.split(' ')[0] } : {}),
|
|
54
|
+
markdown,
|
|
55
|
+
author: { participantId: email.replace(/@dsh\.local$/, '') || 'unknown', nickname, role: role ?? 'product', kind: 'human' },
|
|
56
|
+
summary,
|
|
57
|
+
createdAt: Number(seconds) * 1000,
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
history(requirementId: string): Array<Omit<RequirementVersion, 'markdown'>> {
|
|
62
|
+
assertRequirementId(requirementId)
|
|
63
|
+
const output = this.gitText(['log', '--format=%H%x1f%P%x1f%at%x1f%an%x1f%ae%x1f%B%x1e', '--', this.relativeSpecPath(requirementId)])
|
|
64
|
+
return output.split('\x1e').map(row => row.trim()).filter(Boolean).map(row => {
|
|
65
|
+
const [commit = '', parents = '', seconds = '0', nickname = 'unknown', email = '', ...bodyParts] = row.split('\x1f')
|
|
66
|
+
const body = bodyParts.join('\x1f').trim()
|
|
67
|
+
const role = /DSH-Role:\s*(product|engineering)/.exec(body)?.[1] as ParticipantSnapshot['role'] | undefined
|
|
68
|
+
return {
|
|
69
|
+
commit,
|
|
70
|
+
...(parents.split(' ')[0] ? { parentCommit: parents.split(' ')[0] } : {}),
|
|
71
|
+
author: { participantId: email.replace(/@dsh\.local$/, '') || 'unknown', nickname, role: role ?? 'product', kind: 'human' },
|
|
72
|
+
summary: body.split('\n')[0] ?? 'Saved version',
|
|
73
|
+
createdAt: Number(seconds) * 1000,
|
|
74
|
+
}
|
|
75
|
+
})
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
diff(requirementId: string, baseCommit: string, headCommit?: string): string {
|
|
79
|
+
assertRequirementId(requirementId)
|
|
80
|
+
return this.gitText(['diff', baseCommit, headCommit ?? this.head(requirementId), '--', this.relativeSpecPath(requirementId)])
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
remove(requirementId: string, participant: ParticipantSnapshot): void {
|
|
84
|
+
assertRequirementId(requirementId)
|
|
85
|
+
if (!existsSync(this.specPath(requirementId))) throw new Error('requirement spec not found')
|
|
86
|
+
this.git(['rm', '-r', `requirements/${requirementId}`])
|
|
87
|
+
this.commitStaged(participant, 'Delete requirement')
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
head(requirementId: string): string {
|
|
91
|
+
assertRequirementId(requirementId)
|
|
92
|
+
return this.gitText(['log', '-1', '--format=%H', '--', this.relativeSpecPath(requirementId)]).trim()
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
private commit(requirementId: string, participant: ParticipantSnapshot, summary: string): string {
|
|
96
|
+
this.git(['add', this.relativeSpecPath(requirementId)])
|
|
97
|
+
return this.commitStaged(participant, summary)
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
private commitStaged(participant: ParticipantSnapshot, summary: string): string {
|
|
101
|
+
const env = {
|
|
102
|
+
...process.env,
|
|
103
|
+
GIT_AUTHOR_NAME: participant.nickname,
|
|
104
|
+
GIT_AUTHOR_EMAIL: `${participant.participantId}@dsh.local`,
|
|
105
|
+
GIT_COMMITTER_NAME: participant.nickname,
|
|
106
|
+
GIT_COMMITTER_EMAIL: `${participant.participantId}@dsh.local`,
|
|
107
|
+
}
|
|
108
|
+
execFileSync('git', ['commit', '-m', summary, '-m', `DSH-Role: ${participant.role}`], { cwd: this.root, env, stdio: 'pipe' })
|
|
109
|
+
return this.gitText(['rev-parse', 'HEAD']).trim()
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
private ensureRepository(): void {
|
|
113
|
+
mkdirSync(this.root, { recursive: true, mode: 0o700 })
|
|
114
|
+
if (!existsSync(join(this.root, '.git'))) execFileSync('git', ['init'], { cwd: this.root, stdio: 'pipe' })
|
|
115
|
+
}
|
|
116
|
+
private relativeSpecPath(id: string): string { assertRequirementId(id); return `requirements/${id}/spec.md` }
|
|
117
|
+
private specPath(id: string): string { return join(this.root, this.relativeSpecPath(id)) }
|
|
118
|
+
private gitText(args: string[]): string { return execFileSync('git', args, { cwd: this.root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }) }
|
|
119
|
+
private git(args: string[], allowFailure = false): { status: number } {
|
|
120
|
+
try { execFileSync('git', args, { cwd: this.root, stdio: 'pipe' }); return { status: 0 } }
|
|
121
|
+
catch (error) { if (allowFailure) return { status: (error as { status?: number }).status ?? 1 }; throw error }
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function slug(title: string): string {
|
|
126
|
+
const value = title.toLowerCase().trim().replace(/[^a-z0-9\u4e00-\u9fff]+/g, '-').replace(/^-|-$/g, '').slice(0, 48)
|
|
127
|
+
return value || 'requirement'
|
|
128
|
+
}
|
|
129
|
+
function assertRequirementId(value: string): void { if (!/^[a-z0-9\u4e00-\u9fff][a-z0-9\u4e00-\u9fff-]{1,80}$/.test(value)) throw new Error('invalid requirement id') }
|
|
130
|
+
function initialSpec(title: string, raw: string, sources: SourceReference[]): string {
|
|
131
|
+
const sourceLines = sources.length === 0 ? ['- 原始需求:当前文档(创建版本)'] : sources.map(item => `- [${item.accessStatus}] ${item.label}${item.stableId ? ` — ${item.stableId}` : ''}`)
|
|
132
|
+
return [`# ${title}`, '', '## 原始需求与来源', '', raw.trim(), '', ...sourceLines, '', '## 目标与用户结果', '', '<!-- AI 初审后补充 -->', '', '## 范围与非范围', '', '### 范围', '', '### 非范围', '', '## 业务术语与规则', '', '## 需求与验收标准', '', '- **AC-1**:待澄清', '', '## 异常、权限与兼容', '', '## 测试约束', '', '## 非阻塞 Open Questions', ''].join('\n')
|
|
133
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { homedir } from 'node:os'
|
|
2
|
+
import { join } from 'node:path'
|
|
3
|
+
import type { Context } from '@deepseek-ai/cordis'
|
|
4
|
+
import Schema from 'schemastery'
|
|
5
|
+
import type {} from '@deepseek-ai/dsh-host-apiproxy'
|
|
6
|
+
import type {} from '@deepseek-ai/dsh-host-webserver'
|
|
7
|
+
import type {} from '@deepseek-ai/dsh-system-prompt'
|
|
8
|
+
import type {} from '@deepseek-ai/dsh-tools'
|
|
9
|
+
import { CollaborationEngine } from './engine.ts'
|
|
10
|
+
import { GitRequirementStore } from './git-store.ts'
|
|
11
|
+
import { DshReviewCoordinator } from './review-runtime.ts'
|
|
12
|
+
import { ReviewContextCatalog, type ReviewContextConfig } from './review-context.ts'
|
|
13
|
+
import { makeRoutes } from './routes.ts'
|
|
14
|
+
import { allSpecTools } from './tools.ts'
|
|
15
|
+
|
|
16
|
+
export const name = 'spec-collab'
|
|
17
|
+
export const inject = ['webServer', 'apiProxy', 'tools', 'systemPrompt']
|
|
18
|
+
export interface Config extends ReviewContextConfig { dataRoot?: string; repositoryPath?: string }
|
|
19
|
+
|
|
20
|
+
const stringList = () => Schema.array(Schema.string()).default([])
|
|
21
|
+
const contextFields = () => ({
|
|
22
|
+
skills: stringList().description('当前上下文必须先加载的 Skill 名称。'),
|
|
23
|
+
mcpServers: stringList().description('当前上下文可使用的 MCP serverName;工具 namespace 为 mcp__<serverName>__*。'),
|
|
24
|
+
documentPaths: stringList().description('AI 分析前可读取的本地文件或目录路径;相对路径按需求工作区根目录解析。'),
|
|
25
|
+
agentPreset: Schema.string().description('实际挂载这些 Skill/MCP 工具的 DSH Agent Preset ID。'),
|
|
26
|
+
})
|
|
27
|
+
export const Config: Schema<Config> = Schema.object({
|
|
28
|
+
dataRoot: Schema.string().description('协作账本数据目录。'),
|
|
29
|
+
repositoryPath: Schema.string().description('正式 Spec Git 仓库目录。'),
|
|
30
|
+
defaultContext: Schema.object(contextFields()).description('所有需求工作区都会合并的默认 AI 上下文。'),
|
|
31
|
+
workspaces: Schema.array(Schema.object({
|
|
32
|
+
workspaceId: Schema.string().required().description('需要追加项目专属 AI 上下文的 DSH workspaceId。'),
|
|
33
|
+
...contextFields(),
|
|
34
|
+
})).default([]).description('按 DSH 工作区追加的 AI 上下文;未列出的工作区仍继承 defaultContext。'),
|
|
35
|
+
}) as Schema<Config>
|
|
36
|
+
|
|
37
|
+
export function apply(ctx: Context, config: Config = {}): void {
|
|
38
|
+
const dataRoot = config.dataRoot ?? join(homedir(), '.dsh', 'spec-collab')
|
|
39
|
+
const contexts = new ReviewContextCatalog(config)
|
|
40
|
+
const engine = new CollaborationEngine(join(dataRoot, 'collaboration-v2.json'), new GitRequirementStore(config.repositoryPath ?? join(dataRoot, 'repository')))
|
|
41
|
+
const coordinator = new DshReviewCoordinator(ctx.apiProxy, contexts)
|
|
42
|
+
engine.setCoordinator(coordinator)
|
|
43
|
+
ctx.effect(() => { const disposers = makeRoutes(engine, coordinator).map(route => ctx.webServer.register(route)); return () => { for (const dispose of disposers) dispose() } }, 'spec-collab: routes')
|
|
44
|
+
ctx.effect(() => { const disposers = allSpecTools(engine).map(tool => ctx.tools.register(tool)); return () => { for (const dispose of disposers) dispose() } }, 'spec-collab: tools')
|
|
45
|
+
ctx.effect(() => ctx.systemPrompt.section({
|
|
46
|
+
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 参与审核。',
|
|
48
|
+
}), 'spec-collab: prompt')
|
|
49
|
+
}
|