dsh-spec-collab 0.2.2 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +11 -0
- package/README.md +84 -18
- 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/experience-review-checklist-2026-08-24.md +72 -45
- package/docs/insight-import-template.csv +3 -0
- package/docs/insight-import-template.md +19 -0
- package/docs/migration-v3.md +23 -0
- package/docs/usage-walkthrough.md +25 -43
- package/lib/client.js +10854 -1168
- package/lib/index.js +1313 -98
- package/lib/types/client/AccessibleDialog.d.ts +9 -0
- package/lib/types/client/AccessibleDialog.d.ts.map +1 -0
- package/lib/types/client/SpecWorkbench.d.ts +42 -2
- package/lib/types/client/SpecWorkbench.d.ts.map +1 -1
- package/lib/types/client/api.d.ts +26 -3
- package/lib/types/client/api.d.ts.map +1 -1
- package/lib/types/client/drafts.d.ts +8 -0
- package/lib/types/client/drafts.d.ts.map +1 -0
- package/lib/types/client/mount.d.ts.map +1 -1
- package/lib/types/client/review-anchors.d.ts.map +1 -1
- package/lib/types/client/workflow.d.ts.map +1 -1
- package/lib/types/engine.d.ts +37 -3
- package/lib/types/engine.d.ts.map +1 -1
- package/lib/types/git-store.d.ts +6 -0
- package/lib/types/git-store.d.ts.map +1 -1
- package/lib/types/protocol.d.ts +245 -10
- package/lib/types/protocol.d.ts.map +1 -1
- package/lib/types/ready-admission.d.ts +14 -0
- package/lib/types/ready-admission.d.ts.map +1 -0
- package/lib/types/review-runtime.d.ts +6 -0
- package/lib/types/review-runtime.d.ts.map +1 -1
- package/lib/types/routes.d.ts.map +1 -1
- package/lib/types/structured-diff.d.ts +3 -0
- package/lib/types/structured-diff.d.ts.map +1 -0
- package/package.json +14 -4
- package/src/client/AccessibleDialog.tsx +42 -0
- package/src/client/SpecWorkbench.tsx +776 -87
- package/src/client/api.ts +8 -3
- package/src/client/drafts.ts +51 -0
- package/src/client/mount.tsx +11 -6
- package/src/client/review-anchors.ts +1 -0
- package/src/client/workbench.module.css +223 -79
- package/src/client/workflow.ts +8 -9
- package/src/engine.ts +448 -46
- package/src/git-store.ts +87 -18
- package/src/index.ts +1 -1
- package/src/protocol.ts +64 -13
- package/src/ready-admission.ts +29 -0
- package/src/review-runtime.ts +39 -11
- package/src/routes.ts +33 -4
- package/src/structured-diff.ts +75 -0
- package/src/tools.ts +1 -1
- package/docs/assets/spec-collab-walkthrough.mp4 +0 -0
package/src/git-store.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { execFileSync } from 'node:child_process'
|
|
2
2
|
import { randomUUID } from 'node:crypto'
|
|
3
|
-
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
|
|
3
|
+
import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
|
|
4
4
|
import { dirname, join } from 'node:path'
|
|
5
5
|
import type { ParticipantSnapshot, RequirementVersion, SourceReference } from './protocol.ts'
|
|
6
6
|
|
|
@@ -12,16 +12,29 @@ export interface CreateRequirementInput { title: string; rawRequirement: string;
|
|
|
12
12
|
export interface SaveVersionInput { requirementId: string; baseCommit: string; markdown: string; participant: ParticipantSnapshot; summary: string }
|
|
13
13
|
|
|
14
14
|
export class GitRequirementStore {
|
|
15
|
+
private readonly versionCache = new Map<string, RequirementVersion>()
|
|
16
|
+
private readonly headCache = new Map<string, string>()
|
|
17
|
+
private readonly historyCache = new Map<string, Array<Omit<RequirementVersion, 'markdown'>>>()
|
|
18
|
+
private commitBaseUrl: string | null | undefined
|
|
19
|
+
|
|
15
20
|
constructor(readonly root: string) { this.ensureRepository() }
|
|
16
21
|
|
|
17
22
|
create(input: CreateRequirementInput): { requirementId: string; version: RequirementVersion } {
|
|
18
23
|
const requirementId = `${slug(input.title)}-${randomUUID().slice(0, 8)}`
|
|
19
24
|
const markdown = initialSpec(input.title, input.rawRequirement, input.sources)
|
|
20
25
|
const path = this.specPath(requirementId)
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
26
|
+
try {
|
|
27
|
+
mkdirSync(dirname(path), { recursive: true })
|
|
28
|
+
writeFileSync(path, markdown, 'utf8')
|
|
29
|
+
const commit = this.commit(requirementId, input.participant, 'Create requirement')
|
|
30
|
+
const version = this.rememberCommittedVersion(requirementId, commit, markdown, input.participant, 'Create requirement')
|
|
31
|
+
return { requirementId, version }
|
|
32
|
+
}
|
|
33
|
+
catch (error) {
|
|
34
|
+
this.git(['reset', '--', this.relativeSpecPath(requirementId)], true)
|
|
35
|
+
rmSync(dirname(path), { recursive: true, force: true })
|
|
36
|
+
throw error
|
|
37
|
+
}
|
|
25
38
|
}
|
|
26
39
|
|
|
27
40
|
save(input: SaveVersionInput): RequirementVersion {
|
|
@@ -31,24 +44,34 @@ export class GitRequirementStore {
|
|
|
31
44
|
if (onDisk !== this.read(input.requirementId, current).markdown) throw new Error('spec has external uncommitted changes')
|
|
32
45
|
if (input.summary.trim() === '') throw new Error('change summary is required')
|
|
33
46
|
if (input.markdown.length > 2_000_000) throw new Error('spec exceeds 2 MB')
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
47
|
+
if (input.markdown === onDisk) throw new Error('no changes to save')
|
|
48
|
+
const relativePath = this.relativeSpecPath(input.requirementId)
|
|
49
|
+
try {
|
|
50
|
+
writeFileSync(this.specPath(input.requirementId), input.markdown, 'utf8')
|
|
51
|
+
this.git(['add', relativePath])
|
|
52
|
+
const commit = this.commitStaged(input.participant, input.summary.trim())
|
|
53
|
+
return this.rememberCommittedVersion(input.requirementId, commit, input.markdown, input.participant, input.summary.trim(), current)
|
|
54
|
+
}
|
|
55
|
+
catch (error) {
|
|
56
|
+
writeFileSync(this.specPath(input.requirementId), onDisk, 'utf8')
|
|
57
|
+
this.git(['reset', '--', relativePath], true)
|
|
58
|
+
throw error
|
|
59
|
+
}
|
|
40
60
|
}
|
|
41
61
|
|
|
42
62
|
read(requirementId: string, commit?: string): RequirementVersion {
|
|
43
63
|
assertRequirementId(requirementId)
|
|
44
64
|
const resolved = commit ?? this.head(requirementId)
|
|
65
|
+
const cacheKey = `${requirementId}:${resolved}`
|
|
66
|
+
const cached = this.versionCache.get(cacheKey)
|
|
67
|
+
if (cached !== undefined) return structuredClone(cached)
|
|
45
68
|
const markdown = this.gitText(['show', `${resolved}:${this.relativeSpecPath(requirementId)}`])
|
|
46
69
|
const fields = this.gitText(['show', '-s', '--format=%H%x1f%P%x1f%at%x1f%an%x1f%ae%x1f%B', resolved]).split('\x1f')
|
|
47
70
|
const [sha = resolved, parents = '', seconds = '0', nickname = 'unknown', email = '', ...bodyParts] = fields
|
|
48
71
|
const body = bodyParts.join('\x1f').trim()
|
|
49
72
|
const role = /DSH-Role:\s*(product|engineering)/.exec(body)?.[1] as ParticipantSnapshot['role'] | undefined
|
|
50
73
|
const summary = body.split('\n')[0] ?? 'Saved version'
|
|
51
|
-
|
|
74
|
+
const version: RequirementVersion = {
|
|
52
75
|
commit: sha,
|
|
53
76
|
...(parents.split(' ')[0] ? { parentCommit: parents.split(' ')[0] } : {}),
|
|
54
77
|
markdown,
|
|
@@ -56,23 +79,29 @@ export class GitRequirementStore {
|
|
|
56
79
|
summary,
|
|
57
80
|
createdAt: Number(seconds) * 1000,
|
|
58
81
|
}
|
|
82
|
+
this.versionCache.set(cacheKey, version)
|
|
83
|
+
return structuredClone(version)
|
|
59
84
|
}
|
|
60
85
|
|
|
61
86
|
history(requirementId: string): Array<Omit<RequirementVersion, 'markdown'>> {
|
|
62
87
|
assertRequirementId(requirementId)
|
|
88
|
+
const cached = this.historyCache.get(requirementId)
|
|
89
|
+
if (cached !== undefined) return structuredClone(cached)
|
|
63
90
|
const output = this.gitText(['log', '--format=%H%x1f%P%x1f%at%x1f%an%x1f%ae%x1f%B%x1e', '--', this.relativeSpecPath(requirementId)])
|
|
64
|
-
|
|
91
|
+
const history: Array<Omit<RequirementVersion, 'markdown'>> = output.split('\x1e').map(row => row.trim()).filter(Boolean).map(row => {
|
|
65
92
|
const [commit = '', parents = '', seconds = '0', nickname = 'unknown', email = '', ...bodyParts] = row.split('\x1f')
|
|
66
93
|
const body = bodyParts.join('\x1f').trim()
|
|
67
94
|
const role = /DSH-Role:\s*(product|engineering)/.exec(body)?.[1] as ParticipantSnapshot['role'] | undefined
|
|
68
95
|
return {
|
|
69
96
|
commit,
|
|
70
97
|
...(parents.split(' ')[0] ? { parentCommit: parents.split(' ')[0] } : {}),
|
|
71
|
-
author: { participantId: email.replace(/@dsh\.local$/, '') || 'unknown', nickname, role: role ?? 'product', kind: 'human' },
|
|
98
|
+
author: { participantId: email.replace(/@dsh\.local$/, '') || 'unknown', nickname, role: role ?? 'product', kind: 'human' as const },
|
|
72
99
|
summary: body.split('\n')[0] ?? 'Saved version',
|
|
73
100
|
createdAt: Number(seconds) * 1000,
|
|
74
101
|
}
|
|
75
102
|
})
|
|
103
|
+
this.historyCache.set(requirementId, history)
|
|
104
|
+
return structuredClone(history)
|
|
76
105
|
}
|
|
77
106
|
|
|
78
107
|
diff(requirementId: string, baseCommit: string, headCommit?: string): string {
|
|
@@ -80,16 +109,41 @@ export class GitRequirementStore {
|
|
|
80
109
|
return this.gitText(['diff', baseCommit, headCommit ?? this.head(requirementId), '--', this.relativeSpecPath(requirementId)])
|
|
81
110
|
}
|
|
82
111
|
|
|
112
|
+
commitUrl(commit: string): string | undefined {
|
|
113
|
+
if (!/^[a-f0-9]{40}$/.test(commit)) return undefined
|
|
114
|
+
if (this.commitBaseUrl !== undefined) return this.commitBaseUrl === null ? undefined : `${this.commitBaseUrl}/commit/${commit}`
|
|
115
|
+
let origin: string
|
|
116
|
+
try { origin = this.gitText(['config', '--get', 'remote.origin.url']).trim() } catch { this.commitBaseUrl = null; return undefined }
|
|
117
|
+
if (origin === '') { this.commitBaseUrl = null; return undefined }
|
|
118
|
+
const scp = /^git@([^:]+):(.+)$/.exec(origin)
|
|
119
|
+
const normalized = scp ? `https://${scp[1]}/${scp[2]}` : origin.replace(/^ssh:\/\/git@/, 'https://')
|
|
120
|
+
if (!/^https?:\/\//.test(normalized)) { this.commitBaseUrl = null; return undefined }
|
|
121
|
+
try {
|
|
122
|
+
const url = new URL(normalized)
|
|
123
|
+
url.username = ''; url.password = ''
|
|
124
|
+
this.commitBaseUrl = url.toString().replace(/\.git$/, '').replace(/\/$/, '')
|
|
125
|
+
}
|
|
126
|
+
catch { this.commitBaseUrl = null; return undefined }
|
|
127
|
+
return `${this.commitBaseUrl}/commit/${commit}`
|
|
128
|
+
}
|
|
129
|
+
|
|
83
130
|
remove(requirementId: string, participant: ParticipantSnapshot): void {
|
|
84
131
|
assertRequirementId(requirementId)
|
|
85
132
|
if (!existsSync(this.specPath(requirementId))) throw new Error('requirement spec not found')
|
|
86
|
-
|
|
87
|
-
this.commitStaged(participant, 'Delete requirement')
|
|
133
|
+
const relativeDirectory = `requirements/${requirementId}`
|
|
134
|
+
try { this.git(['rm', '-r', relativeDirectory]); this.commitStaged(participant, 'Delete requirement') }
|
|
135
|
+
catch (error) { this.git(['restore', '--staged', '--worktree', relativeDirectory], true); throw error }
|
|
136
|
+
this.headCache.delete(requirementId); this.historyCache.delete(requirementId)
|
|
137
|
+
for (const key of this.versionCache.keys()) if (key.startsWith(`${requirementId}:`)) this.versionCache.delete(key)
|
|
88
138
|
}
|
|
89
139
|
|
|
90
140
|
head(requirementId: string): string {
|
|
91
141
|
assertRequirementId(requirementId)
|
|
92
|
-
|
|
142
|
+
const cached = this.headCache.get(requirementId)
|
|
143
|
+
if (cached !== undefined) return cached
|
|
144
|
+
const resolved = this.gitText(['log', '-1', '--format=%H', '--', this.relativeSpecPath(requirementId)]).trim()
|
|
145
|
+
this.headCache.set(requirementId, resolved)
|
|
146
|
+
return resolved
|
|
93
147
|
}
|
|
94
148
|
|
|
95
149
|
private commit(requirementId: string, participant: ParticipantSnapshot, summary: string): string {
|
|
@@ -105,10 +159,20 @@ export class GitRequirementStore {
|
|
|
105
159
|
GIT_COMMITTER_NAME: participant.nickname,
|
|
106
160
|
GIT_COMMITTER_EMAIL: `${participant.participantId}@dsh.local`,
|
|
107
161
|
}
|
|
108
|
-
execFileSync('git', ['commit', '-m', summary, '-m', `DSH-Role: ${participant.role}`], { cwd: this.root, env, stdio: 'pipe' })
|
|
162
|
+
execFileSync('git', ['-c', 'commit.gpgsign=false', '-c', 'core.hooksPath=/dev/null', 'commit', '--no-verify', '-m', summary, '-m', `DSH-Role: ${participant.role}`], { cwd: this.root, env, stdio: 'pipe' })
|
|
109
163
|
return this.gitText(['rev-parse', 'HEAD']).trim()
|
|
110
164
|
}
|
|
111
165
|
|
|
166
|
+
private rememberCommittedVersion(requirementId: string, commit: string, markdown: string, participant: ParticipantSnapshot, summary: string, parentCommit?: string): RequirementVersion {
|
|
167
|
+
const version: RequirementVersion = { commit, ...(parentCommit ? { parentCommit } : {}), markdown, author: participant, summary, createdAt: Date.now() }
|
|
168
|
+
this.headCache.set(requirementId, commit)
|
|
169
|
+
this.versionCache.set(`${requirementId}:${commit}`, version)
|
|
170
|
+
const metadata = withoutMarkdown(version)
|
|
171
|
+
const history = this.historyCache.get(requirementId)
|
|
172
|
+
this.historyCache.set(requirementId, history === undefined ? [metadata] : [metadata, ...history])
|
|
173
|
+
return structuredClone(version)
|
|
174
|
+
}
|
|
175
|
+
|
|
112
176
|
private ensureRepository(): void {
|
|
113
177
|
mkdirSync(this.root, { recursive: true, mode: 0o700 })
|
|
114
178
|
if (!existsSync(join(this.root, '.git'))) execFileSync('git', ['init'], { cwd: this.root, stdio: 'pipe' })
|
|
@@ -122,6 +186,11 @@ export class GitRequirementStore {
|
|
|
122
186
|
}
|
|
123
187
|
}
|
|
124
188
|
|
|
189
|
+
function withoutMarkdown(version: RequirementVersion): Omit<RequirementVersion, 'markdown'> {
|
|
190
|
+
const { markdown: _markdown, ...metadata } = version
|
|
191
|
+
return metadata
|
|
192
|
+
}
|
|
193
|
+
|
|
125
194
|
function slug(title: string): string {
|
|
126
195
|
const value = title.toLowerCase().trim().replace(/[^a-z0-9\u4e00-\u9fff]+/g, '-').replace(/^-|-$/g, '').slice(0, 48)
|
|
127
196
|
return value || 'requirement'
|
package/src/index.ts
CHANGED
|
@@ -55,7 +55,7 @@ export function apply(ctx: Context, config: Config = {}): void {
|
|
|
55
55
|
const dataRoot = config.dataRoot ?? join(homedir(), '.dsh', 'spec-collab')
|
|
56
56
|
const contexts = new ReviewContextCatalog(config)
|
|
57
57
|
const prompts = resolveReviewPrompts(config.prompts)
|
|
58
|
-
const engine = new CollaborationEngine(join(dataRoot, 'collaboration-
|
|
58
|
+
const engine = new CollaborationEngine(join(dataRoot, 'collaboration-v3.json'), new GitRequirementStore(config.repositoryPath ?? join(dataRoot, 'repository')), { legacyPath: join(dataRoot, 'collaboration-v2.json') })
|
|
59
59
|
const coordinator = new DshReviewCoordinator(ctx.apiProxy, contexts, prompts)
|
|
60
60
|
engine.setCoordinator(coordinator)
|
|
61
61
|
ctx.effect(() => { const disposers = makeRoutes(engine, coordinator).map(route => ctx.webServer.register(route)); return () => { for (const dispose of disposers) dispose() } }, 'spec-collab: routes')
|
package/src/protocol.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
export const API_PREFIX = '/api/spec-collab'
|
|
2
|
-
export const SCHEMA_VERSION =
|
|
2
|
+
export const SCHEMA_VERSION = 3 as const
|
|
3
3
|
|
|
4
4
|
export type ParticipantRole = 'product' | 'engineering'
|
|
5
5
|
export type ParticipantKind = 'human' | 'ai'
|
|
@@ -13,6 +13,9 @@ export type CommentResolution = 'written-back' | 'decision' | 'rejected' | 'open
|
|
|
13
13
|
export type ConfirmationScope = 'version' | 'section' | 'acceptance-criterion' | 'decision'
|
|
14
14
|
export type ActionItemStatus = 'pending' | 'handled' | 'invalidated' | 'cancelled'
|
|
15
15
|
export type AiTaskStatus = 'queued' | 'running' | 'completed' | 'failed'
|
|
16
|
+
export type InsightImportance = 'unknown' | 'want' | 'important' | 'critical'
|
|
17
|
+
export type InsightTargetType = 'requirement' | 'section' | 'acceptance-criterion'
|
|
18
|
+
export type CollaborationEventType = 'state.synced' | 'comment.changed' | 'assignment.changed' | 'mention.created' | 'notification.changed' | 'ai.status' | 'metrics.changed'
|
|
16
19
|
|
|
17
20
|
export interface ParticipantSnapshot { participantId: string; nickname: string; role: ParticipantRole; kind: ParticipantKind; sessionId?: string }
|
|
18
21
|
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' }
|
|
@@ -28,10 +31,11 @@ export interface ReviewItem {
|
|
|
28
31
|
response?: { participant: ParticipantSnapshot; disposition: 'context' | 'evidence' | 'accept' | 'accept-modified' | 'reject' | 'to-verify' | 'joint-review'; body: string; createdAt: number }
|
|
29
32
|
createdAt: number; updatedAt: number
|
|
30
33
|
}
|
|
31
|
-
export interface CommentReply { id: string; author: ParticipantSnapshot; body: string; createdAt: number }
|
|
34
|
+
export interface CommentReply { id: string; author: ParticipantSnapshot; body: string; mentions: string[]; createdAt: number }
|
|
35
|
+
export interface TextAnchor { heading?: string; quote: string; prefix?: string; suffix?: string }
|
|
32
36
|
export interface CommentThread {
|
|
33
|
-
id: string; requirementId: string; commit: string;
|
|
34
|
-
author: ParticipantSnapshot; body: string; replies: CommentReply[]; aiStatus: AiTaskStatus; aiSessionId?: string
|
|
37
|
+
id: string; requirementId: string; commit: string; scope: 'page' | 'inline'; anchor?: TextAnchor
|
|
38
|
+
author: ParticipantSnapshot; body: string; mentions: string[]; replies: CommentReply[]; aiStatus: AiTaskStatus; aiSessionId?: string
|
|
35
39
|
status: 'open' | 'resolved' | 'orphaned' | 'invalidated'; resolution?: CommentResolution; createdAt: number; updatedAt: number
|
|
36
40
|
}
|
|
37
41
|
export interface CandidatePatch {
|
|
@@ -41,7 +45,7 @@ export interface CandidatePatch {
|
|
|
41
45
|
}
|
|
42
46
|
export interface Decision {
|
|
43
47
|
id: string; requirementId: string; commit: string; question: string; options: string[]; decision: string; rationale: string
|
|
44
|
-
confirmer: ParticipantSnapshot; affectedSections: string[]; affectedAcceptanceIds: string[]; sourceAnchors?:
|
|
48
|
+
confirmer: ParticipantSnapshot; affectedSections: string[]; affectedAcceptanceIds: string[]; sourceAnchors?: TextAnchor[]; createdAt: number; status: 'active' | 'invalidated'
|
|
45
49
|
}
|
|
46
50
|
export interface Confirmation { id: string; requirementId: string; commit: string; role: ParticipantRole; participant: ParticipantSnapshot; scope: ConfirmationScope; scopeId?: string; status: 'active' | 'invalidated'; createdAt: number }
|
|
47
51
|
export interface ActionItem {
|
|
@@ -50,44 +54,91 @@ export interface ActionItem {
|
|
|
50
54
|
status: ActionItemStatus; dueStage: RequirementStage; createdAt: number; updatedAt: number
|
|
51
55
|
}
|
|
52
56
|
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 }
|
|
57
|
+
export interface AiStageConversation { stage: RequirementStage; stageCycle: number; sessionId: string; createdAt: number; updatedAt: number }
|
|
53
58
|
export interface ReadinessCheck { key: 'goal' | 'acceptance' | 'scope' | 'semantics' | 'evidence' | 'test-constraints'; passed: boolean; reasons: string[] }
|
|
54
59
|
export interface ReadyPackage { requirementId: string; commit: string; packageHash: string; generatedAt: number; generatedBy: ParticipantSnapshot; markdown: string }
|
|
55
60
|
export interface ReviewWorkspaceSummary { workspaceId: string; title: string; path: string }
|
|
61
|
+
export interface Company { id: string; name: string; externalRef?: string; createdAt: number; updatedAt: number }
|
|
62
|
+
export interface Customer { id: string; displayName: string; companyId?: string; externalRef?: string; createdAt: number; updatedAt: number }
|
|
63
|
+
export interface FeedbackSource {
|
|
64
|
+
id: string; kind: 'text' | 'url' | 'csv' | 'markdown'; label: string; url?: string; externalRef?: string
|
|
65
|
+
accessStatus: 'available' | 'unverified' | 'missing'; createdAt: number; updatedAt: number
|
|
66
|
+
}
|
|
67
|
+
export interface Insight {
|
|
68
|
+
id: string; sourceId: string; customerId?: string; companyId?: string; title: string; body: string
|
|
69
|
+
importance: InsightImportance; capturedAt: number; dedupeHash: string; createdBy: ParticipantSnapshot; createdAt: number; updatedAt: number
|
|
70
|
+
}
|
|
71
|
+
export interface InsightLink { id: string; insightId: string; requirementId: string; targetType: InsightTargetType; targetId?: string; createdBy: ParticipantSnapshot; createdAt: number }
|
|
72
|
+
export interface Notification {
|
|
73
|
+
id: string; recipientParticipantId: string; kind: 'mention' | 'reply' | 'assignment' | 'status-change'; requirementId: string
|
|
74
|
+
objectType: 'comment' | 'action' | 'requirement'; objectId: string; message: string; deepLink: string; createdAt: number; readAt?: number
|
|
75
|
+
}
|
|
76
|
+
export interface RequirementMetrics {
|
|
77
|
+
openReviewCount: number; openCommentCount: number; pendingActionCount: number; activeDecisionCount: number; riskCount: number
|
|
78
|
+
insightCount: number; customerImportanceScore: number; customerCount: number; companyCount: number; anonymousInsightCount: number
|
|
79
|
+
}
|
|
80
|
+
export interface RequirementSummary {
|
|
81
|
+
id: string; title: string; stage: RequirementStage; currentCommit: string; workspaceId?: string; archivedAt?: number; updatedAt: number
|
|
82
|
+
metrics: RequirementMetrics; participantIds: string[]
|
|
83
|
+
}
|
|
84
|
+
export interface StructuredDiffLine { type: 'context' | 'added' | 'removed'; oldLine?: number; newLine?: number; text: string }
|
|
85
|
+
export interface StructuredDiffHunk { id: string; oldStart: number; newStart: number; lines: StructuredDiffLine[]; collapsedBefore: number; collapsedAfter: number; collapsedBeforeLines: StructuredDiffLine[]; collapsedAfterLines: StructuredDiffLine[] }
|
|
86
|
+
export interface StructuredDiff { baseLabel: string; headLabel: string; added: number; removed: number; hunks: StructuredDiffHunk[] }
|
|
87
|
+
export interface DraftRecord { requirementId: string; participantId: string; baseCommit: string; markdown: string; summary: string; updatedAt: number }
|
|
88
|
+
export interface CollaborationEvent { types: CollaborationEventType[]; revision: number; requirementId?: string; objectId?: string }
|
|
56
89
|
export interface RequirementRecord {
|
|
57
|
-
id: string; title: string; stage: RequirementStage; currentCommit: string; productConfirmedCommit?: string; jointConfirmedCommit?: string
|
|
90
|
+
id: string; title: string; stage: RequirementStage; stageCycle: number; currentCommit: string; productConfirmedCommit?: string; jointConfirmedCommit?: string
|
|
58
91
|
workspaceId?: string
|
|
59
92
|
archivedAt?: number
|
|
60
93
|
sources: SourceReference[]; reviewItems: ReviewItem[]; comments: CommentThread[]; patches: CandidatePatch[]; decisions: Decision[]
|
|
61
|
-
confirmations: Confirmation[]; actionItems: ActionItem[]; aiRuns: AiReviewRun[]; readyPackage?: ReadyPackage; createdAt: number; updatedAt: number
|
|
94
|
+
confirmations: Confirmation[]; actionItems: ActionItem[]; aiRuns: AiReviewRun[]; aiConversations: AiStageConversation[]; readyPackage?: ReadyPackage; createdAt: number; updatedAt: number
|
|
95
|
+
}
|
|
96
|
+
export interface CollaborationState {
|
|
97
|
+
schemaVersion: typeof SCHEMA_VERSION; revision: number; participants: ParticipantSnapshot[]; requirements: RequirementRecord[]
|
|
98
|
+
companies: Company[]; customers: Customer[]; feedbackSources: FeedbackSource[]; insights: Insight[]; insightLinks: InsightLink[]; notifications: Notification[]
|
|
62
99
|
}
|
|
63
|
-
export interface
|
|
64
|
-
export interface RequirementView extends RequirementRecord { version: RequirementVersion; history: Array<Omit<RequirementVersion, 'markdown'>>; readiness: ReadinessCheck[] }
|
|
100
|
+
export interface RequirementView extends RequirementRecord { version: RequirementVersion; history: Array<Omit<RequirementVersion, 'markdown'>>; readiness: ReadinessCheck[]; metrics: RequirementMetrics; commitUrl?: string }
|
|
65
101
|
export interface SaveConflict {
|
|
66
102
|
requirementId: string; baseCommit: string; currentCommit: string; baseMarkdown: string; currentMarkdown: string; draftMarkdown: string
|
|
67
103
|
baseToCurrentDiff: string; baseToDraftDiff: string
|
|
68
104
|
}
|
|
69
105
|
export type MyItemCategory = 'awaiting-my-response' | 'awaiting-my-confirmation' | 'initiated-by-me' | 'possibly-mine-by-ip'
|
|
70
|
-
export interface MyActionItem extends ActionItem { category: MyItemCategory; requirementTitle: string; target: { tab: 'review' | 'discussion' | 'patches' | 'decisions' | 'ready'; objectId: string } }
|
|
106
|
+
export interface MyActionItem extends ActionItem { category: MyItemCategory; requirementTitle: string; objectTitle: string; target: { tab: 'review' | 'discussion' | 'patches' | 'decisions' | 'ready'; objectId: string } }
|
|
71
107
|
|
|
72
108
|
export type CollaborationAction =
|
|
73
109
|
| { kind: 'requirement.create'; participant: ParticipantSnapshot; title: string; rawRequirement: string; sources: SourceReference[]; workspaceId: string }
|
|
74
110
|
| { kind: 'requirement.bind-workspace'; participant: ParticipantSnapshot; requirementId: string; workspaceId: string }
|
|
75
111
|
| { kind: 'requirement.rename'; participant: ParticipantSnapshot; requirementId: string; title: string }
|
|
76
112
|
| { kind: 'requirement.archive'; participant: ParticipantSnapshot; requirementId: string; archived: boolean }
|
|
113
|
+
| { kind: 'requirement.unarchive'; participant: ParticipantSnapshot; requirementId: string }
|
|
77
114
|
| { kind: 'requirement.delete'; participant: ParticipantSnapshot; requirementId: string }
|
|
78
115
|
| { kind: 'version.save'; participant: ParticipantSnapshot; requirementId: string; baseCommit: string; markdown: string; summary: string }
|
|
116
|
+
| { kind: 'version.restore'; participant: ParticipantSnapshot; requirementId: string; commit: string; summary: string }
|
|
79
117
|
| { kind: 'review.request'; participant: ParticipantSnapshot; requirementId: string; reviewKind: ReviewKind }
|
|
80
118
|
| { kind: 'review.respond'; participant: ParticipantSnapshot; requirementId: string; reviewItemId: string; disposition: NonNullable<ReviewItem['response']>['disposition']; body: string }
|
|
81
|
-
| { kind: 'comment.create'; participant: ParticipantSnapshot; requirementId: string; commit: string;
|
|
82
|
-
| { kind: 'comment.reply'; participant: ParticipantSnapshot; requirementId: string; commentId: string; body: string }
|
|
119
|
+
| { kind: 'comment.create'; participant: ParticipantSnapshot; requirementId: string; commit: string; scope?: 'page' | 'inline'; anchor?: TextAnchor; body: string; mentions?: string[] }
|
|
120
|
+
| { kind: 'comment.reply'; participant: ParticipantSnapshot; requirementId: string; commentId: string; body: string; mentions?: string[] }
|
|
83
121
|
| { kind: 'comment.resolve'; participant: ParticipantSnapshot; requirementId: string; commentId: string; resolution: CommentResolution }
|
|
122
|
+
| { kind: 'comment.reopen'; participant: ParticipantSnapshot; requirementId: string; commentId: string }
|
|
84
123
|
| { kind: 'patch.accept'; participant: ParticipantSnapshot; requirementId: string; patchId: string; summary: string }
|
|
85
124
|
| { kind: 'patch.reject'; participant: ParticipantSnapshot; requirementId: string; patchId: string }
|
|
86
|
-
| { kind: 'decision.create'; participant: ParticipantSnapshot; requirementId: string; question: string; options: string[]; decision: string; rationale: string; affectedSections: string[]; affectedAcceptanceIds: string[]; sourceAnchors?:
|
|
125
|
+
| { kind: 'decision.create'; participant: ParticipantSnapshot; requirementId: string; question: string; options: string[]; decision: string; rationale: string; affectedSections: string[]; affectedAcceptanceIds: string[]; sourceAnchors?: TextAnchor[] }
|
|
87
126
|
| { kind: 'confirmation.create'; participant: ParticipantSnapshot; requirementId: string; role: ParticipantRole; scope: ConfirmationScope; scopeId?: string }
|
|
88
127
|
| { kind: 'stage.advance'; participant: ParticipantSnapshot; requirementId: string }
|
|
89
128
|
| { kind: 'ready.generate'; participant: ParticipantSnapshot; requirementId: string }
|
|
90
129
|
| { kind: 'downstream.return'; participant: ParticipantSnapshot; requirementId: string; summary: string; evidence: ReviewEvidence[]; affectedSections: string[]; affectedAcceptanceIds: string[] }
|
|
130
|
+
| { kind: 'participant.register'; participant: ParticipantSnapshot; requirementId: string }
|
|
131
|
+
| { kind: 'action.assign'; participant: ParticipantSnapshot; requirementId: string; actionItemId: string; assigneeRole: ParticipantRole; assigneeParticipantId?: string; dueStage?: RequirementStage }
|
|
132
|
+
| { kind: 'notification.mark-read'; participant: ParticipantSnapshot; requirementId: string; notificationIds: string[] }
|
|
133
|
+
| { kind: 'source.upsert'; participant: ParticipantSnapshot; requirementId: string; source: Omit<FeedbackSource, 'createdAt' | 'updatedAt'> }
|
|
134
|
+
| { kind: 'company.upsert'; participant: ParticipantSnapshot; requirementId: string; company: Omit<Company, 'createdAt' | 'updatedAt'> }
|
|
135
|
+
| { kind: 'customer.upsert'; participant: ParticipantSnapshot; requirementId: string; customer: Omit<Customer, 'createdAt' | 'updatedAt'> }
|
|
136
|
+
| { kind: 'insight.create'; participant: ParticipantSnapshot; requirementId: string; insight: Omit<Insight, 'dedupeHash' | 'createdBy' | 'createdAt' | 'updatedAt'>; links?: Array<Pick<InsightLink, 'requirementId' | 'targetType' | 'targetId'>> }
|
|
137
|
+
| { kind: 'insight.update'; participant: ParticipantSnapshot; requirementId: string; insightId: string; changes: Partial<Pick<Insight, 'sourceId' | 'customerId' | 'companyId' | 'title' | 'body' | 'importance' | 'capturedAt'>> }
|
|
138
|
+
| { kind: 'insight.delete'; participant: ParticipantSnapshot; requirementId: string; insightId: string }
|
|
139
|
+
| { kind: 'insight.link'; participant: ParticipantSnapshot; requirementId: string; insightId: string; link: Pick<InsightLink, 'requirementId' | 'targetType' | 'targetId'> }
|
|
140
|
+
| { kind: 'insight.unlink'; participant: ParticipantSnapshot; requirementId: string; linkId: string }
|
|
141
|
+
| { kind: 'insight.import'; participant: ParticipantSnapshot; requirementId: string; source?: Omit<FeedbackSource, 'createdAt' | 'updatedAt'>; sources?: Array<Omit<FeedbackSource, 'createdAt' | 'updatedAt'>>; companies?: Array<Omit<Company, 'createdAt' | 'updatedAt'>>; customers?: Array<Omit<Customer, 'createdAt' | 'updatedAt'>>; rows: Array<Omit<Insight, 'dedupeHash' | 'createdBy' | 'createdAt' | 'updatedAt'>>; links?: Array<{ insightId: string } & Pick<InsightLink, 'requirementId' | 'targetType' | 'targetId'>> }
|
|
91
142
|
|
|
92
143
|
export interface ActionEnvelope { requestId: string; action: CollaborationAction }
|
|
93
144
|
export type ActionResult = { ok: true; revision: number; requirement: RequirementView; deletedRequirementId?: string } | { ok: false; revision: number; error: string; conflict?: SaveConflict }
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { ParticipantRole, ReadinessCheck, RequirementRecord, ReviewKind } from './protocol.ts'
|
|
2
|
+
|
|
3
|
+
export function hasCompletedCurrentReview(record: Pick<RequirementRecord, 'aiRuns' | 'currentCommit'>, kind: ReviewKind): boolean {
|
|
4
|
+
// A failed retry does not erase an earlier completed review of this exact body.
|
|
5
|
+
return record.aiRuns.some(run => run.commit === record.currentCommit && run.kind === kind && run.status === 'completed')
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export function hasVersionConfirmation(record: Pick<RequirementRecord, 'confirmations' | 'currentCommit'>, role: ParticipantRole): boolean {
|
|
9
|
+
return record.confirmations.some(item => item.commit === record.currentCommit && item.role === role && item.scope === 'version' && item.status === 'active')
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/** Shared by workflow guidance and the authoritative Ready write. Checks must come from the current Git body. */
|
|
13
|
+
export function readyAdmission(record: RequirementRecord, checks: ReadinessCheck[]) {
|
|
14
|
+
const activeRun = record.aiRuns.slice().reverse().find(run => run.commit === record.currentCommit && (run.status === 'queued' || run.status === 'running'))
|
|
15
|
+
const engineeringReviewed = hasCompletedCurrentReview(record, 'engineering-precheck')
|
|
16
|
+
const pendingPatches = record.patches.filter(item => item.baseCommit === record.currentCommit && item.status === 'pending')
|
|
17
|
+
const failedChecks = checks.filter(check => !check.passed)
|
|
18
|
+
const productConfirmed = hasVersionConfirmation(record, 'product')
|
|
19
|
+
const engineeringConfirmed = hasVersionConfirmation(record, 'engineering')
|
|
20
|
+
const error = record.stage !== 'joint-review' ? 'readiness gate is not satisfied'
|
|
21
|
+
: !record.workspaceId?.trim() ? 'review workspace is required'
|
|
22
|
+
: activeRun ? 'current version review is still running'
|
|
23
|
+
: !engineeringReviewed ? 'engineering precheck is required for the current version'
|
|
24
|
+
: pendingPatches.length > 0 ? 'current version has pending patches'
|
|
25
|
+
: failedChecks.length > 0 ? 'readiness gate is not satisfied'
|
|
26
|
+
: !productConfirmed || !engineeringConfirmed ? 'current version needs product and engineering confirmation'
|
|
27
|
+
: undefined
|
|
28
|
+
return { activeRun, engineeringReviewed, pendingPatches, failedChecks, productConfirmed, engineeringConfirmed, error }
|
|
29
|
+
}
|
package/src/review-runtime.ts
CHANGED
|
@@ -11,6 +11,7 @@ const FOLLOW_UP_METADATA = '\n\n<!-- dsh-spec-collab-follow-up:'
|
|
|
11
11
|
|
|
12
12
|
export class DshReviewCoordinator implements AiCoordinator {
|
|
13
13
|
private readonly prompts: ResolvedReviewPrompts
|
|
14
|
+
private readonly stageSessions = new Map<string, Promise<string>>()
|
|
14
15
|
constructor(private readonly api: ApiProxy, private readonly contexts = new ReviewContextCatalog(), prompts: ReviewPromptConfig = {}) {
|
|
15
16
|
this.prompts = resolveReviewPrompts(prompts)
|
|
16
17
|
}
|
|
@@ -22,17 +23,21 @@ export class DshReviewCoordinator implements AiCoordinator {
|
|
|
22
23
|
async assertWorkspaceAvailable(workspaceId: string): Promise<void> {
|
|
23
24
|
await this.resolveWorkspace(workspaceId)
|
|
24
25
|
}
|
|
25
|
-
async requestReview(input: { requirement: RequirementView; run: AiReviewRun }): Promise<string> {
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
26
|
+
async requestReview(input: { requirement: RequirementView; run: AiReviewRun; sessionId?: string }): Promise<string> {
|
|
27
|
+
return this.inStageSession(input.requirement, input.sessionId, reviewContinuationPrompt(input.requirement, input.run, this.prompts), async () => {
|
|
28
|
+
const context = this.contexts.resolve(input.requirement.workspaceId)
|
|
29
|
+
const workspace = await this.resolveWorkspace(context.workspaceId)
|
|
30
|
+
const snapshot = await readWorkspaceSnapshot(workspace.path, context.documentPaths)
|
|
31
|
+
return this.launch(`Spec ${input.run.kind}: ${input.requirement.title}`, reviewPrompt(input.requirement, input.run, context, workspace, snapshot, this.prompts), context.workspaceId, context.agentPreset)
|
|
32
|
+
})
|
|
30
33
|
}
|
|
31
|
-
async requestCommentReply(input: { requirement: RequirementView; comment: CommentThread }): Promise<string> {
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
34
|
+
async requestCommentReply(input: { requirement: RequirementView; comment: CommentThread; sessionId?: string }): Promise<string> {
|
|
35
|
+
return this.inStageSession(input.requirement, input.sessionId, commentContinuationPrompt(input.requirement, input.comment, this.prompts), async () => {
|
|
36
|
+
const context = this.contexts.resolve(input.requirement.workspaceId)
|
|
37
|
+
const workspace = await this.resolveWorkspace(context.workspaceId)
|
|
38
|
+
const snapshot = await readWorkspaceSnapshot(workspace.path, context.documentPaths)
|
|
39
|
+
return this.launch(`Spec ${input.requirement.stage}: ${input.requirement.title}`, commentPrompt(input.requirement, input.comment, context, workspace, snapshot, this.prompts), context.workspaceId, context.agentPreset)
|
|
40
|
+
})
|
|
36
41
|
}
|
|
37
42
|
async conversation(sessionId: string): Promise<Array<{ role: 'user' | 'assistant'; text: string }>> {
|
|
38
43
|
const history = await this.api.sessions.history(request({ sessionId: sessionId as never }))
|
|
@@ -65,6 +70,22 @@ export class DshReviewCoordinator implements AiCoordinator {
|
|
|
65
70
|
const prompted = await this.api.sessions.prompt(request({ sessionId: sessionId as never, mode: 'queue' as const, content: [{ type: 'text' as const, text: promptText }] }))
|
|
66
71
|
if (!prompted.result.ok) throw failure(prompted.result.error)
|
|
67
72
|
}
|
|
73
|
+
private async inStageSession(requirement: RequirementView, existingSessionId: string | undefined, continuation: string, launch: () => Promise<string>): Promise<string> {
|
|
74
|
+
const key = `${requirement.id}:${requirement.stage}:${requirement.stageCycle}`
|
|
75
|
+
if (existingSessionId !== undefined) {
|
|
76
|
+
this.rememberStageSession(key, Promise.resolve(existingSessionId))
|
|
77
|
+
await this.promptExisting(existingSessionId, continuation); return existingSessionId
|
|
78
|
+
}
|
|
79
|
+
const pending = this.stageSessions.get(key)
|
|
80
|
+
if (pending !== undefined) { const sessionId = await pending; await this.promptExisting(sessionId, continuation); return sessionId }
|
|
81
|
+
const created = launch(); this.rememberStageSession(key, created)
|
|
82
|
+
try { return await created } catch (error) { if (this.stageSessions.get(key) === created) this.stageSessions.delete(key); throw error }
|
|
83
|
+
}
|
|
84
|
+
private rememberStageSession(key: string, session: Promise<string>): void { this.stageSessions.delete(key); this.stageSessions.set(key, session); while (this.stageSessions.size > 100) { const oldest = this.stageSessions.keys().next().value as string | undefined; if (oldest === undefined) break; this.stageSessions.delete(oldest) } }
|
|
85
|
+
private async promptExisting(sessionId: string, promptText: string): Promise<void> {
|
|
86
|
+
const prompted = await this.api.sessions.prompt(request({ sessionId: sessionId as never, mode: 'queue' as const, content: [{ type: 'text' as const, text: promptText }] }))
|
|
87
|
+
if (!prompted.result.ok) throw failure(prompted.result.error)
|
|
88
|
+
}
|
|
68
89
|
private async launch(title: string, promptText: string, workspaceId: string, agentPreset?: string): Promise<string> {
|
|
69
90
|
if (agentPreset !== undefined) {
|
|
70
91
|
const presets = await this.api.agentPresets.list(request({}))
|
|
@@ -129,5 +150,12 @@ function reviewPrompt(requirement: RequirementView, run: AiReviewRun, context: R
|
|
|
129
150
|
return [common(requirement, context, workspace, workspaceSnapshot, prompts), `Review run ID: ${run.id}`, `Review kind: ${run.kind}`, `AI session ID: {{SESSION_ID}}`, '', tasks[run.kind]].join('\n')
|
|
130
151
|
}
|
|
131
152
|
function commentPrompt(requirement: RequirementView, comment: CommentThread, context: ReturnType<ReviewContextCatalog['resolve']>, workspace: ReviewWorkspaceSummary, workspaceSnapshot: string, prompts: ResolvedReviewPrompts): string {
|
|
132
|
-
return [common(requirement, context, workspace, workspaceSnapshot, prompts), `Comment ID: ${comment.id}`, `Anchor quote: ${comment.anchor
|
|
153
|
+
return [common(requirement, context, workspace, workspaceSnapshot, prompts), `Comment ID: ${comment.id}`, `Comment scope: ${comment.scope}`, `Anchor quote: ${comment.anchor?.quote ?? '整篇需求'}`, `Human comment: ${comment.body}`, `AI session ID: {{SESSION_ID}}`, '', prompts.comment].join('\n')
|
|
154
|
+
}
|
|
155
|
+
function reviewContinuationPrompt(requirement: RequirementView, run: AiReviewRun, prompts: ResolvedReviewPrompts): string {
|
|
156
|
+
const tasks: Record<AiReviewRun['kind'], string> = { 'product-first': prompts.productFirst, 'product-second': prompts.productSecond, 'engineering-precheck': prompts.engineeringPrecheck, 'change-review': prompts.changeReview }
|
|
157
|
+
return ['继续当前需求同一阶段的审核。不要重复读取已知背景,只使用 spec_read 获取当前 commit 的增量变化。', `Requirement ID: ${requirement.id}`, `Current stage: ${requirement.stage}`, `Pinned commit: ${requirement.currentCommit}`, `Review run ID: ${run.id}`, `Review kind: ${run.kind}`, '', tasks[run.kind]].join('\n')
|
|
158
|
+
}
|
|
159
|
+
function commentContinuationPrompt(requirement: RequirementView, comment: CommentThread, prompts: ResolvedReviewPrompts): string {
|
|
160
|
+
return ['在当前需求同一阶段的既有上下文中分析这条新评论。不要重新扫描整个工作区;仅在评论涉及新的实现事实时做最小增量查询。', `Requirement ID: ${requirement.id}`, `Pinned commit: ${requirement.currentCommit}`, `Comment ID: ${comment.id}`, `Comment scope: ${comment.scope}`, `Anchor quote: ${comment.anchor?.quote ?? '整篇需求'}`, `Human comment: ${comment.body}`, '', prompts.comment].join('\n')
|
|
133
161
|
}
|
package/src/routes.ts
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
import type { IncomingMessage, ServerResponse } from 'node:http'
|
|
2
2
|
import type { WebRoute } from '@deepseek-ai/dsh-host-webserver'
|
|
3
3
|
import type { CollaborationEngine } from './engine.ts'
|
|
4
|
-
import { API_PREFIX, parseEnvelope } from './protocol.ts'
|
|
4
|
+
import { API_PREFIX, parseEnvelope, type CollaborationEvent, type InsightImportance } from './protocol.ts'
|
|
5
|
+
import { buildStructuredDiff } from './structured-diff.ts'
|
|
5
6
|
import type { DshReviewCoordinator } from './review-runtime.ts'
|
|
6
7
|
|
|
7
|
-
const BODY_LIMIT =
|
|
8
|
+
const BODY_LIMIT = 6 * 1024 * 1024
|
|
8
9
|
const HEARTBEAT_MS = 15_000
|
|
9
10
|
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
11
|
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 true; try { return new URL(origin).host === req.headers.host } catch { return false } }
|
|
@@ -13,7 +14,35 @@ async function readJson(req: IncomingMessage): Promise<unknown> { const chunks:
|
|
|
13
14
|
export function makeRoutes(engine: CollaborationEngine, coordinator: DshReviewCoordinator): WebRoute[] {
|
|
14
15
|
const guard = (req: IncomingMessage, res: ServerResponse): boolean => { if (trusted(req)) return true; json(res, 403, { ok: false, error: 'forbidden' }); return false }
|
|
15
16
|
return [
|
|
16
|
-
{ kind: 'exact', path: `${API_PREFIX}/state`, handler: (req, res) => {
|
|
17
|
+
{ kind: 'exact', path: `${API_PREFIX}/state`, handler: (req, res) => {
|
|
18
|
+
if (req.method !== 'GET') return json(res, 405, { ok: false, error: 'method-not-allowed' }); if (!guard(req, res)) return
|
|
19
|
+
const state = engine.snapshot(); const summaries = engine.summaries(); const url = new URL(req.url ?? '', `http://${req.headers.host ?? '127.0.0.1'}`)
|
|
20
|
+
const requestedId = url.searchParams.get('requirementId'); const currentId = requestedId ?? summaries.find(item => item.archivedAt === undefined)?.id ?? summaries[0]?.id
|
|
21
|
+
let requirement
|
|
22
|
+
try { requirement = currentId ? engine.view(currentId) : undefined } catch {}
|
|
23
|
+
json(res, 200, { revision: state.revision, participants: state.participants, requirements: summaries, ...(requirement ? { requirement } : {}) })
|
|
24
|
+
} },
|
|
25
|
+
{ 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
|
+
{ kind: 'exact', path: `${API_PREFIX}/notifications`, handler: (req, res) => {
|
|
27
|
+
if (req.method !== 'GET') return json(res, 405, { ok: false, error: 'method-not-allowed' }); if (!guard(req, res)) return
|
|
28
|
+
const url = new URL(req.url ?? '', `http://${req.headers.host ?? '127.0.0.1'}`); const participantId = url.searchParams.get('participantId') ?? ''
|
|
29
|
+
if (participantId.length < 8) return json(res, 400, { ok: false, error: 'invalid-participant-query' })
|
|
30
|
+
json(res, 200, { ok: true, ...engine.notifications(participantId, Number(url.searchParams.get('page') ?? 1), Number(url.searchParams.get('pageSize') ?? 50)) })
|
|
31
|
+
} },
|
|
32
|
+
{ kind: 'exact', path: `${API_PREFIX}/insights`, handler: (req, res) => {
|
|
33
|
+
if (req.method !== 'GET') return json(res, 405, { ok: false, error: 'method-not-allowed' }); if (!guard(req, res)) return
|
|
34
|
+
const url = new URL(req.url ?? '', `http://${req.headers.host ?? '127.0.0.1'}`); const value = (key: string): string | undefined => url.searchParams.get(key) || undefined
|
|
35
|
+
const requirementId = value('requirementId'); const customerId = value('customerId'); const companyId = value('companyId'); const sourceId = value('sourceId'); const importance = value('importance') as InsightImportance | undefined
|
|
36
|
+
json(res, 200, { ok: true, ...engine.insights({ ...(requirementId ? { requirementId } : {}), ...(customerId ? { customerId } : {}), ...(companyId ? { companyId } : {}), ...(sourceId ? { sourceId } : {}), ...(importance ? { importance } : {}), page: Number(value('page') ?? 1), pageSize: Number(value('pageSize') ?? 50) }) })
|
|
37
|
+
} },
|
|
38
|
+
{ kind: 'exact', path: `${API_PREFIX}/diff`, handler: async (req, res) => {
|
|
39
|
+
if (!guard(req, res)) return
|
|
40
|
+
try {
|
|
41
|
+
if (req.method === 'GET') { const url = new URL(req.url ?? '', `http://${req.headers.host ?? '127.0.0.1'}`); return json(res, 200, { ok: true, diff: engine.diff(url.searchParams.get('requirementId') ?? '', url.searchParams.get('baseCommit') ?? '', url.searchParams.get('headCommit') || undefined) }) }
|
|
42
|
+
if (req.method === 'POST') { if (!(req.headers['content-type'] ?? '').toLowerCase().startsWith('application/json')) return json(res, 415, { ok: false, error: 'json-required' }); const body = await readJson(req) as { before?: unknown; after?: unknown; baseLabel?: unknown; headLabel?: unknown }; if (typeof body.before !== 'string' || typeof body.after !== 'string') return json(res, 400, { ok: false, error: 'invalid-diff-preview' }); return json(res, 200, { ok: true, diff: buildStructuredDiff(body.before, body.after, typeof body.baseLabel === 'string' ? body.baseLabel : undefined, typeof body.headLabel === 'string' ? body.headLabel : undefined) }) }
|
|
43
|
+
return json(res, 405, { ok: false, error: 'method-not-allowed' })
|
|
44
|
+
} catch (error) { return json(res, 400, { ok: false, error: error instanceof Error ? error.message : String(error) }) }
|
|
45
|
+
} },
|
|
17
46
|
{ 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
47
|
{ 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
48
|
{ kind: 'exact', path: `${API_PREFIX}/my-items`, handler: (req, res) => {
|
|
@@ -47,6 +76,6 @@ export function makeRoutes(engine: CollaborationEngine, coordinator: DshReviewCo
|
|
|
47
76
|
return json(res, 405, { ok: false, error: 'method-not-allowed' })
|
|
48
77
|
} catch (error) { return json(res, 400, { ok: false, error: error instanceof Error ? error.message : String(error) }) }
|
|
49
78
|
} },
|
|
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(
|
|
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.snapshot().revision }) } },
|
|
51
80
|
]
|
|
52
81
|
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import type { StructuredDiff, StructuredDiffLine } from './protocol.ts'
|
|
2
|
+
|
|
3
|
+
type Operation = { type: StructuredDiffLine['type']; text: string }
|
|
4
|
+
|
|
5
|
+
export function buildStructuredDiff(before: string, after: string, baseLabel = '原版本', headLabel = '新版本'): StructuredDiff {
|
|
6
|
+
const operations = myers(before.split('\n'), after.split('\n'))
|
|
7
|
+
let oldLine = 0; let newLine = 0
|
|
8
|
+
const lines = operations.map<StructuredDiffLine>(operation => {
|
|
9
|
+
if (operation.type !== 'added') oldLine += 1
|
|
10
|
+
if (operation.type !== 'removed') newLine += 1
|
|
11
|
+
return { type: operation.type, ...(operation.type === 'added' ? {} : { oldLine }), ...(operation.type === 'removed' ? {} : { newLine }), text: operation.text }
|
|
12
|
+
})
|
|
13
|
+
const changed = lines.flatMap((line, index) => line.type === 'context' ? [] : [index])
|
|
14
|
+
if (changed.length === 0) return { baseLabel, headLabel, added: 0, removed: 0, hunks: [] }
|
|
15
|
+
const ranges: Array<{ start: number; end: number }> = []
|
|
16
|
+
for (const index of changed) {
|
|
17
|
+
const start = Math.max(0, index - 3); const end = Math.min(lines.length - 1, index + 3); const previous = ranges.at(-1)
|
|
18
|
+
if (previous !== undefined && start <= previous.end + 1) previous.end = Math.max(previous.end, end)
|
|
19
|
+
else ranges.push({ start, end })
|
|
20
|
+
}
|
|
21
|
+
return {
|
|
22
|
+
baseLabel, headLabel,
|
|
23
|
+
added: lines.filter(line => line.type === 'added').length,
|
|
24
|
+
removed: lines.filter(line => line.type === 'removed').length,
|
|
25
|
+
hunks: ranges.map((range, index) => {
|
|
26
|
+
const visible = lines.slice(range.start, range.end + 1)
|
|
27
|
+
const collapsedBeforeLines = index === 0 ? lines.slice(0, range.start) : []
|
|
28
|
+
const collapsedAfterLines = lines.slice(range.end + 1, ranges[index + 1]?.start ?? lines.length)
|
|
29
|
+
return {
|
|
30
|
+
id: `hunk-${index + 1}`,
|
|
31
|
+
oldStart: visible.find(line => line.oldLine !== undefined)?.oldLine ?? 0,
|
|
32
|
+
newStart: visible.find(line => line.newLine !== undefined)?.newLine ?? 0,
|
|
33
|
+
lines: visible,
|
|
34
|
+
collapsedBefore: collapsedBeforeLines.length,
|
|
35
|
+
collapsedAfter: collapsedAfterLines.length,
|
|
36
|
+
collapsedBeforeLines,
|
|
37
|
+
collapsedAfterLines,
|
|
38
|
+
}
|
|
39
|
+
}),
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function myers(left: string[], right: string[]): Operation[] {
|
|
44
|
+
const trace: Array<Map<number, number>> = []
|
|
45
|
+
let frontier = new Map<number, number>([[1, 0]])
|
|
46
|
+
for (let distance = 0; distance <= left.length + right.length; distance += 1) {
|
|
47
|
+
trace.push(new Map(frontier))
|
|
48
|
+
const next = new Map<number, number>()
|
|
49
|
+
for (let diagonal = -distance; diagonal <= distance; diagonal += 2) {
|
|
50
|
+
const down = diagonal === -distance || (diagonal !== distance && (frontier.get(diagonal - 1) ?? -1) < (frontier.get(diagonal + 1) ?? -1))
|
|
51
|
+
let x = down ? frontier.get(diagonal + 1) ?? 0 : (frontier.get(diagonal - 1) ?? 0) + 1
|
|
52
|
+
let y = x - diagonal
|
|
53
|
+
while (x < left.length && y < right.length && left[x] === right[y]) { x += 1; y += 1 }
|
|
54
|
+
next.set(diagonal, x)
|
|
55
|
+
if (x >= left.length && y >= right.length) return backtrack(trace, left, right)
|
|
56
|
+
}
|
|
57
|
+
frontier = next
|
|
58
|
+
}
|
|
59
|
+
return []
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function backtrack(trace: Array<Map<number, number>>, left: string[], right: string[]): Operation[] {
|
|
63
|
+
let x = left.length; let y = right.length; const result: Operation[] = []
|
|
64
|
+
for (let distance = trace.length - 1; distance >= 0; distance -= 1) {
|
|
65
|
+
const frontier = trace[distance]!; const diagonal = x - y
|
|
66
|
+
const down = diagonal === -distance || (diagonal !== distance && (frontier.get(diagonal - 1) ?? -1) < (frontier.get(diagonal + 1) ?? -1))
|
|
67
|
+
const previousDiagonal = down ? diagonal + 1 : diagonal - 1
|
|
68
|
+
const previousX = frontier.get(previousDiagonal) ?? 0; const previousY = previousX - previousDiagonal
|
|
69
|
+
while (x > previousX && y > previousY) { result.push({ type: 'context', text: left[x - 1]! }); x -= 1; y -= 1 }
|
|
70
|
+
if (distance === 0) break
|
|
71
|
+
if (x === previousX) { result.push({ type: 'added', text: right[y - 1]! }); y -= 1 }
|
|
72
|
+
else { result.push({ type: 'removed', text: left[x - 1]! }); x -= 1 }
|
|
73
|
+
}
|
|
74
|
+
return result.reverse()
|
|
75
|
+
}
|