dsh-spec-collab 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/git-store.ts CHANGED
@@ -1,7 +1,8 @@
1
1
  import { execFileSync } from 'node:child_process'
2
2
  import { randomUUID } from 'node:crypto'
3
- import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
4
- import { dirname, join } from 'node:path'
3
+ import { existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, rmSync } from 'node:fs'
4
+ import { tmpdir } from 'node:os'
5
+ import { join } from 'node:path'
5
6
  import type { ParticipantSnapshot, RequirementVersion, SourceReference } from './protocol.ts'
6
7
 
7
8
  export class VersionConflictError extends Error {
@@ -11,191 +12,261 @@ export class VersionConflictError extends Error {
11
12
  export interface CreateRequirementInput { title: string; rawRequirement: string; sources: SourceReference[]; participant: ParticipantSnapshot }
12
13
  export interface SaveVersionInput { requirementId: string; baseCommit: string; markdown: string; participant: ParticipantSnapshot; summary: string }
13
14
 
15
+ export interface PreparedSpecCommit {
16
+ requirementId: string
17
+ operation: 'create' | 'update' | 'delete'
18
+ baseHead?: string
19
+ commit: string
20
+ }
21
+
22
+ const SHA = /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/
23
+ const REQUIREMENT_ID = /^[a-z0-9\u4e00-\u9fff][a-z0-9\u4e00-\u9fff-]{1,80}$/
24
+ const GIT_BUFFER_LIMIT = 16 * 1024 * 1024
25
+
26
+ type VersionMetadata = Omit<RequirementVersion, 'markdown'>
27
+
14
28
  export class GitRequirementStore {
29
+ private readonly historyCache = new Map<string, { head: string; history: VersionMetadata[] }>()
30
+ // Git blobs addressed by a full commit SHA are immutable. Bound the cache because bodies can reach 2 MB.
15
31
  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
32
  private commitBaseUrl: string | null | undefined
19
33
 
20
- constructor(readonly root: string) { this.ensureRepository() }
34
+ constructor(readonly root: string) {
35
+ mkdirSync(root, { recursive: true, mode: 0o700 })
36
+ if (!existsSync(join(root, '.git'))) this.git(['init'])
37
+ }
21
38
 
22
39
  create(input: CreateRequirementInput): { requirementId: string; version: RequirementVersion } {
40
+ const change = this.prepareCreate(input)
41
+ this.publish(change)
42
+ return { requirementId: change.requirementId, version: this.read(change.requirementId, change.commit) }
43
+ }
44
+
45
+ save(input: SaveVersionInput): RequirementVersion {
46
+ const change = this.prepareSave(input)
47
+ this.publish(change)
48
+ return this.read(change.requirementId, change.commit)
49
+ }
50
+
51
+ remove(requirementId: string, participant: ParticipantSnapshot): void {
52
+ this.publish(this.prepareRemove(requirementId, this.head(requirementId), participant))
53
+ }
54
+
55
+ prepareCreate(input: CreateRequirementInput): PreparedSpecCommit {
23
56
  const requirementId = `${slug(input.title)}-${randomUUID().slice(0, 8)}`
24
57
  const markdown = initialSpec(input.title, input.rawRequirement, input.sources)
25
- const path = this.specPath(requirementId)
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
- }
58
+ validateSize(markdown)
59
+ const baseHead = this.repositoryHead()
60
+ return this.prepareCommit({ requirementId, operation: 'create', ...(baseHead ? { baseHead } : {}) }, input.participant, 'Create requirement', markdown)
38
61
  }
39
62
 
40
- save(input: SaveVersionInput): RequirementVersion {
41
- const current = this.head(input.requirementId)
42
- if (current !== input.baseCommit) throw new VersionConflictError(current)
43
- const onDisk = readFileSync(this.specPath(input.requirementId), 'utf8')
44
- if (onDisk !== this.read(input.requirementId, current).markdown) throw new Error('spec has external uncommitted changes')
45
- if (input.summary.trim() === '') throw new Error('change summary is required')
46
- if (input.markdown.length > 2_000_000) throw new Error('spec exceeds 2 MB')
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)
63
+ prepareSave(input: SaveVersionInput): PreparedSpecCommit {
64
+ const baseHead = this.assertCurrent(input.requirementId, input.baseCommit)
65
+ const summary = input.summary.trim()
66
+ if (!summary) throw new Error('change summary is required')
67
+ validateSize(input.markdown)
68
+ if (input.markdown === this.read(input.requirementId, input.baseCommit).markdown) throw new Error('no changes to save')
69
+ return this.prepareCommit({ requirementId: input.requirementId, operation: 'update', baseHead }, input.participant, summary, input.markdown)
70
+ }
71
+
72
+ prepareRemove(requirementId: string, baseCommit: string, participant: ParticipantSnapshot): PreparedSpecCommit {
73
+ const baseHead = this.assertCurrent(requirementId, baseCommit)
74
+ return this.prepareCommit({ requirementId, operation: 'delete', baseHead }, participant, 'Delete requirement')
75
+ }
76
+
77
+ /** Publish a prepared commit and synchronize its one owned path. Safe to repeat after interruption. */
78
+ publish(change: PreparedSpecCommit): void {
79
+ const path = this.relativeSpecPath(change.requirementId)
80
+ const head = this.repositoryHead()
81
+ if (head !== change.commit) {
82
+ if (head !== change.baseHead) throw new Error('spec repository HEAD changed during the collaboration transaction')
83
+ this.assertClean(path)
84
+ this.git(['update-ref', 'HEAD', change.commit, change.baseHead ?? '0'.repeat(change.commit.length)])
85
+ } else {
86
+ this.assertRecoverableCheckout(change, path)
54
87
  }
55
- catch (error) {
56
- writeFileSync(this.specPath(input.requirementId), onDisk, 'utf8')
57
- this.git(['reset', '--', relativePath], true)
58
- throw error
88
+ if (change.operation !== 'delete' || existsSync(join(this.root, path)) || this.git(['ls-files', '--', path]).trim() !== '') {
89
+ this.git(['restore', '--source', change.commit, '--staged', '--worktree', '--', path])
59
90
  }
91
+ if (change.operation === 'delete') this.historyCache.delete(change.requirementId)
60
92
  }
61
93
 
62
- read(requirementId: string, commit?: string): RequirementVersion {
63
- assertRequirementId(requirementId)
64
- const resolved = commit ?? this.head(requirementId)
65
- const cacheKey = `${requirementId}:${resolved}`
66
- const cached = this.versionCache.get(cacheKey)
94
+ read(requirementId: string, commit = this.head(requirementId)): RequirementVersion {
95
+ const key = `${requirementId}:${commit}`
96
+ const cached = this.versionCache.get(key)
67
97
  if (cached !== undefined) return structuredClone(cached)
68
- const markdown = this.gitText(['show', `${resolved}:${this.relativeSpecPath(requirementId)}`])
69
- const fields = this.gitText(['show', '-s', '--format=%H%x1f%P%x1f%at%x1f%an%x1f%ae%x1f%B', resolved]).split('\x1f')
70
- const [sha = resolved, parents = '', seconds = '0', nickname = 'unknown', email = '', ...bodyParts] = fields
71
- const body = bodyParts.join('\x1f').trim()
72
- const role = /DSH-Role:\s*(product|engineering)/.exec(body)?.[1] as ParticipantSnapshot['role'] | undefined
73
- const summary = body.split('\n')[0] ?? 'Saved version'
74
- const version: RequirementVersion = {
75
- commit: sha,
76
- ...(parents.split(' ')[0] ? { parentCommit: parents.split(' ')[0] } : {}),
77
- markdown,
78
- author: { participantId: email.replace(/@dsh\.local$/, '') || 'unknown', nickname, role: role ?? 'product', kind: 'human' },
79
- summary,
80
- createdAt: Number(seconds) * 1000,
81
- }
82
- this.versionCache.set(cacheKey, version)
98
+ const markdown = this.body(requirementId, commit)
99
+ const metadata = this.historyCache.get(requirementId)?.history.find(item => item.commit === commit)
100
+ ?? parseMetadata(this.git(['show', '-s', `--format=${VERSION_FORMAT}`, commit]))
101
+ const version = { ...metadata, markdown }
102
+ if (this.versionCache.size >= 16) this.versionCache.delete(this.versionCache.keys().next().value!)
103
+ this.versionCache.set(key, version)
83
104
  return structuredClone(version)
84
105
  }
85
106
 
86
- history(requirementId: string): Array<Omit<RequirementVersion, 'markdown'>> {
87
- assertRequirementId(requirementId)
107
+ history(requirementId: string, head = this.repositoryHead()): VersionMetadata[] {
108
+ const path = this.relativeSpecPath(requirementId)
109
+ if (head === undefined) return []
110
+ assertCommit(head)
88
111
  const cached = this.historyCache.get(requirementId)
89
- if (cached !== undefined) return structuredClone(cached)
90
- const output = this.gitText(['log', '--format=%H%x1f%P%x1f%at%x1f%an%x1f%ae%x1f%B%x1e', '--', this.relativeSpecPath(requirementId)])
91
- const history: Array<Omit<RequirementVersion, 'markdown'>> = output.split('\x1e').map(row => row.trim()).filter(Boolean).map(row => {
92
- const [commit = '', parents = '', seconds = '0', nickname = 'unknown', email = '', ...bodyParts] = row.split('\x1f')
93
- const body = bodyParts.join('\x1f').trim()
94
- const role = /DSH-Role:\s*(product|engineering)/.exec(body)?.[1] as ParticipantSnapshot['role'] | undefined
95
- return {
96
- commit,
97
- ...(parents.split(' ')[0] ? { parentCommit: parents.split(' ')[0] } : {}),
98
- author: { participantId: email.replace(/@dsh\.local$/, '') || 'unknown', nickname, role: role ?? 'product', kind: 'human' as const },
99
- summary: body.split('\n')[0] ?? 'Saved version',
100
- createdAt: Number(seconds) * 1000,
101
- }
102
- })
103
- this.historyCache.set(requirementId, history)
112
+ if (cached?.head === head) return structuredClone(cached.history)
113
+ const output = this.git(['log', `--format=${VERSION_FORMAT}%x1e`, head, '--', path])
114
+ const history = output.split('\x1e').map(row => row.trim()).filter(Boolean).map(parseMetadata)
115
+ this.historyCache.set(requirementId, { head, history })
104
116
  return structuredClone(history)
105
117
  }
106
118
 
107
- diff(requirementId: string, baseCommit: string, headCommit?: string): string {
108
- assertRequirementId(requirementId)
109
- return this.gitText(['diff', baseCommit, headCommit ?? this.head(requirementId), '--', this.relativeSpecPath(requirementId)])
119
+ diff(requirementId: string, baseCommit: string, headCommit = this.head(requirementId)): string {
120
+ assertCommit(baseCommit)
121
+ assertCommit(headCommit)
122
+ return this.git(['diff', baseCommit, headCommit, '--', this.relativeSpecPath(requirementId)])
110
123
  }
111
124
 
112
125
  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 }
126
+ if (!SHA.test(commit)) return undefined
127
+ if (this.commitBaseUrl === undefined) {
128
+ try {
129
+ const origin = this.git(['config', '--get', 'remote.origin.url']).trim()
130
+ const scp = /^git@([^:]+):(.+)$/.exec(origin)
131
+ const url = new URL(scp ? `https://${scp[1]}/${scp[2]}` : origin.replace(/^ssh:\/\/git@/, 'https://'))
132
+ if (url.protocol !== 'https:' && url.protocol !== 'http:') throw new Error('unsupported remote URL')
133
+ url.username = ''; url.password = ''
134
+ this.commitBaseUrl = url.toString().replace(/\.git$/, '').replace(/\/$/, '')
135
+ } catch {
136
+ this.commitBaseUrl = null
137
+ }
138
+ }
139
+ return this.commitBaseUrl === null ? undefined : `${this.commitBaseUrl}/commit/${commit}`
140
+ }
141
+
142
+ head(requirementId: string): string {
143
+ return this.requirementHead(requirementId, this.repositoryHead())
144
+ }
145
+
146
+ private requirementHead(requirementId: string, repositoryHead: string | undefined): string {
147
+ const path = this.relativeSpecPath(requirementId)
148
+ return repositoryHead === undefined ? '' : this.git(['log', '-1', '--format=%H', repositoryHead, '--', path]).trim()
149
+ }
150
+
151
+ private assertCurrent(requirementId: string, baseCommit: string): string {
152
+ const head = this.repositoryHead()
153
+ const current = this.requirementHead(requirementId, head)
154
+ if (current !== baseCommit) throw new VersionConflictError(current)
155
+ if (head === undefined || current === '') throw new Error('requirement spec not found')
156
+ return head
157
+ }
158
+
159
+ private prepareCommit(change: Omit<PreparedSpecCommit, 'commit'>, participant: ParticipantSnapshot, summary: string, markdown?: string): PreparedSpecCommit {
160
+ const path = this.relativeSpecPath(change.requirementId)
161
+ this.assertClean(path)
162
+ if (change.operation === 'create' && existsSync(join(this.root, path))) throw new Error('requirement spec already exists')
163
+ const temporary = mkdtempSync(join(tmpdir(), 'spec-git-index-'))
121
164
  try {
122
- const url = new URL(normalized)
123
- url.username = ''; url.password = ''
124
- this.commitBaseUrl = url.toString().replace(/\.git$/, '').replace(/\/$/, '')
165
+ const env = { ...process.env, GIT_INDEX_FILE: join(temporary, 'index') }
166
+ this.git(['read-tree', change.baseHead ?? '--empty'], { env })
167
+ if (markdown === undefined) {
168
+ this.git(['update-index', '--force-remove', '--', path], { env })
169
+ } else {
170
+ const blob = this.git(['hash-object', '-w', '--stdin'], { input: markdown }).trim()
171
+ this.git(['update-index', '--add', '--cacheinfo', `100644,${blob},${path}`], { env })
172
+ }
173
+ const tree = this.git(['write-tree'], { env }).trim()
174
+ const parent = change.baseHead ? ['-p', change.baseHead] : []
175
+ const email = `${participant.participantId}@dsh.local`
176
+ const commit = this.git(['-c', 'commit.gpgsign=false', 'commit-tree', tree, ...parent, '-m', summary, '-m', `DSH-Role: ${participant.role}`], {
177
+ env: { ...env, GIT_AUTHOR_NAME: participant.nickname, GIT_AUTHOR_EMAIL: email, GIT_COMMITTER_NAME: participant.nickname, GIT_COMMITTER_EMAIL: email },
178
+ }).trim()
179
+ return { ...change, commit }
180
+ } finally {
181
+ rmSync(temporary, { recursive: true, force: true })
125
182
  }
126
- catch { this.commitBaseUrl = null; return undefined }
127
- return `${this.commitBaseUrl}/commit/${commit}`
128
183
  }
129
184
 
130
- remove(requirementId: string, participant: ParticipantSnapshot): void {
131
- assertRequirementId(requirementId)
132
- if (!existsSync(this.specPath(requirementId))) throw new Error('requirement spec not found')
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)
185
+ private assertClean(path: string): void {
186
+ const fullPath = join(this.root, path)
187
+ const stat = lstatSync(fullPath, { throwIfNoEntry: false })
188
+ if ((stat && !stat.isFile()) || this.git(['status', '--porcelain', '--untracked-files=all', '--', path]).trim() !== '') {
189
+ throw new Error('spec has external uncommitted changes')
190
+ }
138
191
  }
139
192
 
140
- head(requirementId: string): string {
141
- assertRequirementId(requirementId)
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
147
- }
148
-
149
- private commit(requirementId: string, participant: ParticipantSnapshot, summary: string): string {
150
- this.git(['add', this.relativeSpecPath(requirementId)])
151
- return this.commitStaged(participant, summary)
152
- }
153
-
154
- private commitStaged(participant: ParticipantSnapshot, summary: string): string {
155
- const env = {
156
- ...process.env,
157
- GIT_AUTHOR_NAME: participant.nickname,
158
- GIT_AUTHOR_EMAIL: `${participant.participantId}@dsh.local`,
159
- GIT_COMMITTER_NAME: participant.nickname,
160
- GIT_COMMITTER_EMAIL: `${participant.participantId}@dsh.local`,
193
+ private assertRecoverableCheckout(change: PreparedSpecCommit, path: string): void {
194
+ // After the ref moves, either side of the transaction is a valid checkout of this path.
195
+ const previous = change.operation === 'create' ? undefined : this.body(change.requirementId, change.baseHead!)
196
+ const next = change.operation === 'delete' ? undefined : this.body(change.requirementId, change.commit)
197
+ const fullPath = join(this.root, path)
198
+ const stat = lstatSync(fullPath, { throwIfNoEntry: false })
199
+ if (stat && !stat.isFile()) throw new Error('spec has external uncommitted changes')
200
+ const actual = stat ? readFileSync(fullPath, 'utf8') : undefined
201
+ if (actual !== previous && actual !== next) throw new Error('spec has external uncommitted changes')
202
+
203
+ const entry = this.git(['ls-files', '--stage', '-z', '--', path])
204
+ const matchesIndex = (body: string | undefined): boolean => {
205
+ if (body === undefined) return entry === ''
206
+ const hash = this.git(['hash-object', '--stdin'], { input: body }).trim()
207
+ return entry === `100644 ${hash} 0\t${path}\0`
161
208
  }
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' })
163
- return this.gitText(['rev-parse', 'HEAD']).trim()
209
+ if (!matchesIndex(previous) && !matchesIndex(next)) throw new Error('spec has external staged changes')
164
210
  }
165
211
 
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)
212
+ private repositoryHead(): string | undefined {
213
+ try { return this.git(['rev-parse', '--verify', '--quiet', 'HEAD']).trim() }
214
+ catch (error) { if ((error as { status?: number }).status === 1) return undefined; throw error }
215
+ }
216
+
217
+ private body(requirementId: string, commit: string): string {
218
+ assertCommit(commit)
219
+ return this.git(['show', `${commit}:${this.relativeSpecPath(requirementId)}`])
174
220
  }
175
221
 
176
- private ensureRepository(): void {
177
- mkdirSync(this.root, { recursive: true, mode: 0o700 })
178
- if (!existsSync(join(this.root, '.git'))) execFileSync('git', ['init'], { cwd: this.root, stdio: 'pipe' })
222
+ private relativeSpecPath(id: string): string {
223
+ if (!REQUIREMENT_ID.test(id)) throw new Error('invalid requirement id')
224
+ return `requirements/${id}/spec.md`
179
225
  }
180
- private relativeSpecPath(id: string): string { assertRequirementId(id); return `requirements/${id}/spec.md` }
181
- private specPath(id: string): string { return join(this.root, this.relativeSpecPath(id)) }
182
- private gitText(args: string[]): string { return execFileSync('git', args, { cwd: this.root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }) }
183
- private git(args: string[], allowFailure = false): { status: number } {
184
- try { execFileSync('git', args, { cwd: this.root, stdio: 'pipe' }); return { status: 0 } }
185
- catch (error) { if (allowFailure) return { status: (error as { status?: number }).status ?? 1 }; throw error }
226
+
227
+ private git(args: string[], options: { env?: NodeJS.ProcessEnv; input?: string } = {}): string {
228
+ return execFileSync('git', args, { ...options, cwd: this.root, encoding: 'utf8', stdio: [options.input === undefined ? 'ignore' : 'pipe', 'pipe', 'pipe'], maxBuffer: GIT_BUFFER_LIMIT })
186
229
  }
187
230
  }
188
231
 
189
- function withoutMarkdown(version: RequirementVersion): Omit<RequirementVersion, 'markdown'> {
190
- const { markdown: _markdown, ...metadata } = version
191
- return metadata
232
+ export function isPreparedSpecCommit(value: unknown): value is PreparedSpecCommit {
233
+ if (typeof value !== 'object' || value === null) return false
234
+ const { requirementId, operation, baseHead, commit } = value as Partial<PreparedSpecCommit>
235
+ return typeof requirementId === 'string' && REQUIREMENT_ID.test(requirementId)
236
+ && (operation === 'create' || operation === 'update' || operation === 'delete')
237
+ && typeof commit === 'string' && SHA.test(commit)
238
+ && (baseHead === undefined ? operation === 'create' : typeof baseHead === 'string' && SHA.test(baseHead))
239
+ }
240
+
241
+ const VERSION_FORMAT = '%H%x1f%P%x1f%at%x1f%an%x1f%ae%x1f%B'
242
+
243
+ function parseMetadata(row: string): VersionMetadata {
244
+ const [commit = '', parents = '', seconds = '0', nickname = 'unknown', email = '', ...bodyParts] = row.split('\x1f')
245
+ const body = bodyParts.join('\x1f').trim()
246
+ const role = /DSH-Role:\s*(product|engineering)/.exec(body)?.[1] as ParticipantSnapshot['role'] | undefined
247
+ const parentCommit = parents.split(' ')[0]
248
+ return {
249
+ commit,
250
+ ...(parentCommit ? { parentCommit } : {}),
251
+ author: { participantId: email.replace(/@dsh\.local$/, '') || 'unknown', nickname, role: role ?? 'product', kind: 'human' },
252
+ summary: body.split('\n')[0] ?? 'Saved version',
253
+ createdAt: Number(seconds) * 1000,
254
+ }
255
+ }
256
+
257
+ function validateSize(markdown: string): void {
258
+ if (markdown.length > 2_000_000) throw new Error('spec exceeds 2 MB')
259
+ }
260
+
261
+ function assertCommit(commit: string): void {
262
+ if (!SHA.test(commit)) throw new Error('invalid commit')
192
263
  }
193
264
 
194
265
  function slug(title: string): string {
195
266
  const value = title.toLowerCase().trim().replace(/[^a-z0-9\u4e00-\u9fff]+/g, '-').replace(/^-|-$/g, '').slice(0, 48)
196
267
  return value || 'requirement'
197
268
  }
198
- 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') }
269
+
199
270
  function initialSpec(title: string, raw: string, sources: SourceReference[]): string {
200
271
  const sourceLines = sources.length === 0 ? ['- 原始需求:当前文档(创建版本)'] : sources.map(item => `- [${item.accessStatus}] ${item.label}${item.stableId ? ` — ${item.stableId}` : ''}`)
201
272
  return [`# ${title}`, '', '## 原始需求与来源', '', raw.trim(), '', ...sourceLines, '', '## 目标与用户结果', '', '<!-- AI 初审后补充 -->', '', '## 范围与非范围', '', '### 范围', '', '### 非范围', '', '## 业务术语与规则', '', '## 需求与验收标准', '', '- **AC-1**:待澄清', '', '## 异常、权限与兼容', '', '## 测试约束', '', '## 待补充资料', ''].join('\n')
@@ -0,0 +1,186 @@
1
+ import { createHash, randomUUID } from 'node:crypto'
2
+ import type { CollaborationAction, CollaborationState, FeedbackSource, Insight, InsightImportance, InsightLink, ParticipantSnapshot, RequirementMetrics } from './protocol.ts'
3
+
4
+ export function safeHttpUrl(value: string | undefined): boolean {
5
+ if (!value) return false
6
+ try { const url = new URL(value); return url.protocol === 'http:' || url.protocol === 'https:' } catch { return false }
7
+ }
8
+
9
+ function cleanSource(input: Omit<FeedbackSource, 'createdAt' | 'updatedAt'>): Omit<FeedbackSource, 'createdAt' | 'updatedAt'> {
10
+ return { id: input.id, kind: input.kind, label: input.label, ...(input.url === undefined ? {} : { url: input.url }), ...(input.externalRef === undefined ? {} : { externalRef: input.externalRef }), accessStatus: input.accessStatus }
11
+ }
12
+ function cleanCompany(input: { id: string; name: string; externalRef?: string }): { id: string; name: string; externalRef?: string } {
13
+ return { id: input.id, name: input.name, ...(input.externalRef === undefined ? {} : { externalRef: input.externalRef }) }
14
+ }
15
+ function cleanCustomer(input: { id: string; displayName: string; companyId?: string; externalRef?: string }): { id: string; displayName: string; companyId?: string; externalRef?: string } {
16
+ return { id: input.id, displayName: input.displayName, ...(input.companyId === undefined ? {} : { companyId: input.companyId }), ...(input.externalRef === undefined ? {} : { externalRef: input.externalRef }) }
17
+ }
18
+ function validateSource(source: Pick<FeedbackSource, 'id' | 'kind' | 'label' | 'url' | 'accessStatus'>): void {
19
+ if (!source.id.trim() || !source.label.trim() || !['text', 'url', 'csv', 'markdown'].includes(source.kind) || !['available', 'unverified', 'missing'].includes(source.accessStatus) || (source.kind === 'url' && !safeHttpUrl(source.url))) throw new Error('valid source id, label and http(s) URL are required')
20
+ }
21
+ function validateCompany(company: Pick<CollaborationState['companies'][number], 'id' | 'name'>): void {
22
+ if (!company.id.trim() || !company.name.trim()) throw new Error('company id and name are required')
23
+ }
24
+ function validateCustomer(customer: Pick<CollaborationState['customers'][number], 'id' | 'displayName' | 'companyId'>, state: CollaborationState): void {
25
+ if (!customer.id.trim() || !customer.displayName.trim()) throw new Error('customer id and display name are required')
26
+ if (customer.companyId !== undefined && !state.companies.some(item => item.id === customer.companyId)) throw new Error('company not found')
27
+ }
28
+
29
+ export function insightHash(sourceId: string, body: string): string { return createHash('sha256').update(`${sourceId}\n${body.normalize('NFKC').trim().replace(/\s+/g, ' ').toLocaleLowerCase()}`).digest('hex') }
30
+ function validateInsight(insight: Insight, state: CollaborationState): void {
31
+ if (!insight.id.trim() || !insight.sourceId.trim() || !insight.body.trim()) throw new Error('insight id, source and body are required')
32
+ if (!state.feedbackSources.some(item => item.id === insight.sourceId)) throw new Error('feedback source not found')
33
+ if (insight.customerId !== undefined && !state.customers.some(item => item.id === insight.customerId)) throw new Error('customer not found')
34
+ if (insight.companyId !== undefined && !state.companies.some(item => item.id === insight.companyId)) throw new Error('company not found')
35
+ if (!['unknown', 'want', 'important', 'critical'].includes(insight.importance)) throw new Error('invalid insight importance')
36
+ }
37
+
38
+ export interface InsightQuery {
39
+ requirementId?: string
40
+ customerId?: string
41
+ companyId?: string
42
+ sourceId?: string
43
+ importance?: InsightImportance
44
+ page?: number
45
+ pageSize?: number
46
+ }
47
+
48
+ export interface InsightPage {
49
+ items: Insight[]
50
+ total: number
51
+ links: InsightLink[]
52
+ customers: CollaborationState['customers']
53
+ companies: CollaborationState['companies']
54
+ sources: FeedbackSource[]
55
+ }
56
+
57
+ export function queryInsights(state: CollaborationState, query: InsightQuery = {}): InsightPage {
58
+ const linkedIds = query.requirementId === undefined ? undefined : new Set(state.insightLinks.filter(link => link.requirementId === query.requirementId).map(link => link.insightId))
59
+ const rows = state.insights.filter(item => { const companyId = item.companyId ?? (item.customerId ? state.customers.find(customer => customer.id === item.customerId)?.companyId : undefined); return (linkedIds === undefined || linkedIds.has(item.id)) && (query.customerId === undefined || item.customerId === query.customerId) && (query.companyId === undefined || companyId === query.companyId) && (query.sourceId === undefined || item.sourceId === query.sourceId) && (query.importance === undefined || item.importance === query.importance) }).sort((left, right) => right.capturedAt - left.capturedAt)
60
+ const pageSize = Math.min(100, Math.max(1, query.pageSize ?? 50)); const start = Math.max(0, (query.page ?? 1) - 1) * pageSize
61
+ const page = rows.slice(start, start + pageSize); const ids = new Set(page.map(item => item.id)); const customerIds = new Set(page.flatMap(item => item.customerId ? [item.customerId] : [])); const companyIds = new Set(page.flatMap(item => item.companyId ? [item.companyId] : [])); for (const customer of state.customers.filter(item => customerIds.has(item.id))) if (customer.companyId) companyIds.add(customer.companyId)
62
+ return { items: structuredClone(page), total: rows.length, links: structuredClone(state.insightLinks.filter(item => ids.has(item.insightId))), customers: structuredClone(state.customers.filter(item => customerIds.has(item.id))), companies: structuredClone(state.companies.filter(item => companyIds.has(item.id))), sources: structuredClone(state.feedbackSources.filter(item => page.some(insight => insight.sourceId === item.id))) }
63
+ }
64
+
65
+ export function insightMetrics(state: CollaborationState, requirementId: string): Pick<RequirementMetrics, 'insightCount' | 'customerImportanceScore' | 'customerCount' | 'companyCount' | 'anonymousInsightCount'> {
66
+ const insightIds = new Set(state.insightLinks.filter(link => link.requirementId === requirementId).map(link => link.insightId))
67
+ const insights = state.insights.filter(insight => insightIds.has(insight.id))
68
+ const customers = new Set<string>(); const companies = new Set<string>(); const entityScores = new Map<string, number>(); let anonymousInsightCount = 0
69
+ const weights: Record<InsightImportance, number> = { unknown: 1, want: 1, important: 2, critical: 3 }
70
+ for (const insight of insights) {
71
+ const customer = insight.customerId === undefined ? undefined : state.customers.find(item => item.id === insight.customerId)
72
+ const companyId = insight.companyId ?? customer?.companyId
73
+ if (insight.customerId !== undefined) customers.add(insight.customerId)
74
+ if (companyId !== undefined) companies.add(companyId)
75
+ const entity = insight.customerId !== undefined ? `customer:${insight.customerId}` : companyId !== undefined ? `company:${companyId}` : undefined
76
+ if (entity === undefined) anonymousInsightCount += 1
77
+ else entityScores.set(entity, Math.max(entityScores.get(entity) ?? 0, weights[insight.importance]))
78
+ }
79
+ return {
80
+ insightCount: insights.length, customerImportanceScore: [...entityScores.values()].reduce((sum, value) => sum + value, 0), customerCount: customers.size, companyCount: companies.size, anonymousInsightCount,
81
+ }
82
+ }
83
+
84
+
85
+ type InsightAction = Extract<CollaborationAction, { kind: 'source.upsert' | 'company.upsert' | 'customer.upsert' | `insight.${string}` }>
86
+
87
+ export function isInsightAction(action: CollaborationAction): action is InsightAction {
88
+ return action.kind === 'source.upsert' || action.kind === 'company.upsert' || action.kind === 'customer.upsert' || action.kind.startsWith('insight.')
89
+ }
90
+
91
+ export function applyInsightAction(state: CollaborationState, action: InsightAction, now: number): void {
92
+ const { requirementId, participant } = action
93
+ switch (action.kind) {
94
+ case 'source.upsert':
95
+ upsertSource(state, action.source, now)
96
+ break
97
+ case 'company.upsert':
98
+ upsertCompany(state, action.company, now)
99
+ break
100
+ case 'customer.upsert':
101
+ upsertCustomer(state, action.customer, now)
102
+ break
103
+ case 'insight.create': {
104
+ const insight = createInsight(state, requirementId, action.insight, participant, now)
105
+ for (const link of action.links ?? []) addInsightLink(state, insight.id, link, participant, now)
106
+ break
107
+ }
108
+ case 'insight.update': {
109
+ const insight = state.insights.find(item => item.id === action.insightId)
110
+ if (insight === undefined) throw new Error('insight not found')
111
+ Object.assign(insight, action.changes)
112
+ validateInsight(insight, state)
113
+ insight.dedupeHash = insightHash(insight.sourceId, insight.body)
114
+ insight.updatedAt = now
115
+ break
116
+ }
117
+ case 'insight.delete': {
118
+ const index = state.insights.findIndex(item => item.id === action.insightId)
119
+ if (index < 0) throw new Error('insight not found')
120
+ state.insights.splice(index, 1)
121
+ state.insightLinks = state.insightLinks.filter(item => item.insightId !== action.insightId)
122
+ break
123
+ }
124
+ case 'insight.link':
125
+ addInsightLink(state, action.insightId, action.link, participant, now)
126
+ break
127
+ case 'insight.unlink':
128
+ if (!state.insightLinks.some(item => item.id === action.linkId)) throw new Error('insight link not found')
129
+ state.insightLinks = state.insightLinks.filter(item => item.id !== action.linkId)
130
+ break
131
+ case 'insight.import': {
132
+ if (action.rows.length > 2_000 || Buffer.byteLength(JSON.stringify(action.rows), 'utf8') > 5 * 1024 * 1024) throw new Error('insight import exceeds 2,000 rows or 5 MB')
133
+ if (action.source) upsertSource(state, action.source, now)
134
+ for (const source of action.sources ?? []) upsertSource(state, source, now)
135
+ for (const company of action.companies ?? []) upsertCompany(state, company, now)
136
+ for (const customer of action.customers ?? []) upsertCustomer(state, customer, now)
137
+ const actualIds = new Map<string, string>()
138
+ for (const row of action.rows) actualIds.set(row.id, createInsight(state, requirementId, row, participant, now).id)
139
+ for (const link of action.links ?? []) addInsightLink(state, actualIds.get(link.insightId) ?? link.insightId, link, participant, now)
140
+ break
141
+ }
142
+ }
143
+ }
144
+
145
+ function upsertSource(state: CollaborationState, input: Parameters<typeof cleanSource>[0], now: number): void {
146
+ const source = cleanSource(input)
147
+ validateSource(source)
148
+ upsert(state.feedbackSources, source, now)
149
+ }
150
+
151
+ function upsertCompany(state: CollaborationState, input: Parameters<typeof cleanCompany>[0], now: number): void {
152
+ const company = cleanCompany(input)
153
+ validateCompany(company)
154
+ upsert(state.companies, company, now)
155
+ }
156
+
157
+ function upsertCustomer(state: CollaborationState, input: Parameters<typeof cleanCustomer>[0], now: number): void {
158
+ const customer = cleanCustomer(input)
159
+ validateCustomer(customer, state)
160
+ upsert(state.customers, customer, now)
161
+ }
162
+
163
+ function upsert<T extends { id: string }>(rows: Array<T & { createdAt: number; updatedAt: number }>, value: T, now: number): void {
164
+ const existing = rows.find(row => row.id === value.id)
165
+ if (existing === undefined) rows.push({ ...value, createdAt: now, updatedAt: now })
166
+ else Object.assign(existing, value, { updatedAt: now })
167
+ }
168
+
169
+ function createInsight(state: CollaborationState, requirementId: string, input: Omit<Insight, 'dedupeHash' | 'createdBy' | 'createdAt' | 'updatedAt'>, participant: ParticipantSnapshot, now: number): Insight {
170
+ const draft: Insight = { ...input, title: input.title.trim(), body: input.body.trim(), dedupeHash: insightHash(input.sourceId, input.body), createdBy: participant, createdAt: now, updatedAt: now }
171
+ validateInsight(draft, state)
172
+ const existing = state.insights.find(item => item.dedupeHash === draft.dedupeHash)
173
+ const insight = existing ?? draft
174
+ if (existing === undefined) state.insights.push(insight)
175
+ if (!state.insightLinks.some(item => item.insightId === insight.id && item.requirementId === requirementId && item.targetType === 'requirement')) state.insightLinks.push({ id: randomUUID(), insightId: insight.id, requirementId, targetType: 'requirement', createdBy: participant, createdAt: now })
176
+ return insight
177
+ }
178
+
179
+ function addInsightLink(state: CollaborationState, insightId: string, link: Pick<InsightLink, 'requirementId' | 'targetType' | 'targetId'>, participant: ParticipantSnapshot, now: number): void {
180
+ if (!state.insights.some(item => item.id === insightId)) throw new Error('insight not found')
181
+ if (!state.requirements.some(item => item.id === link.requirementId)) throw new Error('requirement not found')
182
+ if (!['requirement', 'section', 'acceptance-criterion'].includes(link.targetType)) throw new Error('invalid insight link target type')
183
+ if (link.targetType !== 'requirement' && !link.targetId?.trim()) throw new Error('linked section or acceptance criterion id is required')
184
+ const duplicate = state.insightLinks.some(item => item.insightId === insightId && item.requirementId === link.requirementId && item.targetType === link.targetType && item.targetId === link.targetId)
185
+ if (!duplicate) state.insightLinks.push({ id: randomUUID(), insightId, ...link, createdBy: participant, createdAt: now })
186
+ }
@@ -5,8 +5,12 @@ export function hasCompletedCurrentReview(record: Pick<RequirementRecord, 'aiRun
5
5
  return record.aiRuns.some(run => run.commit === record.currentCommit && run.kind === kind && run.status === 'completed')
6
6
  }
7
7
 
8
+ export function currentVersionConfirmations(record: Pick<RequirementRecord, 'confirmations' | 'currentCommit'>, role: ParticipantRole) {
9
+ return record.confirmations.filter(item => item.commit === record.currentCommit && item.role === role && item.scope === 'version' && item.status === 'active' && item.participant.kind === 'human' && item.participant.role === role)
10
+ }
11
+
8
12
  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')
13
+ return currentVersionConfirmations(record, role).length > 0
10
14
  }
11
15
 
12
16
  /** Shared by workflow guidance and the authoritative Ready write. Checks must come from the current Git body. */