dsh-spec-collab 0.3.0 → 0.4.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/index.ts CHANGED
@@ -1,8 +1,7 @@
1
1
  import { homedir } from 'node:os'
2
2
  import { join } from 'node:path'
3
3
  import type { Context } from '@deepseek-ai/cordis'
4
- import Schema from 'schemastery'
5
- import type {} from '@deepseek-ai/dsh-host-apiproxy'
4
+ import Schema from '@deepseek-ai/schemastery'
6
5
  import type {} from '@deepseek-ai/dsh-host-webserver'
7
6
  import type {} from '@deepseek-ai/dsh-system-prompt'
8
7
  import type {} from '@deepseek-ai/dsh-tools'
@@ -18,7 +17,7 @@ export { DEFAULT_REVIEW_PROMPTS, resolveReviewPrompts }
18
17
  export type { ReviewPromptConfig }
19
18
 
20
19
  export const name = 'spec-collab'
21
- export const inject = ['webServer', 'apiProxy', 'tools', 'systemPrompt']
20
+ export const inject = ['webServer', 'sessionController', 'workspaceRegistry', 'agentPresets', 'tools', 'systemPrompt']
22
21
  export interface Config extends ReviewContextConfig { dataRoot?: string; repositoryPath?: string; prompts?: ReviewPromptConfig }
23
22
 
24
23
  const stringList = () => Schema.array(Schema.string()).default([])
@@ -56,8 +55,9 @@ export function apply(ctx: Context, config: Config = {}): void {
56
55
  const contexts = new ReviewContextCatalog(config)
57
56
  const prompts = resolveReviewPrompts(config.prompts)
58
57
  const engine = new CollaborationEngine(join(dataRoot, 'collaboration-v3.json'), new GitRequirementStore(config.repositoryPath ?? join(dataRoot, 'repository')), { legacyPath: join(dataRoot, 'collaboration-v2.json') })
59
- const coordinator = new DshReviewCoordinator(ctx.apiProxy, contexts, prompts)
58
+ const coordinator = new DshReviewCoordinator(ctx, contexts, prompts)
60
59
  engine.setCoordinator(coordinator)
60
+ ctx.effect(() => () => coordinator.dispose(), 'spec-collab: review lifetime')
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')
62
62
  ctx.effect(() => { const disposers = allSpecTools(engine).map(tool => ctx.tools.register(tool)); return () => { for (const dispose of disposers) dispose() } }, 'spec-collab: tools')
63
63
  ctx.effect(() => ctx.systemPrompt.section({
@@ -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
+ }
@@ -1,24 +1,29 @@
1
- import type { ApiProxy, RpcId } from '@deepseek-ai/dsh-host-apiproxy'
1
+ import type { SessionController, SessionPromptRequest } from '@deepseek-ai/dsh-api-session-controller'
2
+ import type { AgentPresetRegistry } from '@deepseek-ai/dsh-agent-preset-registry'
3
+ import type { WorkspaceId, WorkspaceRegistry } from '@deepseek-ai/dsh-workspace'
2
4
  import type { AiCoordinator } from './engine.ts'
3
5
  import type { AiReviewRun, CommentThread, RequirementView, ReviewWorkspaceSummary } from './protocol.ts'
4
6
  import { DEFAULT_REVIEW_PROMPTS, extractPromptValue, renderPrompt, resolveReviewPrompts, type ResolvedReviewPrompts, type ReviewPromptConfig } from './prompts.ts'
5
7
  import { ReviewContextCatalog, reviewContextPrompt } from './review-context.ts'
6
8
  import { readWorkspaceSnapshot } from './workspace-context.ts'
7
9
 
8
- function request<T>(payload: T) { return { rpcId: `spec-collab-${crypto.randomUUID()}` as RpcId, payload } }
9
- function failure(error: { code: string; message: string }): Error { return new Error(`${error.code}: ${error.message}`) }
10
+ export interface DshReviewHost {
11
+ sessionController: Pick<SessionController, 'create' | 'rename' | 'prompt' | 'inspect'>
12
+ workspaceRegistry: Pick<WorkspaceRegistry, 'list'>
13
+ agentPresets: Pick<AgentPresetRegistry, 'list'>
14
+ }
10
15
  const FOLLOW_UP_METADATA = '\n\n<!-- dsh-spec-collab-follow-up:'
11
16
 
12
17
  export class DshReviewCoordinator implements AiCoordinator {
13
18
  private readonly prompts: ResolvedReviewPrompts
14
19
  private readonly stageSessions = new Map<string, Promise<string>>()
15
- constructor(private readonly api: ApiProxy, private readonly contexts = new ReviewContextCatalog(), prompts: ReviewPromptConfig = {}) {
20
+ private readonly lifetime = new AbortController()
21
+ constructor(private readonly host: DshReviewHost, private readonly contexts = new ReviewContextCatalog(), prompts: ReviewPromptConfig = {}) {
16
22
  this.prompts = resolveReviewPrompts(prompts)
17
23
  }
24
+ dispose(): void { this.lifetime.abort(); this.stageSessions.clear() }
18
25
  async reviewWorkspaces(): Promise<ReviewWorkspaceSummary[]> {
19
- const listed = await this.api.workspace.list(request({}))
20
- if (!listed.result.ok) throw failure(listed.result.error)
21
- return listed.result.value.items.map(item => ({ workspaceId: item.workspaceId, title: item.title, path: item.path }))
26
+ return this.host.workspaceRegistry.list().map(item => ({ workspaceId: item.id, title: item.title, path: item.path }))
22
27
  }
23
28
  async assertWorkspaceAvailable(workspaceId: string): Promise<void> {
24
29
  await this.resolveWorkspace(workspaceId)
@@ -40,25 +45,24 @@ export class DshReviewCoordinator implements AiCoordinator {
40
45
  })
41
46
  }
42
47
  async conversation(sessionId: string): Promise<Array<{ role: 'user' | 'assistant'; text: string }>> {
43
- const history = await this.api.sessions.history(request({ sessionId: sessionId as never }))
44
- if (!history.result.ok) throw failure(history.result.error)
48
+ const history = await this.host.sessionController.inspect(sessionId as SessionPromptRequest['sessionId'], this.lifetime.signal)
45
49
  const rows: Array<{ role: 'user' | 'assistant'; text: string }> = []
46
50
  let skippedOrchestrationPrompt = false
47
- for (const entry of history.result.value.events) {
48
- if (entry.event.type !== 'user/message' && entry.event.type !== 'assistant/message') continue
49
- if (entry.event.type === 'user/message' && !skippedOrchestrationPrompt) { skippedOrchestrationPrompt = true; continue }
50
- const value = entry.event.data as unknown
51
+ for (const entry of history.events) {
52
+ if (entry.type !== 'user/message' && entry.type !== 'assistant/message') continue
53
+ if (entry.type === 'user/message' && !skippedOrchestrationPrompt) { skippedOrchestrationPrompt = true; continue }
54
+ const value = entry.data as unknown
51
55
  const message = isObject(value) && 'message' in value ? value.message : value
52
56
  const content = isObject(message) && 'content' in message ? message.content : message
53
57
  let messageText = collectText(content).join('\n').trim()
54
- if (entry.event.type === 'user/message') {
58
+ if (entry.type === 'user/message') {
55
59
  const followUp = storedFollowUp(messageText)
56
60
  ?? extractPromptValue(messageText, this.prompts.followUp.trim(), 'CONTENT')
57
61
  ?? extractPromptValue(messageText, DEFAULT_REVIEW_PROMPTS.followUp, 'CONTENT')
58
62
  if (followUp === undefined) continue
59
63
  messageText = followUp.trim()
60
64
  }
61
- if (messageText !== '') rows.push({ role: entry.event.type === 'user/message' ? 'user' : 'assistant', text: messageText })
65
+ if (messageText !== '') rows.push({ role: entry.type === 'user/message' ? 'user' : 'assistant', text: messageText })
62
66
  }
63
67
  return rows
64
68
  }
@@ -67,8 +71,7 @@ export class DshReviewCoordinator implements AiCoordinator {
67
71
  if (content === '') throw new Error('追问内容不能为空')
68
72
  const metadata = Buffer.from(content, 'utf8').toString('base64url')
69
73
  const promptText = `${renderPrompt(this.prompts.followUp, { CONTENT: content }).trim()}${FOLLOW_UP_METADATA}${metadata} -->`
70
- const prompted = await this.api.sessions.prompt(request({ sessionId: sessionId as never, mode: 'queue' as const, content: [{ type: 'text' as const, text: promptText }] }))
71
- if (!prompted.result.ok) throw failure(prompted.result.error)
74
+ await this.promptExisting(sessionId, promptText)
72
75
  }
73
76
  private async inStageSession(requirement: RequirementView, existingSessionId: string | undefined, continuation: string, launch: () => Promise<string>): Promise<string> {
74
77
  const key = `${requirement.id}:${requirement.stage}:${requirement.stageCycle}`
@@ -83,23 +86,20 @@ export class DshReviewCoordinator implements AiCoordinator {
83
86
  }
84
87
  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
88
  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)
89
+ await this.host.sessionController.prompt({
90
+ requestId: `spec-collab-${crypto.randomUUID()}` as SessionPromptRequest['requestId'],
91
+ sessionId: sessionId as SessionPromptRequest['sessionId'],
92
+ mode: 'queue', content: [{ type: 'text', text: promptText }],
93
+ }, this.lifetime.signal)
88
94
  }
89
95
  private async launch(title: string, promptText: string, workspaceId: string, agentPreset?: string): Promise<string> {
90
96
  if (agentPreset !== undefined) {
91
- const presets = await this.api.agentPresets.list(request({}))
92
- if (!presets.result.ok) throw failure(presets.result.error)
93
- const preset = presets.result.value.presets.find(item => item.id === agentPreset)
97
+ const preset = (await this.host.agentPresets.list()).find(item => item.id === agentPreset)
94
98
  if (preset === undefined || preset.broken !== undefined) throw new Error('agent preset is unavailable')
95
99
  }
96
- const created = await this.api.sessions.create(request({ workspaceId: workspaceId as never, ...(agentPreset === undefined ? {} : { agentPreset }) }))
97
- if (!created.result.ok) throw failure(created.result.error)
98
- const sessionId = created.result.value.sessionId
99
- const renamed = await this.api.sessions.rename(request({ sessionId, title }))
100
- if (!renamed.result.ok) throw failure(renamed.result.error)
101
- const prompted = await this.api.sessions.prompt(request({ sessionId, mode: 'queue' as const, content: [{ type: 'text' as const, text: promptText.replaceAll('{{SESSION_ID}}', sessionId) }] }))
102
- if (!prompted.result.ok) throw failure(prompted.result.error)
100
+ const { sessionId } = await this.host.sessionController.create({ workspaceId: workspaceId as WorkspaceId, ...(agentPreset === undefined ? {} : { agentPreset }) })
101
+ await this.host.sessionController.rename({ sessionId, title })
102
+ await this.promptExisting(sessionId, promptText.replaceAll('{{SESSION_ID}}', sessionId))
103
103
  return sessionId
104
104
  }
105
105
  private async resolveWorkspace(workspaceId: string): Promise<ReviewWorkspaceSummary> {