dsh-spec-collab 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/README.md +106 -0
- package/cordis.patch.yml +3 -0
- package/lib/client.js +41298 -0
- package/lib/index.js +1986 -0
- package/lib/types/client/SpecWorkbench.d.ts +6 -0
- package/lib/types/client/SpecWorkbench.d.ts.map +1 -0
- package/lib/types/client/api.d.ts +20 -0
- package/lib/types/client/api.d.ts.map +1 -0
- package/lib/types/client/index.d.ts +4 -0
- package/lib/types/client/index.d.ts.map +1 -0
- package/lib/types/client/mount.d.ts +4 -0
- package/lib/types/client/mount.d.ts.map +1 -0
- package/lib/types/engine.d.ts +67 -0
- package/lib/types/engine.d.ts.map +1 -0
- package/lib/types/git-store.d.ts +40 -0
- package/lib/types/git-store.d.ts.map +1 -0
- package/lib/types/index.d.ts +12 -0
- package/lib/types/index.d.ts.map +1 -0
- package/lib/types/protocol.d.ts +358 -0
- package/lib/types/protocol.d.ts.map +1 -0
- package/lib/types/review-context.d.ts +32 -0
- package/lib/types/review-context.d.ts.map +1 -0
- package/lib/types/review-runtime.d.ts +26 -0
- package/lib/types/review-runtime.d.ts.map +1 -0
- package/lib/types/routes.d.ts +5 -0
- package/lib/types/routes.d.ts.map +1 -0
- package/lib/types/tools.d.ts +8 -0
- package/lib/types/tools.d.ts.map +1 -0
- package/package.json +96 -0
- package/src/client/SpecWorkbench.tsx +293 -0
- package/src/client/api.ts +12 -0
- package/src/client/css-modules.d.ts +1 -0
- package/src/client/index.ts +16 -0
- package/src/client/mount.tsx +73 -0
- package/src/client/toast-ui.d.ts +25 -0
- package/src/client/workbench.module.css +275 -0
- package/src/engine.ts +358 -0
- package/src/git-store.ts +133 -0
- package/src/index.ts +49 -0
- package/src/protocol.ts +108 -0
- package/src/review-context.ts +87 -0
- package/src/review-runtime.ts +106 -0
- package/src/routes.ts +52 -0
- package/src/tools.ts +80 -0
package/lib/index.js
ADDED
|
@@ -0,0 +1,1986 @@
|
|
|
1
|
+
import { homedir } from "node:os";
|
|
2
|
+
import { dirname, join, normalize, resolve } from "node:path";
|
|
3
|
+
import Schema from "schemastery";
|
|
4
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
5
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
6
|
+
import { execFileSync } from "node:child_process";
|
|
7
|
+
import { defineTool } from "@deepseek-ai/dsh-tools";
|
|
8
|
+
//#region src/git-store.ts
|
|
9
|
+
var VersionConflictError = class extends Error {
|
|
10
|
+
currentCommit;
|
|
11
|
+
constructor(currentCommit) {
|
|
12
|
+
super("base-commit-conflict");
|
|
13
|
+
this.currentCommit = currentCommit;
|
|
14
|
+
this.name = "VersionConflictError";
|
|
15
|
+
}
|
|
16
|
+
};
|
|
17
|
+
var GitRequirementStore = class {
|
|
18
|
+
root;
|
|
19
|
+
constructor(root) {
|
|
20
|
+
this.root = root;
|
|
21
|
+
this.ensureRepository();
|
|
22
|
+
}
|
|
23
|
+
create(input) {
|
|
24
|
+
const requirementId = `${slug(input.title)}-${randomUUID().slice(0, 8)}`;
|
|
25
|
+
const markdown = initialSpec(input.title, input.rawRequirement, input.sources);
|
|
26
|
+
const path = this.specPath(requirementId);
|
|
27
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
28
|
+
writeFileSync(path, markdown, "utf8");
|
|
29
|
+
const commit = this.commit(requirementId, input.participant, "Create requirement");
|
|
30
|
+
return {
|
|
31
|
+
requirementId,
|
|
32
|
+
version: this.read(requirementId, commit)
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
save(input) {
|
|
36
|
+
const current = this.head(input.requirementId);
|
|
37
|
+
if (current !== input.baseCommit) throw new VersionConflictError(current);
|
|
38
|
+
if (readFileSync(this.specPath(input.requirementId), "utf8") !== this.read(input.requirementId, current).markdown) throw new Error("spec has external uncommitted changes");
|
|
39
|
+
if (input.summary.trim() === "") throw new Error("change summary is required");
|
|
40
|
+
if (input.markdown.length > 2e6) throw new Error("spec exceeds 2 MB");
|
|
41
|
+
writeFileSync(this.specPath(input.requirementId), input.markdown, "utf8");
|
|
42
|
+
this.git(["add", this.relativeSpecPath(input.requirementId)]);
|
|
43
|
+
if (this.git([
|
|
44
|
+
"diff",
|
|
45
|
+
"--cached",
|
|
46
|
+
"--quiet"
|
|
47
|
+
], true).status === 0) throw new Error("no changes to save");
|
|
48
|
+
const commit = this.commitStaged(input.participant, input.summary.trim());
|
|
49
|
+
return this.read(input.requirementId, commit);
|
|
50
|
+
}
|
|
51
|
+
read(requirementId, commit) {
|
|
52
|
+
assertRequirementId(requirementId);
|
|
53
|
+
const resolved = commit ?? this.head(requirementId);
|
|
54
|
+
const markdown = this.gitText(["show", `${resolved}:${this.relativeSpecPath(requirementId)}`]);
|
|
55
|
+
const [sha = resolved, parents = "", seconds = "0", nickname = "unknown", email = "", ...bodyParts] = this.gitText([
|
|
56
|
+
"show",
|
|
57
|
+
"-s",
|
|
58
|
+
"--format=%H%x1f%P%x1f%at%x1f%an%x1f%ae%x1f%B",
|
|
59
|
+
resolved
|
|
60
|
+
]).split("");
|
|
61
|
+
const body = bodyParts.join("").trim();
|
|
62
|
+
const role = /DSH-Role:\s*(product|engineering)/.exec(body)?.[1];
|
|
63
|
+
const summary = body.split("\n")[0] ?? "Saved version";
|
|
64
|
+
return {
|
|
65
|
+
commit: sha,
|
|
66
|
+
...parents.split(" ")[0] ? { parentCommit: parents.split(" ")[0] } : {},
|
|
67
|
+
markdown,
|
|
68
|
+
author: {
|
|
69
|
+
participantId: email.replace(/@dsh\.local$/, "") || "unknown",
|
|
70
|
+
nickname,
|
|
71
|
+
role: role ?? "product",
|
|
72
|
+
kind: "human"
|
|
73
|
+
},
|
|
74
|
+
summary,
|
|
75
|
+
createdAt: Number(seconds) * 1e3
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
history(requirementId) {
|
|
79
|
+
assertRequirementId(requirementId);
|
|
80
|
+
return this.gitText([
|
|
81
|
+
"log",
|
|
82
|
+
"--format=%H%x1f%P%x1f%at%x1f%an%x1f%ae%x1f%B%x1e",
|
|
83
|
+
"--",
|
|
84
|
+
this.relativeSpecPath(requirementId)
|
|
85
|
+
]).split("").map((row) => row.trim()).filter(Boolean).map((row) => {
|
|
86
|
+
const [commit = "", parents = "", seconds = "0", nickname = "unknown", email = "", ...bodyParts] = row.split("");
|
|
87
|
+
const body = bodyParts.join("").trim();
|
|
88
|
+
const role = /DSH-Role:\s*(product|engineering)/.exec(body)?.[1];
|
|
89
|
+
return {
|
|
90
|
+
commit,
|
|
91
|
+
...parents.split(" ")[0] ? { parentCommit: parents.split(" ")[0] } : {},
|
|
92
|
+
author: {
|
|
93
|
+
participantId: email.replace(/@dsh\.local$/, "") || "unknown",
|
|
94
|
+
nickname,
|
|
95
|
+
role: role ?? "product",
|
|
96
|
+
kind: "human"
|
|
97
|
+
},
|
|
98
|
+
summary: body.split("\n")[0] ?? "Saved version",
|
|
99
|
+
createdAt: Number(seconds) * 1e3
|
|
100
|
+
};
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
diff(requirementId, baseCommit, headCommit) {
|
|
104
|
+
assertRequirementId(requirementId);
|
|
105
|
+
return this.gitText([
|
|
106
|
+
"diff",
|
|
107
|
+
baseCommit,
|
|
108
|
+
headCommit ?? this.head(requirementId),
|
|
109
|
+
"--",
|
|
110
|
+
this.relativeSpecPath(requirementId)
|
|
111
|
+
]);
|
|
112
|
+
}
|
|
113
|
+
remove(requirementId, participant) {
|
|
114
|
+
assertRequirementId(requirementId);
|
|
115
|
+
if (!existsSync(this.specPath(requirementId))) throw new Error("requirement spec not found");
|
|
116
|
+
this.git([
|
|
117
|
+
"rm",
|
|
118
|
+
"-r",
|
|
119
|
+
`requirements/${requirementId}`
|
|
120
|
+
]);
|
|
121
|
+
this.commitStaged(participant, "Delete requirement");
|
|
122
|
+
}
|
|
123
|
+
head(requirementId) {
|
|
124
|
+
assertRequirementId(requirementId);
|
|
125
|
+
return this.gitText([
|
|
126
|
+
"log",
|
|
127
|
+
"-1",
|
|
128
|
+
"--format=%H",
|
|
129
|
+
"--",
|
|
130
|
+
this.relativeSpecPath(requirementId)
|
|
131
|
+
]).trim();
|
|
132
|
+
}
|
|
133
|
+
commit(requirementId, participant, summary) {
|
|
134
|
+
this.git(["add", this.relativeSpecPath(requirementId)]);
|
|
135
|
+
return this.commitStaged(participant, summary);
|
|
136
|
+
}
|
|
137
|
+
commitStaged(participant, summary) {
|
|
138
|
+
const env = {
|
|
139
|
+
...process.env,
|
|
140
|
+
GIT_AUTHOR_NAME: participant.nickname,
|
|
141
|
+
GIT_AUTHOR_EMAIL: `${participant.participantId}@dsh.local`,
|
|
142
|
+
GIT_COMMITTER_NAME: participant.nickname,
|
|
143
|
+
GIT_COMMITTER_EMAIL: `${participant.participantId}@dsh.local`
|
|
144
|
+
};
|
|
145
|
+
execFileSync("git", [
|
|
146
|
+
"commit",
|
|
147
|
+
"-m",
|
|
148
|
+
summary,
|
|
149
|
+
"-m",
|
|
150
|
+
`DSH-Role: ${participant.role}`
|
|
151
|
+
], {
|
|
152
|
+
cwd: this.root,
|
|
153
|
+
env,
|
|
154
|
+
stdio: "pipe"
|
|
155
|
+
});
|
|
156
|
+
return this.gitText(["rev-parse", "HEAD"]).trim();
|
|
157
|
+
}
|
|
158
|
+
ensureRepository() {
|
|
159
|
+
mkdirSync(this.root, {
|
|
160
|
+
recursive: true,
|
|
161
|
+
mode: 448
|
|
162
|
+
});
|
|
163
|
+
if (!existsSync(join(this.root, ".git"))) execFileSync("git", ["init"], {
|
|
164
|
+
cwd: this.root,
|
|
165
|
+
stdio: "pipe"
|
|
166
|
+
});
|
|
167
|
+
}
|
|
168
|
+
relativeSpecPath(id) {
|
|
169
|
+
assertRequirementId(id);
|
|
170
|
+
return `requirements/${id}/spec.md`;
|
|
171
|
+
}
|
|
172
|
+
specPath(id) {
|
|
173
|
+
return join(this.root, this.relativeSpecPath(id));
|
|
174
|
+
}
|
|
175
|
+
gitText(args) {
|
|
176
|
+
return execFileSync("git", args, {
|
|
177
|
+
cwd: this.root,
|
|
178
|
+
encoding: "utf8",
|
|
179
|
+
stdio: [
|
|
180
|
+
"ignore",
|
|
181
|
+
"pipe",
|
|
182
|
+
"pipe"
|
|
183
|
+
]
|
|
184
|
+
});
|
|
185
|
+
}
|
|
186
|
+
git(args, allowFailure = false) {
|
|
187
|
+
try {
|
|
188
|
+
execFileSync("git", args, {
|
|
189
|
+
cwd: this.root,
|
|
190
|
+
stdio: "pipe"
|
|
191
|
+
});
|
|
192
|
+
return { status: 0 };
|
|
193
|
+
} catch (error) {
|
|
194
|
+
if (allowFailure) return { status: error.status ?? 1 };
|
|
195
|
+
throw error;
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
};
|
|
199
|
+
function slug(title) {
|
|
200
|
+
return title.toLowerCase().trim().replace(/[^a-z0-9\u4e00-\u9fff]+/g, "-").replace(/^-|-$/g, "").slice(0, 48) || "requirement";
|
|
201
|
+
}
|
|
202
|
+
function assertRequirementId(value) {
|
|
203
|
+
if (!/^[a-z0-9\u4e00-\u9fff][a-z0-9\u4e00-\u9fff-]{1,80}$/.test(value)) throw new Error("invalid requirement id");
|
|
204
|
+
}
|
|
205
|
+
function initialSpec(title, raw, sources) {
|
|
206
|
+
const sourceLines = sources.length === 0 ? ["- 原始需求:当前文档(创建版本)"] : sources.map((item) => `- [${item.accessStatus}] ${item.label}${item.stableId ? ` — ${item.stableId}` : ""}`);
|
|
207
|
+
return [
|
|
208
|
+
`# ${title}`,
|
|
209
|
+
"",
|
|
210
|
+
"## 原始需求与来源",
|
|
211
|
+
"",
|
|
212
|
+
raw.trim(),
|
|
213
|
+
"",
|
|
214
|
+
...sourceLines,
|
|
215
|
+
"",
|
|
216
|
+
"## 目标与用户结果",
|
|
217
|
+
"",
|
|
218
|
+
"<!-- AI 初审后补充 -->",
|
|
219
|
+
"",
|
|
220
|
+
"## 范围与非范围",
|
|
221
|
+
"",
|
|
222
|
+
"### 范围",
|
|
223
|
+
"",
|
|
224
|
+
"### 非范围",
|
|
225
|
+
"",
|
|
226
|
+
"## 业务术语与规则",
|
|
227
|
+
"",
|
|
228
|
+
"## 需求与验收标准",
|
|
229
|
+
"",
|
|
230
|
+
"- **AC-1**:待澄清",
|
|
231
|
+
"",
|
|
232
|
+
"## 异常、权限与兼容",
|
|
233
|
+
"",
|
|
234
|
+
"## 测试约束",
|
|
235
|
+
"",
|
|
236
|
+
"## 非阻塞 Open Questions",
|
|
237
|
+
""
|
|
238
|
+
].join("\n");
|
|
239
|
+
}
|
|
240
|
+
//#endregion
|
|
241
|
+
//#region src/protocol.ts
|
|
242
|
+
const API_PREFIX = "/api/spec-collab";
|
|
243
|
+
function isParticipant(value) {
|
|
244
|
+
if (typeof value !== "object" || value === null) return false;
|
|
245
|
+
const row = value;
|
|
246
|
+
return typeof row.participantId === "string" && row.participantId.length >= 8 && typeof row.nickname === "string" && row.nickname.trim().length >= 2 && row.nickname.length <= 40 && ["product", "engineering"].includes(String(row.role)) && ["human", "ai"].includes(String(row.kind)) && (row.kind !== "ai" || typeof row.sessionId === "string");
|
|
247
|
+
}
|
|
248
|
+
function parseEnvelope(value) {
|
|
249
|
+
if (typeof value !== "object" || value === null) return void 0;
|
|
250
|
+
const row = value;
|
|
251
|
+
if (typeof row.requestId !== "string" || row.requestId.trim() === "" || typeof row.action !== "object" || row.action === null) return void 0;
|
|
252
|
+
const action = row.action;
|
|
253
|
+
if (typeof action.kind !== "string" || !isParticipant(action.participant)) return void 0;
|
|
254
|
+
return {
|
|
255
|
+
requestId: row.requestId,
|
|
256
|
+
action
|
|
257
|
+
};
|
|
258
|
+
}
|
|
259
|
+
//#endregion
|
|
260
|
+
//#region src/engine.ts
|
|
261
|
+
const emptyState = () => ({
|
|
262
|
+
schemaVersion: 2,
|
|
263
|
+
revision: 0,
|
|
264
|
+
participants: [],
|
|
265
|
+
requirements: []
|
|
266
|
+
});
|
|
267
|
+
var CollaborationEngine = class {
|
|
268
|
+
eventPath;
|
|
269
|
+
versions;
|
|
270
|
+
state;
|
|
271
|
+
coordinator;
|
|
272
|
+
listeners = /* @__PURE__ */ new Set();
|
|
273
|
+
seen = /* @__PURE__ */ new Map();
|
|
274
|
+
constructor(eventPath, versions) {
|
|
275
|
+
this.eventPath = eventPath;
|
|
276
|
+
this.versions = versions;
|
|
277
|
+
this.state = this.load();
|
|
278
|
+
}
|
|
279
|
+
setCoordinator(coordinator) {
|
|
280
|
+
this.coordinator = coordinator;
|
|
281
|
+
}
|
|
282
|
+
snapshot() {
|
|
283
|
+
return structuredClone(this.state);
|
|
284
|
+
}
|
|
285
|
+
subscribe(listener) {
|
|
286
|
+
this.listeners.add(listener);
|
|
287
|
+
return () => this.listeners.delete(listener);
|
|
288
|
+
}
|
|
289
|
+
list() {
|
|
290
|
+
return this.state.requirements.map((item) => this.view(item.id));
|
|
291
|
+
}
|
|
292
|
+
version(requirementId, commit) {
|
|
293
|
+
const record = this.record(requirementId);
|
|
294
|
+
if (!this.versions.history(record.id).some((version) => version.commit === commit)) throw new Error("requirement version not found");
|
|
295
|
+
return this.versions.read(record.id, commit);
|
|
296
|
+
}
|
|
297
|
+
myItems(participant, category) {
|
|
298
|
+
const rows = [];
|
|
299
|
+
for (const record of this.state.requirements) for (const item of record.actionItems.filter((candidate) => candidate.status === "pending")) {
|
|
300
|
+
const categories = [];
|
|
301
|
+
if (item.assigneeParticipantId === participant.participantId || item.assigneeParticipantId === void 0 && item.assigneeRole === participant.role) categories.push(item.type === "confirm" || item.type === "reconfirm" ? "awaiting-my-confirmation" : "awaiting-my-response");
|
|
302
|
+
if (sourceParticipantId(record, item) === participant.participantId) categories.push("initiated-by-me");
|
|
303
|
+
for (const current of categories) if (category === void 0 || category === current) rows.push({
|
|
304
|
+
...structuredClone(item),
|
|
305
|
+
category: current,
|
|
306
|
+
requirementTitle: record.title,
|
|
307
|
+
target: actionTarget(item)
|
|
308
|
+
});
|
|
309
|
+
}
|
|
310
|
+
return rows.sort((left, right) => Number(right.blocking) - Number(left.blocking) || right.updatedAt - left.updatedAt);
|
|
311
|
+
}
|
|
312
|
+
hasAiSession(requirementId, sessionId) {
|
|
313
|
+
const record = this.record(requirementId);
|
|
314
|
+
return record.aiRuns.some((run) => run.sessionId === sessionId) || record.comments.some((comment) => comment.aiSessionId === sessionId);
|
|
315
|
+
}
|
|
316
|
+
view(id) {
|
|
317
|
+
const record = this.record(id);
|
|
318
|
+
const version = this.versions.read(id, record.currentCommit);
|
|
319
|
+
return {
|
|
320
|
+
...structuredClone(record),
|
|
321
|
+
version,
|
|
322
|
+
history: this.versions.history(id),
|
|
323
|
+
readiness: readiness(version.markdown, record)
|
|
324
|
+
};
|
|
325
|
+
}
|
|
326
|
+
apply(requestId, action) {
|
|
327
|
+
const cached = this.seen.get(requestId);
|
|
328
|
+
if (cached !== void 0) return structuredClone(cached);
|
|
329
|
+
let result;
|
|
330
|
+
try {
|
|
331
|
+
const registered = action.participant.kind === "human" ? this.state.participants.find((item) => item.participantId === action.participant.participantId) : void 0;
|
|
332
|
+
if (registered !== void 0 && registered.role !== action.participant.role) throw new Error(`participant role is bound to ${registered.role}`);
|
|
333
|
+
result = this.applyFresh(action);
|
|
334
|
+
if (result.ok && action.participant.kind === "human" && registered === void 0) {
|
|
335
|
+
this.state.participants.push(structuredClone(action.participant));
|
|
336
|
+
this.persist();
|
|
337
|
+
result = result.deletedRequirementId ? {
|
|
338
|
+
...result,
|
|
339
|
+
revision: this.state.revision
|
|
340
|
+
} : {
|
|
341
|
+
ok: true,
|
|
342
|
+
revision: this.state.revision,
|
|
343
|
+
requirement: this.view(result.requirement.id)
|
|
344
|
+
};
|
|
345
|
+
}
|
|
346
|
+
} catch (error) {
|
|
347
|
+
const conflict = error instanceof VersionConflictError && action.kind === "version.save" ? this.saveConflict(action) : void 0;
|
|
348
|
+
result = {
|
|
349
|
+
ok: false,
|
|
350
|
+
revision: this.state.revision,
|
|
351
|
+
error: error instanceof Error ? error.message : String(error),
|
|
352
|
+
...conflict === void 0 ? {} : { conflict }
|
|
353
|
+
};
|
|
354
|
+
}
|
|
355
|
+
this.seen.set(requestId, result);
|
|
356
|
+
return structuredClone(result);
|
|
357
|
+
}
|
|
358
|
+
submitReview(input) {
|
|
359
|
+
const record = this.record(input.requirementId);
|
|
360
|
+
const run = record.aiRuns.find((item) => item.id === input.runId);
|
|
361
|
+
if (run === void 0 || run.commit !== input.commit || record.currentCommit !== input.commit) throw new Error("review run is stale");
|
|
362
|
+
assertChineseFeedback(input.maturitySummary);
|
|
363
|
+
const now = Date.now();
|
|
364
|
+
for (const item of input.items) {
|
|
365
|
+
assertChineseFeedback(item.statement, item.impact, item.question);
|
|
366
|
+
if (item.epistemicStatus === "FACT" && !item.evidence.some((evidence) => evidence.accessible && evidence.version !== void 0 && evidence.version !== "")) throw new Error("FACT requires accessible versioned evidence");
|
|
367
|
+
const recommendedOptions = item.recommendedOptions?.map((option) => option.trim()).filter(Boolean);
|
|
368
|
+
const created = {
|
|
369
|
+
...item,
|
|
370
|
+
...recommendedOptions ? { recommendedOptions } : {},
|
|
371
|
+
id: randomUUID(),
|
|
372
|
+
requirementId: record.id,
|
|
373
|
+
commit: input.commit,
|
|
374
|
+
reviewKind: run.kind,
|
|
375
|
+
createdAt: now,
|
|
376
|
+
updatedAt: now
|
|
377
|
+
};
|
|
378
|
+
record.reviewItems.push(created);
|
|
379
|
+
record.actionItems.push(actionForReview(created));
|
|
380
|
+
}
|
|
381
|
+
run.status = "completed";
|
|
382
|
+
run.maturitySummary = input.maturitySummary;
|
|
383
|
+
run.updatedAt = now;
|
|
384
|
+
this.persist();
|
|
385
|
+
}
|
|
386
|
+
submitPatch(input) {
|
|
387
|
+
const record = this.record(input.requirementId);
|
|
388
|
+
if (record.currentCommit !== input.baseCommit) throw new Error("patch base commit is stale");
|
|
389
|
+
assertChineseFeedback(input.summary, input.proposedMarkdown);
|
|
390
|
+
const patch = {
|
|
391
|
+
id: randomUUID(),
|
|
392
|
+
requirementId: record.id,
|
|
393
|
+
baseCommit: input.baseCommit,
|
|
394
|
+
reviewKind: input.reviewKind,
|
|
395
|
+
proposedMarkdown: input.proposedMarkdown,
|
|
396
|
+
summary: input.summary,
|
|
397
|
+
affectedReviewItemIds: input.affectedReviewItemIds,
|
|
398
|
+
affectedSections: input.affectedSections,
|
|
399
|
+
affectedAcceptanceIds: input.affectedAcceptanceIds,
|
|
400
|
+
createdBy: input.ai,
|
|
401
|
+
status: "pending",
|
|
402
|
+
createdAt: Date.now()
|
|
403
|
+
};
|
|
404
|
+
record.patches.push(patch);
|
|
405
|
+
record.actionItems.push({
|
|
406
|
+
id: randomUUID(),
|
|
407
|
+
requirementId: record.id,
|
|
408
|
+
sourceType: "patch",
|
|
409
|
+
sourceId: patch.id,
|
|
410
|
+
type: "confirm",
|
|
411
|
+
assigneeRole: input.reviewKind === "engineering-precheck" ? "engineering" : "product",
|
|
412
|
+
blocking: true,
|
|
413
|
+
status: "pending",
|
|
414
|
+
dueStage: record.stage,
|
|
415
|
+
createdAt: Date.now(),
|
|
416
|
+
updatedAt: Date.now()
|
|
417
|
+
});
|
|
418
|
+
this.persist();
|
|
419
|
+
}
|
|
420
|
+
submitAiReply(input) {
|
|
421
|
+
assertChineseFeedback(input.body);
|
|
422
|
+
const record = this.record(input.requirementId);
|
|
423
|
+
const comment = this.comment(record, input.commentId);
|
|
424
|
+
comment.replies.push({
|
|
425
|
+
id: randomUUID(),
|
|
426
|
+
author: input.ai,
|
|
427
|
+
body: input.body,
|
|
428
|
+
createdAt: Date.now()
|
|
429
|
+
});
|
|
430
|
+
comment.aiStatus = "completed";
|
|
431
|
+
comment.updatedAt = Date.now();
|
|
432
|
+
this.persist();
|
|
433
|
+
}
|
|
434
|
+
markAiFailure(requirementId, sourceId, error) {
|
|
435
|
+
const record = this.record(requirementId);
|
|
436
|
+
const run = record.aiRuns.find((item) => item.id === sourceId);
|
|
437
|
+
if (run !== void 0) {
|
|
438
|
+
run.status = "failed";
|
|
439
|
+
run.error = error;
|
|
440
|
+
run.updatedAt = Date.now();
|
|
441
|
+
}
|
|
442
|
+
const comment = record.comments.find((item) => item.id === sourceId);
|
|
443
|
+
if (comment !== void 0) {
|
|
444
|
+
comment.aiStatus = "failed";
|
|
445
|
+
comment.updatedAt = Date.now();
|
|
446
|
+
}
|
|
447
|
+
this.persist();
|
|
448
|
+
}
|
|
449
|
+
applyFresh(action) {
|
|
450
|
+
const now = Date.now();
|
|
451
|
+
if (action.kind === "requirement.create") {
|
|
452
|
+
requireHuman(action.participant);
|
|
453
|
+
const title = action.title.trim();
|
|
454
|
+
if (title === "" || action.rawRequirement.trim() === "") throw new Error("title and original requirement are required");
|
|
455
|
+
const workspaceId = action.workspaceId?.trim();
|
|
456
|
+
if (workspaceId === void 0 || workspaceId === "") throw new Error("review workspace is required");
|
|
457
|
+
const created = this.versions.create({
|
|
458
|
+
title,
|
|
459
|
+
rawRequirement: action.rawRequirement,
|
|
460
|
+
sources: action.sources,
|
|
461
|
+
participant: action.participant
|
|
462
|
+
});
|
|
463
|
+
const record = {
|
|
464
|
+
id: created.requirementId,
|
|
465
|
+
title,
|
|
466
|
+
stage: "product-review",
|
|
467
|
+
currentCommit: created.version.commit,
|
|
468
|
+
workspaceId,
|
|
469
|
+
sources: action.sources,
|
|
470
|
+
reviewItems: [],
|
|
471
|
+
comments: [],
|
|
472
|
+
patches: [],
|
|
473
|
+
decisions: [],
|
|
474
|
+
confirmations: [],
|
|
475
|
+
actionItems: [],
|
|
476
|
+
aiRuns: [],
|
|
477
|
+
createdAt: now,
|
|
478
|
+
updatedAt: now
|
|
479
|
+
};
|
|
480
|
+
this.state.requirements.unshift(record);
|
|
481
|
+
this.persist();
|
|
482
|
+
this.enqueueReview(record, action.participant, "product-first");
|
|
483
|
+
return {
|
|
484
|
+
ok: true,
|
|
485
|
+
revision: this.state.revision,
|
|
486
|
+
requirement: this.view(record.id)
|
|
487
|
+
};
|
|
488
|
+
}
|
|
489
|
+
const record = this.record(action.requirementId);
|
|
490
|
+
if (action.kind === "requirement.bind-workspace") {
|
|
491
|
+
requireHuman(action.participant);
|
|
492
|
+
const workspaceId = action.workspaceId.trim();
|
|
493
|
+
if (workspaceId === "") throw new Error("review workspace is required");
|
|
494
|
+
if (record.workspaceId !== void 0) throw new Error("review workspace is already bound");
|
|
495
|
+
record.workspaceId = workspaceId;
|
|
496
|
+
record.updatedAt = now;
|
|
497
|
+
this.persist();
|
|
498
|
+
} else if (action.kind === "requirement.rename") {
|
|
499
|
+
requireHuman(action.participant);
|
|
500
|
+
const title = action.title.trim();
|
|
501
|
+
if (title === "" || title.length > 120 || /[\r\n]/.test(title)) throw new Error("valid requirement title is required");
|
|
502
|
+
if (title === record.title) return {
|
|
503
|
+
ok: true,
|
|
504
|
+
revision: this.state.revision,
|
|
505
|
+
requirement: this.view(record.id)
|
|
506
|
+
};
|
|
507
|
+
const before = this.versions.read(record.id, record.currentCommit).markdown;
|
|
508
|
+
const markdown = /^# .+$/m.test(before) ? before.replace(/^# .+$/m, `# ${title}`) : `# ${title}\n\n${before}`;
|
|
509
|
+
const version = this.versions.save({
|
|
510
|
+
requirementId: record.id,
|
|
511
|
+
baseCommit: record.currentCommit,
|
|
512
|
+
markdown,
|
|
513
|
+
participant: action.participant,
|
|
514
|
+
summary: `Rename requirement: ${title}`
|
|
515
|
+
});
|
|
516
|
+
record.title = title;
|
|
517
|
+
record.currentCommit = version.commit;
|
|
518
|
+
record.updatedAt = now;
|
|
519
|
+
invalidateAffected(record, [], []);
|
|
520
|
+
this.persist();
|
|
521
|
+
this.enqueueReview(record, action.participant, "change-review");
|
|
522
|
+
} else if (action.kind === "requirement.archive") {
|
|
523
|
+
requireHuman(action.participant);
|
|
524
|
+
if (action.archived) record.archivedAt = now;
|
|
525
|
+
else delete record.archivedAt;
|
|
526
|
+
record.updatedAt = now;
|
|
527
|
+
this.persist();
|
|
528
|
+
} else if (action.kind === "requirement.delete") {
|
|
529
|
+
requireHuman(action.participant);
|
|
530
|
+
const deleted = this.view(record.id);
|
|
531
|
+
this.versions.remove(record.id, action.participant);
|
|
532
|
+
this.state.requirements.splice(this.state.requirements.indexOf(record), 1);
|
|
533
|
+
this.persist();
|
|
534
|
+
return {
|
|
535
|
+
ok: true,
|
|
536
|
+
revision: this.state.revision,
|
|
537
|
+
requirement: deleted,
|
|
538
|
+
deletedRequirementId: record.id
|
|
539
|
+
};
|
|
540
|
+
} else if (action.kind === "version.save") {
|
|
541
|
+
requireHuman(action.participant);
|
|
542
|
+
const before = this.versions.read(record.id, record.currentCommit).markdown;
|
|
543
|
+
const version = this.versions.save({
|
|
544
|
+
requirementId: record.id,
|
|
545
|
+
baseCommit: action.baseCommit,
|
|
546
|
+
markdown: action.markdown,
|
|
547
|
+
participant: action.participant,
|
|
548
|
+
summary: action.summary
|
|
549
|
+
});
|
|
550
|
+
const impact = changedScopes(before, action.markdown);
|
|
551
|
+
record.currentCommit = version.commit;
|
|
552
|
+
record.updatedAt = now;
|
|
553
|
+
delete record.readyPackage;
|
|
554
|
+
invalidateAffected(record, impact.sections, impact.acceptanceIds);
|
|
555
|
+
record.patches.filter((item) => item.status === "pending").forEach((item) => {
|
|
556
|
+
item.status = "stale";
|
|
557
|
+
});
|
|
558
|
+
if (record.stage === "ready") record.stage = "joint-review";
|
|
559
|
+
this.persist();
|
|
560
|
+
this.enqueueReview(record, action.participant, "change-review");
|
|
561
|
+
} else if (action.kind === "review.request") {
|
|
562
|
+
requireHuman(action.participant);
|
|
563
|
+
this.enqueueReview(record, action.participant, action.reviewKind);
|
|
564
|
+
} else if (action.kind === "review.respond") {
|
|
565
|
+
requireHuman(action.participant);
|
|
566
|
+
const item = record.reviewItems.find((candidate) => candidate.id === action.reviewItemId);
|
|
567
|
+
if (item === void 0) throw new Error("review item not found");
|
|
568
|
+
item.response = {
|
|
569
|
+
participant: action.participant,
|
|
570
|
+
disposition: action.disposition,
|
|
571
|
+
body: action.body.trim(),
|
|
572
|
+
createdAt: now
|
|
573
|
+
};
|
|
574
|
+
item.status = action.disposition === "joint-review" ? "joint-review" : action.disposition === "to-verify" ? "non-blocking-verify" : "answered";
|
|
575
|
+
item.updatedAt = now;
|
|
576
|
+
record.actionItems.filter((task) => task.sourceId === item.id && task.status === "pending").forEach((task) => {
|
|
577
|
+
task.status = "handled";
|
|
578
|
+
task.updatedAt = now;
|
|
579
|
+
});
|
|
580
|
+
this.persist();
|
|
581
|
+
} else if (action.kind === "comment.create") {
|
|
582
|
+
requireHuman(action.participant);
|
|
583
|
+
if (action.commit !== record.currentCommit) throw new VersionConflictError(record.currentCommit);
|
|
584
|
+
const comment = {
|
|
585
|
+
id: randomUUID(),
|
|
586
|
+
requirementId: record.id,
|
|
587
|
+
commit: action.commit,
|
|
588
|
+
anchor: action.anchor,
|
|
589
|
+
author: action.participant,
|
|
590
|
+
body: action.body.trim(),
|
|
591
|
+
replies: [],
|
|
592
|
+
aiStatus: "queued",
|
|
593
|
+
status: "open",
|
|
594
|
+
createdAt: now,
|
|
595
|
+
updatedAt: now
|
|
596
|
+
};
|
|
597
|
+
if (comment.body === "" || comment.anchor.quote.trim() === "") throw new Error("comment and anchor are required");
|
|
598
|
+
record.comments.push(comment);
|
|
599
|
+
record.actionItems.push({
|
|
600
|
+
id: randomUUID(),
|
|
601
|
+
requirementId: record.id,
|
|
602
|
+
sourceType: "comment",
|
|
603
|
+
sourceId: comment.id,
|
|
604
|
+
type: "reply",
|
|
605
|
+
assigneeRole: action.participant.role === "product" ? "engineering" : "product",
|
|
606
|
+
blocking: true,
|
|
607
|
+
status: "pending",
|
|
608
|
+
dueStage: record.stage,
|
|
609
|
+
createdAt: now,
|
|
610
|
+
updatedAt: now
|
|
611
|
+
});
|
|
612
|
+
this.persist();
|
|
613
|
+
const coordinator = this.coordinator;
|
|
614
|
+
if (coordinator !== void 0) {
|
|
615
|
+
const view = this.view(record.id);
|
|
616
|
+
coordinator.requestCommentReply({
|
|
617
|
+
requirement: view,
|
|
618
|
+
comment
|
|
619
|
+
}).then((sessionId) => {
|
|
620
|
+
comment.aiStatus = "running";
|
|
621
|
+
comment.aiSessionId = sessionId;
|
|
622
|
+
comment.updatedAt = Date.now();
|
|
623
|
+
this.persist();
|
|
624
|
+
}, (error) => this.markAiFailure(record.id, comment.id, error instanceof Error ? error.message : String(error)));
|
|
625
|
+
}
|
|
626
|
+
} else if (action.kind === "comment.reply") {
|
|
627
|
+
requireHuman(action.participant);
|
|
628
|
+
const comment = this.comment(record, action.commentId);
|
|
629
|
+
comment.replies.push({
|
|
630
|
+
id: randomUUID(),
|
|
631
|
+
author: action.participant,
|
|
632
|
+
body: action.body.trim(),
|
|
633
|
+
createdAt: now
|
|
634
|
+
});
|
|
635
|
+
comment.updatedAt = now;
|
|
636
|
+
this.persist();
|
|
637
|
+
} else if (action.kind === "comment.resolve") {
|
|
638
|
+
requireHuman(action.participant);
|
|
639
|
+
const comment = this.comment(record, action.commentId);
|
|
640
|
+
comment.status = "resolved";
|
|
641
|
+
comment.resolution = action.resolution;
|
|
642
|
+
comment.updatedAt = now;
|
|
643
|
+
record.actionItems.filter((task) => task.sourceId === comment.id && task.status === "pending").forEach((task) => {
|
|
644
|
+
task.status = "handled";
|
|
645
|
+
task.updatedAt = now;
|
|
646
|
+
});
|
|
647
|
+
this.persist();
|
|
648
|
+
} else if (action.kind === "patch.accept") {
|
|
649
|
+
requireHuman(action.participant);
|
|
650
|
+
const patch = record.patches.find((item) => item.id === action.patchId);
|
|
651
|
+
if (patch === void 0 || patch.status !== "pending") throw new Error("pending patch not found");
|
|
652
|
+
record.currentCommit = this.versions.save({
|
|
653
|
+
requirementId: record.id,
|
|
654
|
+
baseCommit: patch.baseCommit,
|
|
655
|
+
markdown: patch.proposedMarkdown,
|
|
656
|
+
participant: action.participant,
|
|
657
|
+
summary: action.summary
|
|
658
|
+
}).commit;
|
|
659
|
+
patch.status = "accepted";
|
|
660
|
+
record.updatedAt = now;
|
|
661
|
+
for (const id of patch.affectedReviewItemIds) {
|
|
662
|
+
const item = record.reviewItems.find((candidate) => candidate.id === id);
|
|
663
|
+
if (item !== void 0) {
|
|
664
|
+
item.status = "resolved";
|
|
665
|
+
item.updatedAt = now;
|
|
666
|
+
}
|
|
667
|
+
}
|
|
668
|
+
record.actionItems.filter((task) => task.sourceId === patch.id && task.status === "pending").forEach((task) => {
|
|
669
|
+
task.status = "handled";
|
|
670
|
+
task.updatedAt = now;
|
|
671
|
+
});
|
|
672
|
+
this.persist();
|
|
673
|
+
this.enqueueReview(record, action.participant, "change-review");
|
|
674
|
+
} else if (action.kind === "patch.reject") {
|
|
675
|
+
requireHuman(action.participant);
|
|
676
|
+
const patch = record.patches.find((item) => item.id === action.patchId);
|
|
677
|
+
if (patch === void 0) throw new Error("patch not found");
|
|
678
|
+
patch.status = "rejected";
|
|
679
|
+
this.persist();
|
|
680
|
+
} else if (action.kind === "decision.create") {
|
|
681
|
+
requireHuman(action.participant);
|
|
682
|
+
record.decisions.push({
|
|
683
|
+
id: randomUUID(),
|
|
684
|
+
requirementId: record.id,
|
|
685
|
+
commit: record.currentCommit,
|
|
686
|
+
question: action.question,
|
|
687
|
+
options: action.options,
|
|
688
|
+
decision: action.decision,
|
|
689
|
+
rationale: action.rationale,
|
|
690
|
+
confirmer: action.participant,
|
|
691
|
+
affectedSections: action.affectedSections,
|
|
692
|
+
affectedAcceptanceIds: action.affectedAcceptanceIds,
|
|
693
|
+
createdAt: now,
|
|
694
|
+
status: "active"
|
|
695
|
+
});
|
|
696
|
+
this.persist();
|
|
697
|
+
} else if (action.kind === "confirmation.create") {
|
|
698
|
+
requireHuman(action.participant);
|
|
699
|
+
if (action.participant.role !== action.role) throw new Error(`${action.role} role is required`);
|
|
700
|
+
record.confirmations.push({
|
|
701
|
+
id: randomUUID(),
|
|
702
|
+
requirementId: record.id,
|
|
703
|
+
commit: record.currentCommit,
|
|
704
|
+
role: action.role,
|
|
705
|
+
participant: action.participant,
|
|
706
|
+
scope: action.scope,
|
|
707
|
+
...action.scopeId === void 0 ? {} : { scopeId: action.scopeId },
|
|
708
|
+
status: "active",
|
|
709
|
+
createdAt: now
|
|
710
|
+
});
|
|
711
|
+
if (action.role === "product" && action.scope === "version") record.productConfirmedCommit = record.currentCommit;
|
|
712
|
+
if (action.role === "engineering" && action.scope === "version") record.jointConfirmedCommit = record.currentCommit;
|
|
713
|
+
this.persist();
|
|
714
|
+
} else if (action.kind === "stage.advance") {
|
|
715
|
+
requireHuman(action.participant);
|
|
716
|
+
advance(record, action.participant);
|
|
717
|
+
this.persist();
|
|
718
|
+
} else if (action.kind === "ready.generate") {
|
|
719
|
+
requireHuman(action.participant);
|
|
720
|
+
const checks = readiness(this.versions.read(record.id, record.currentCommit).markdown, record);
|
|
721
|
+
if (record.stage !== "joint-review" || checks.some((check) => !check.passed)) throw new Error("readiness gate is not satisfied");
|
|
722
|
+
if (!hasVersionConfirmation(record, "product") || !hasVersionConfirmation(record, "engineering")) throw new Error("current version needs product and engineering confirmation");
|
|
723
|
+
const markdown = readyMarkdown(this.view(record.id));
|
|
724
|
+
record.readyPackage = {
|
|
725
|
+
requirementId: record.id,
|
|
726
|
+
commit: record.currentCommit,
|
|
727
|
+
packageHash: createHash("sha256").update(markdown).digest("hex"),
|
|
728
|
+
generatedAt: now,
|
|
729
|
+
generatedBy: action.participant,
|
|
730
|
+
markdown
|
|
731
|
+
};
|
|
732
|
+
record.stage = "ready";
|
|
733
|
+
this.persist();
|
|
734
|
+
} else if (action.kind === "downstream.return") {
|
|
735
|
+
requireHuman(action.participant);
|
|
736
|
+
if (action.summary.trim() === "") throw new Error("downstream issue summary is required");
|
|
737
|
+
if (action.affectedSections.length === 0 && action.affectedAcceptanceIds.length === 0) throw new Error("downstream return requires an affected section or AC");
|
|
738
|
+
const item = {
|
|
739
|
+
id: randomUUID(),
|
|
740
|
+
requirementId: record.id,
|
|
741
|
+
commit: record.currentCommit,
|
|
742
|
+
reviewKind: "change-review",
|
|
743
|
+
type: "semantics",
|
|
744
|
+
severity: "blocking",
|
|
745
|
+
statement: action.summary.trim(),
|
|
746
|
+
evidence: action.evidence,
|
|
747
|
+
epistemicStatus: action.evidence.some((evidence) => evidence.accessible && evidence.version !== void 0) ? "FACT" : "TO_VERIFY",
|
|
748
|
+
impact: `下游发现影响 ${[...action.affectedSections, ...action.affectedAcceptanceIds].join("、")},需要重新澄清并确认。`,
|
|
749
|
+
question: "应如何修订受影响的需求语义或验收标准?",
|
|
750
|
+
affectedSections: [...new Set(action.affectedSections)],
|
|
751
|
+
affectedAcceptanceIds: [...new Set(action.affectedAcceptanceIds)],
|
|
752
|
+
ownerRole: "product",
|
|
753
|
+
status: "open",
|
|
754
|
+
createdAt: now,
|
|
755
|
+
updatedAt: now
|
|
756
|
+
};
|
|
757
|
+
record.reviewItems.push(item);
|
|
758
|
+
record.actionItems.push(actionForReview(item));
|
|
759
|
+
invalidateAffected(record, item.affectedSections, item.affectedAcceptanceIds);
|
|
760
|
+
delete record.readyPackage;
|
|
761
|
+
record.stage = "joint-review";
|
|
762
|
+
record.updatedAt = now;
|
|
763
|
+
this.persist();
|
|
764
|
+
this.enqueueReview(record, action.participant, "change-review");
|
|
765
|
+
}
|
|
766
|
+
return {
|
|
767
|
+
ok: true,
|
|
768
|
+
revision: this.state.revision,
|
|
769
|
+
requirement: this.view(record.id)
|
|
770
|
+
};
|
|
771
|
+
}
|
|
772
|
+
saveConflict(action) {
|
|
773
|
+
const record = this.record(action.requirementId);
|
|
774
|
+
const baseMarkdown = this.versions.read(record.id, action.baseCommit).markdown;
|
|
775
|
+
const currentMarkdown = this.versions.read(record.id, record.currentCommit).markdown;
|
|
776
|
+
return {
|
|
777
|
+
requirementId: record.id,
|
|
778
|
+
baseCommit: action.baseCommit,
|
|
779
|
+
currentCommit: record.currentCommit,
|
|
780
|
+
baseMarkdown,
|
|
781
|
+
currentMarkdown,
|
|
782
|
+
draftMarkdown: action.markdown,
|
|
783
|
+
baseToCurrentDiff: textDiff(baseMarkdown, currentMarkdown),
|
|
784
|
+
baseToDraftDiff: textDiff(baseMarkdown, action.markdown)
|
|
785
|
+
};
|
|
786
|
+
}
|
|
787
|
+
enqueueReview(record, participant, kind) {
|
|
788
|
+
const now = Date.now();
|
|
789
|
+
const run = {
|
|
790
|
+
id: randomUUID(),
|
|
791
|
+
requirementId: record.id,
|
|
792
|
+
commit: record.currentCommit,
|
|
793
|
+
kind,
|
|
794
|
+
status: "queued",
|
|
795
|
+
requestedBy: participant,
|
|
796
|
+
createdAt: now,
|
|
797
|
+
updatedAt: now
|
|
798
|
+
};
|
|
799
|
+
record.aiRuns.push(run);
|
|
800
|
+
this.persist();
|
|
801
|
+
const coordinator = this.coordinator;
|
|
802
|
+
if (coordinator === void 0) {
|
|
803
|
+
this.markAiFailure(record.id, run.id, "AI coordinator unavailable");
|
|
804
|
+
return;
|
|
805
|
+
}
|
|
806
|
+
const view = this.view(record.id);
|
|
807
|
+
coordinator.requestReview({
|
|
808
|
+
requirement: view,
|
|
809
|
+
run
|
|
810
|
+
}).then((sessionId) => {
|
|
811
|
+
run.status = "running";
|
|
812
|
+
run.sessionId = sessionId;
|
|
813
|
+
run.updatedAt = Date.now();
|
|
814
|
+
this.persist();
|
|
815
|
+
}, (error) => this.markAiFailure(record.id, run.id, error instanceof Error ? error.message : String(error)));
|
|
816
|
+
}
|
|
817
|
+
record(id) {
|
|
818
|
+
const value = this.state.requirements.find((item) => item.id === id);
|
|
819
|
+
if (value === void 0) throw new Error("requirement not found");
|
|
820
|
+
return value;
|
|
821
|
+
}
|
|
822
|
+
comment(record, id) {
|
|
823
|
+
const value = record.comments.find((item) => item.id === id);
|
|
824
|
+
if (value === void 0) throw new Error("comment not found");
|
|
825
|
+
return value;
|
|
826
|
+
}
|
|
827
|
+
persist() {
|
|
828
|
+
this.state.revision += 1;
|
|
829
|
+
mkdirSync(dirname(this.eventPath), {
|
|
830
|
+
recursive: true,
|
|
831
|
+
mode: 448
|
|
832
|
+
});
|
|
833
|
+
const tmp = `${this.eventPath}.tmp`;
|
|
834
|
+
writeFileSync(tmp, JSON.stringify(this.state, null, 2), { mode: 384 });
|
|
835
|
+
renameSync(tmp, this.eventPath);
|
|
836
|
+
for (const listener of this.listeners) listener();
|
|
837
|
+
}
|
|
838
|
+
load() {
|
|
839
|
+
try {
|
|
840
|
+
const value = JSON.parse(readFileSync(this.eventPath, "utf8"));
|
|
841
|
+
if (value.schemaVersion === 2) {
|
|
842
|
+
value.participants ??= [];
|
|
843
|
+
return value;
|
|
844
|
+
}
|
|
845
|
+
} catch {}
|
|
846
|
+
return emptyState();
|
|
847
|
+
}
|
|
848
|
+
};
|
|
849
|
+
function sourceParticipantId(record, item) {
|
|
850
|
+
if (item.sourceType === "comment") return record.comments.find((value) => value.id === item.sourceId)?.author.participantId;
|
|
851
|
+
if (item.sourceType === "patch") return record.patches.find((value) => value.id === item.sourceId)?.createdBy.participantId;
|
|
852
|
+
if (item.sourceType === "decision") return record.decisions.find((value) => value.id === item.sourceId)?.confirmer.participantId;
|
|
853
|
+
if (item.sourceType === "confirmation") return record.confirmations.find((value) => value.id === item.sourceId)?.participant.participantId;
|
|
854
|
+
return record.reviewItems.find((value) => value.id === item.sourceId)?.response?.participant.participantId;
|
|
855
|
+
}
|
|
856
|
+
function actionTarget(item) {
|
|
857
|
+
return {
|
|
858
|
+
tab: {
|
|
859
|
+
"review-item": "review",
|
|
860
|
+
comment: "discussion",
|
|
861
|
+
patch: "patches",
|
|
862
|
+
decision: "decisions",
|
|
863
|
+
confirmation: "ready"
|
|
864
|
+
}[item.sourceType],
|
|
865
|
+
objectId: item.sourceId
|
|
866
|
+
};
|
|
867
|
+
}
|
|
868
|
+
function textDiff(before, after) {
|
|
869
|
+
if (before === after) return "";
|
|
870
|
+
const left = before.split("\n");
|
|
871
|
+
const right = after.split("\n");
|
|
872
|
+
let start = 0;
|
|
873
|
+
while (start < left.length && start < right.length && left[start] === right[start]) start += 1;
|
|
874
|
+
let leftEnd = left.length - 1;
|
|
875
|
+
let rightEnd = right.length - 1;
|
|
876
|
+
while (leftEnd >= start && rightEnd >= start && left[leftEnd] === right[rightEnd]) {
|
|
877
|
+
leftEnd -= 1;
|
|
878
|
+
rightEnd -= 1;
|
|
879
|
+
}
|
|
880
|
+
const contextStart = Math.max(0, start - 2);
|
|
881
|
+
const contextLeftEnd = Math.min(left.length - 1, leftEnd + 2);
|
|
882
|
+
const contextRightEnd = Math.min(right.length - 1, rightEnd + 2);
|
|
883
|
+
return [
|
|
884
|
+
`@@ -${contextStart + 1},${contextLeftEnd - contextStart + 1} +${contextStart + 1},${contextRightEnd - contextStart + 1} @@`,
|
|
885
|
+
...left.slice(contextStart, start).map((line) => ` ${line}`),
|
|
886
|
+
...left.slice(start, leftEnd + 1).map((line) => `-${line}`),
|
|
887
|
+
...right.slice(start, rightEnd + 1).map((line) => `+${line}`),
|
|
888
|
+
...right.slice(rightEnd + 1, contextRightEnd + 1).map((line) => ` ${line}`)
|
|
889
|
+
].join("\n");
|
|
890
|
+
}
|
|
891
|
+
function assertChineseFeedback(...values) {
|
|
892
|
+
if (values.some((value) => !/[\u3400-\u9fff]/.test(value))) throw new Error("AI 评审反馈必须使用中文");
|
|
893
|
+
}
|
|
894
|
+
function requireHuman(participant) {
|
|
895
|
+
if (participant.kind !== "human") throw new Error("human participant is required");
|
|
896
|
+
}
|
|
897
|
+
function actionForReview(item) {
|
|
898
|
+
const now = Date.now();
|
|
899
|
+
return {
|
|
900
|
+
id: randomUUID(),
|
|
901
|
+
requirementId: item.requirementId,
|
|
902
|
+
sourceType: "review-item",
|
|
903
|
+
sourceId: item.id,
|
|
904
|
+
type: "reply",
|
|
905
|
+
assigneeRole: item.ownerRole,
|
|
906
|
+
blocking: item.severity === "blocking",
|
|
907
|
+
status: "pending",
|
|
908
|
+
dueStage: item.reviewKind.startsWith("product") ? "product-review" : "joint-review",
|
|
909
|
+
createdAt: now,
|
|
910
|
+
updatedAt: now
|
|
911
|
+
};
|
|
912
|
+
}
|
|
913
|
+
function hasVersionConfirmation(record, role) {
|
|
914
|
+
return record.confirmations.some((item) => item.role === role && item.scope === "version" && item.commit === record.currentCommit && item.status === "active");
|
|
915
|
+
}
|
|
916
|
+
function advance(record, participant) {
|
|
917
|
+
if (record.stage === "product-review") {
|
|
918
|
+
if (record.reviewItems.some((item) => item.severity === "blocking" && ![
|
|
919
|
+
"resolved",
|
|
920
|
+
"non-blocking-verify",
|
|
921
|
+
"joint-review"
|
|
922
|
+
].includes(item.status))) throw new Error("product blocking review items remain");
|
|
923
|
+
if (!record.aiRuns.some((run) => run.kind === "product-second" && run.commit === record.currentCommit && run.status === "completed")) throw new Error("product second review is required");
|
|
924
|
+
record.stage = "product-confirmation";
|
|
925
|
+
return;
|
|
926
|
+
}
|
|
927
|
+
if (record.stage === "product-confirmation") {
|
|
928
|
+
if (participant.role !== "product" || !hasVersionConfirmation(record, "product")) throw new Error("product must confirm the current version");
|
|
929
|
+
record.stage = "joint-review";
|
|
930
|
+
return;
|
|
931
|
+
}
|
|
932
|
+
throw new Error("stage cannot advance directly");
|
|
933
|
+
}
|
|
934
|
+
function sections(markdown) {
|
|
935
|
+
const result = /* @__PURE__ */ new Map();
|
|
936
|
+
let heading = "";
|
|
937
|
+
for (const line of markdown.split("\n")) if (/^##\s+/.test(line)) {
|
|
938
|
+
heading = line.replace(/^##\s+/, "").trim();
|
|
939
|
+
result.set(heading, "");
|
|
940
|
+
} else if (heading) result.set(heading, `${result.get(heading) ?? ""}\n${line}`);
|
|
941
|
+
return result;
|
|
942
|
+
}
|
|
943
|
+
function acceptance(markdown) {
|
|
944
|
+
const result = /* @__PURE__ */ new Map();
|
|
945
|
+
for (const match of markdown.matchAll(/\*\*(AC-[A-Za-z0-9-]+)\*\*\s*[::]\s*(.+)/g)) result.set(match[1], match[2].trim());
|
|
946
|
+
return result;
|
|
947
|
+
}
|
|
948
|
+
function changedScopes(before, after) {
|
|
949
|
+
const a = sections(before);
|
|
950
|
+
const b = sections(after);
|
|
951
|
+
const sectionNames = /* @__PURE__ */ new Set([...a.keys(), ...b.keys()]);
|
|
952
|
+
const acA = acceptance(before);
|
|
953
|
+
const acB = acceptance(after);
|
|
954
|
+
const acNames = /* @__PURE__ */ new Set([...acA.keys(), ...acB.keys()]);
|
|
955
|
+
return {
|
|
956
|
+
sections: [...sectionNames].filter((key) => a.get(key) !== b.get(key)),
|
|
957
|
+
acceptanceIds: [...acNames].filter((key) => acA.get(key) !== acB.get(key))
|
|
958
|
+
};
|
|
959
|
+
}
|
|
960
|
+
function intersects(left, right) {
|
|
961
|
+
return left.some((item) => right.includes(item));
|
|
962
|
+
}
|
|
963
|
+
function invalidateAffected(record, changedSections, changedAcceptanceIds) {
|
|
964
|
+
for (const confirmation of record.confirmations) {
|
|
965
|
+
if (confirmation.status !== "active") continue;
|
|
966
|
+
if (confirmation.scope === "version" || confirmation.scope === "section" && confirmation.scopeId !== void 0 && changedSections.includes(confirmation.scopeId) || confirmation.scope === "acceptance-criterion" && confirmation.scopeId !== void 0 && changedAcceptanceIds.includes(confirmation.scopeId)) {
|
|
967
|
+
confirmation.status = "invalidated";
|
|
968
|
+
record.actionItems.push({
|
|
969
|
+
id: randomUUID(),
|
|
970
|
+
requirementId: record.id,
|
|
971
|
+
sourceType: "confirmation",
|
|
972
|
+
sourceId: confirmation.id,
|
|
973
|
+
type: "reconfirm",
|
|
974
|
+
assigneeRole: confirmation.role,
|
|
975
|
+
blocking: true,
|
|
976
|
+
status: "pending",
|
|
977
|
+
dueStage: record.stage,
|
|
978
|
+
createdAt: Date.now(),
|
|
979
|
+
updatedAt: Date.now()
|
|
980
|
+
});
|
|
981
|
+
}
|
|
982
|
+
}
|
|
983
|
+
record.reviewItems.filter((item) => item.status === "resolved" && (intersects(item.affectedSections, changedSections) || intersects(item.affectedAcceptanceIds, changedAcceptanceIds))).forEach((item) => {
|
|
984
|
+
item.status = "invalidated";
|
|
985
|
+
item.updatedAt = Date.now();
|
|
986
|
+
});
|
|
987
|
+
record.decisions.filter((item) => item.status === "active" && (intersects(item.affectedSections, changedSections) || intersects(item.affectedAcceptanceIds, changedAcceptanceIds))).forEach((item) => {
|
|
988
|
+
item.status = "invalidated";
|
|
989
|
+
});
|
|
990
|
+
}
|
|
991
|
+
function readiness(markdown, record) {
|
|
992
|
+
const sectionMap = sections(markdown);
|
|
993
|
+
const ac = acceptance(markdown);
|
|
994
|
+
const meaningful = (name) => {
|
|
995
|
+
const value = sectionMap.get(name)?.replace(/<!--.*?-->/gs, "").trim() ?? "";
|
|
996
|
+
return value.length >= 12 && !/待澄清|待补充|TODO/i.test(value);
|
|
997
|
+
};
|
|
998
|
+
const blockers = record.reviewItems.filter((item) => item.severity === "blocking" && !["resolved", "non-blocking-verify"].includes(item.status)).map((item) => item.statement);
|
|
999
|
+
return [
|
|
1000
|
+
{
|
|
1001
|
+
key: "goal",
|
|
1002
|
+
passed: meaningful("目标与用户结果"),
|
|
1003
|
+
reasons: meaningful("目标与用户结果") ? [] : ["缺少可观察的目标与用户结果"]
|
|
1004
|
+
},
|
|
1005
|
+
{
|
|
1006
|
+
key: "acceptance",
|
|
1007
|
+
passed: ac.size > 0 && [...ac.values()].every((value) => !/待澄清|待补充|TODO/i.test(value)),
|
|
1008
|
+
reasons: ac.size === 0 ? ["缺少稳定 AC ID 与可判定结果"] : [...ac.values()].some((value) => /待澄清|待补充|TODO/i.test(value)) ? ["验收标准仍含占位内容"] : []
|
|
1009
|
+
},
|
|
1010
|
+
{
|
|
1011
|
+
key: "scope",
|
|
1012
|
+
passed: meaningful("范围与非范围"),
|
|
1013
|
+
reasons: meaningful("范围与非范围") ? [] : ["范围与非范围不完整"]
|
|
1014
|
+
},
|
|
1015
|
+
{
|
|
1016
|
+
key: "semantics",
|
|
1017
|
+
passed: meaningful("业务术语与规则"),
|
|
1018
|
+
reasons: meaningful("业务术语与规则") ? [] : ["关键术语和规则不完整"]
|
|
1019
|
+
},
|
|
1020
|
+
{
|
|
1021
|
+
key: "evidence",
|
|
1022
|
+
passed: record.sources.every((source) => source.accessStatus !== "missing") && blockers.length === 0,
|
|
1023
|
+
reasons: [...record.sources.filter((source) => source.accessStatus === "missing").map((source) => `来源不可访问:${source.label}`), ...blockers]
|
|
1024
|
+
},
|
|
1025
|
+
{
|
|
1026
|
+
key: "test-constraints",
|
|
1027
|
+
passed: meaningful("测试约束"),
|
|
1028
|
+
reasons: meaningful("测试约束") ? [] : ["测试环境、账号、权限或 fixture 约束不完整"]
|
|
1029
|
+
}
|
|
1030
|
+
];
|
|
1031
|
+
}
|
|
1032
|
+
function readyMarkdown(view) {
|
|
1033
|
+
const open = view.reviewItems.filter((item) => item.status === "non-blocking-verify");
|
|
1034
|
+
return [
|
|
1035
|
+
`# Ready Spec:${view.title}`,
|
|
1036
|
+
"",
|
|
1037
|
+
`- 需求 ID:${view.id}`,
|
|
1038
|
+
`- Commit:${view.currentCommit}`,
|
|
1039
|
+
`- 产品确认:${view.confirmations.filter((item) => item.role === "product" && item.status === "active").map((item) => item.participant.nickname).join("、")}`,
|
|
1040
|
+
`- 研发确认:${view.confirmations.filter((item) => item.role === "engineering" && item.status === "active").map((item) => item.participant.nickname).join("、")}`,
|
|
1041
|
+
"",
|
|
1042
|
+
view.version.markdown,
|
|
1043
|
+
"",
|
|
1044
|
+
"## Decisions",
|
|
1045
|
+
...view.decisions.filter((item) => item.status === "active").map((item) => `- ${item.question}:${item.decision}(${item.rationale})`),
|
|
1046
|
+
"",
|
|
1047
|
+
"## 证据来源与版本",
|
|
1048
|
+
...view.sources.map((source) => `- [${source.accessStatus}] ${source.label}${source.stableId ? ` — ${source.stableId}` : ""}${source.version ? ` @ ${source.version}` : ""}`),
|
|
1049
|
+
"",
|
|
1050
|
+
"## 非阻塞 Open Questions",
|
|
1051
|
+
...open.map((item) => `- ${item.question};负责人:${item.ownerParticipantId ?? item.ownerRole};影响:${item.impact}`),
|
|
1052
|
+
""
|
|
1053
|
+
].join("\n");
|
|
1054
|
+
}
|
|
1055
|
+
//#endregion
|
|
1056
|
+
//#region src/review-context.ts
|
|
1057
|
+
const MCP_SERVER = /^[A-Za-z0-9_-]{1,32}$/;
|
|
1058
|
+
var ReviewContextCatalog = class {
|
|
1059
|
+
defaults;
|
|
1060
|
+
workspaces = /* @__PURE__ */ new Map();
|
|
1061
|
+
constructor(config = {}) {
|
|
1062
|
+
this.defaults = normalizeResources(config.defaultContext);
|
|
1063
|
+
for (const value of config.workspaces ?? []) {
|
|
1064
|
+
const workspaceId = value.workspaceId.trim();
|
|
1065
|
+
if (workspaceId === "") throw new Error("review workspace id is required");
|
|
1066
|
+
if (this.workspaces.has(workspaceId)) throw new Error(`duplicate review workspace id: ${workspaceId}`);
|
|
1067
|
+
this.workspaces.set(workspaceId, {
|
|
1068
|
+
...normalizeResources(value),
|
|
1069
|
+
workspaceId
|
|
1070
|
+
});
|
|
1071
|
+
}
|
|
1072
|
+
}
|
|
1073
|
+
workspaceIds() {
|
|
1074
|
+
return [...this.workspaces.keys()];
|
|
1075
|
+
}
|
|
1076
|
+
resolve(workspaceId) {
|
|
1077
|
+
if (workspaceId === void 0 || workspaceId.trim() === "") throw new Error("review workspace is required");
|
|
1078
|
+
const resources = normalizeResources(this.workspaces.get(workspaceId));
|
|
1079
|
+
return {
|
|
1080
|
+
workspaceId,
|
|
1081
|
+
skills: unique([...this.defaults.skills, ...resources.skills]),
|
|
1082
|
+
mcpServers: unique([...this.defaults.mcpServers, ...resources.mcpServers]),
|
|
1083
|
+
documentPaths: unique([...this.defaults.documentPaths, ...resources.documentPaths]),
|
|
1084
|
+
...resources.agentPreset ?? this.defaults.agentPreset ? { agentPreset: resources.agentPreset ?? this.defaults.agentPreset } : {}
|
|
1085
|
+
};
|
|
1086
|
+
}
|
|
1087
|
+
};
|
|
1088
|
+
function reviewContextPrompt(context) {
|
|
1089
|
+
const rows = ["## 本次审核必须使用的上下文", `DSH 工作区:\`${context.workspaceId}\`。当前 AI session 必须挂载该工作区,不得创建未分组会话。`];
|
|
1090
|
+
if (context.skills.length > 0) rows.push(`Skills:先调用 skill 工具加载 ${context.skills.map((value) => `\`${value}\``).join("、")},读取完整说明后再分析。`);
|
|
1091
|
+
if (context.mcpServers.length > 0) rows.push(`MCP:需要事实查询时优先使用 ${context.mcpServers.map((value) => `\`mcp__${value}__*\``).join("、")} namespace 下的工具。`);
|
|
1092
|
+
if (context.documentPaths.length > 0) rows.push("本地参考文档:分析前先读取与本需求相关的路径;相对路径基于当前 DSH 工作区根目录,引用时必须带具体文件路径和可识别版本。", ...context.documentPaths.map((value) => `- \`${value}\``));
|
|
1093
|
+
if (context.skills.length === 0 && context.mcpServers.length === 0 && context.documentPaths.length === 0) rows.push("当前未配置额外 Skill、MCP 或本地参考文档。");
|
|
1094
|
+
rows.push("任何已配置资源若在当前 Agent Preset 中不可用、无权限或读取失败,必须在结论中明确指出该资源并使用 TO_VERIFY;不得假装已经查询或把不可访问内容写成 FACT。");
|
|
1095
|
+
return rows.join("\n");
|
|
1096
|
+
}
|
|
1097
|
+
function normalizeResources(value) {
|
|
1098
|
+
const skills = cleanList(value?.skills);
|
|
1099
|
+
const mcpServers = cleanList(value?.mcpServers);
|
|
1100
|
+
for (const server of mcpServers) if (!MCP_SERVER.test(server)) throw new Error(`invalid MCP server name: ${server}`);
|
|
1101
|
+
const documentPaths = unique(cleanList(value?.documentPaths).map(resolveDocumentPath));
|
|
1102
|
+
const agentPreset = value?.agentPreset?.trim();
|
|
1103
|
+
return {
|
|
1104
|
+
skills,
|
|
1105
|
+
mcpServers,
|
|
1106
|
+
documentPaths,
|
|
1107
|
+
...agentPreset ? { agentPreset } : {}
|
|
1108
|
+
};
|
|
1109
|
+
}
|
|
1110
|
+
function cleanList(values) {
|
|
1111
|
+
return unique((values ?? []).map((value) => value.trim()).filter(Boolean));
|
|
1112
|
+
}
|
|
1113
|
+
function unique(values) {
|
|
1114
|
+
return [...new Set(values)];
|
|
1115
|
+
}
|
|
1116
|
+
function resolveDocumentPath(value) {
|
|
1117
|
+
if (value === "~") return homedir();
|
|
1118
|
+
if (value.startsWith("~/") || value.startsWith("~\\")) return normalize(resolve(homedir(), value.slice(2)));
|
|
1119
|
+
return normalize(value);
|
|
1120
|
+
}
|
|
1121
|
+
//#endregion
|
|
1122
|
+
//#region src/review-runtime.ts
|
|
1123
|
+
function request(payload) {
|
|
1124
|
+
return {
|
|
1125
|
+
rpcId: `spec-collab-${crypto.randomUUID()}`,
|
|
1126
|
+
payload
|
|
1127
|
+
};
|
|
1128
|
+
}
|
|
1129
|
+
function failure(error) {
|
|
1130
|
+
return /* @__PURE__ */ new Error(`${error.code}: ${error.message}`);
|
|
1131
|
+
}
|
|
1132
|
+
var DshReviewCoordinator = class {
|
|
1133
|
+
api;
|
|
1134
|
+
contexts;
|
|
1135
|
+
constructor(api, contexts = new ReviewContextCatalog()) {
|
|
1136
|
+
this.api = api;
|
|
1137
|
+
this.contexts = contexts;
|
|
1138
|
+
}
|
|
1139
|
+
async reviewWorkspaces() {
|
|
1140
|
+
const listed = await this.api.workspace.list(request({}));
|
|
1141
|
+
if (!listed.result.ok) throw failure(listed.result.error);
|
|
1142
|
+
return listed.result.value.items.map((item) => ({
|
|
1143
|
+
workspaceId: item.workspaceId,
|
|
1144
|
+
title: item.title,
|
|
1145
|
+
path: item.path
|
|
1146
|
+
}));
|
|
1147
|
+
}
|
|
1148
|
+
async assertWorkspaceAvailable(workspaceId) {
|
|
1149
|
+
if (!(await this.reviewWorkspaces()).some((item) => item.workspaceId === workspaceId)) throw new Error(`workspace not found: ${workspaceId}`);
|
|
1150
|
+
}
|
|
1151
|
+
requestReview(input) {
|
|
1152
|
+
const context = this.contexts.resolve(input.requirement.workspaceId);
|
|
1153
|
+
return this.launch(`Spec ${input.run.kind}: ${input.requirement.title}`, reviewPrompt(input.requirement, input.run, context), context.workspaceId, context.agentPreset);
|
|
1154
|
+
}
|
|
1155
|
+
requestCommentReply(input) {
|
|
1156
|
+
const context = this.contexts.resolve(input.requirement.workspaceId);
|
|
1157
|
+
return this.launch(`Spec comment analysis: ${input.requirement.title}`, commentPrompt(input.requirement, input.comment, context), context.workspaceId, context.agentPreset);
|
|
1158
|
+
}
|
|
1159
|
+
async conversation(sessionId) {
|
|
1160
|
+
const history = await this.api.sessions.history(request({ sessionId }));
|
|
1161
|
+
if (!history.result.ok) throw failure(history.result.error);
|
|
1162
|
+
const rows = [];
|
|
1163
|
+
let skippedOrchestrationPrompt = false;
|
|
1164
|
+
for (const entry of history.result.value.events) {
|
|
1165
|
+
if (entry.event.type !== "user/message" && entry.event.type !== "assistant/message") continue;
|
|
1166
|
+
if (entry.event.type === "user/message" && !skippedOrchestrationPrompt) {
|
|
1167
|
+
skippedOrchestrationPrompt = true;
|
|
1168
|
+
continue;
|
|
1169
|
+
}
|
|
1170
|
+
const value = entry.event.data;
|
|
1171
|
+
const message = isObject(value) && "message" in value ? value.message : value;
|
|
1172
|
+
let messageText = collectText(isObject(message) && "content" in message ? message.content : message).join("\n").trim();
|
|
1173
|
+
if (entry.event.type === "user/message") {
|
|
1174
|
+
if (!messageText.startsWith("请使用简体中文回答以下追问,并继续遵守当前 Spec 审核任务的证据、权限和结构化回写约束。")) continue;
|
|
1175
|
+
messageText = messageText.slice(46).trim();
|
|
1176
|
+
}
|
|
1177
|
+
if (messageText !== "") rows.push({
|
|
1178
|
+
role: entry.event.type === "user/message" ? "user" : "assistant",
|
|
1179
|
+
text: messageText
|
|
1180
|
+
});
|
|
1181
|
+
}
|
|
1182
|
+
return rows;
|
|
1183
|
+
}
|
|
1184
|
+
async followUp(sessionId, text) {
|
|
1185
|
+
const content = text.trim();
|
|
1186
|
+
if (content === "") throw new Error("追问内容不能为空");
|
|
1187
|
+
const prompted = await this.api.sessions.prompt(request({
|
|
1188
|
+
sessionId,
|
|
1189
|
+
mode: "queue",
|
|
1190
|
+
content: [{
|
|
1191
|
+
type: "text",
|
|
1192
|
+
text: `请使用简体中文回答以下追问,并继续遵守当前 Spec 审核任务的证据、权限和结构化回写约束。\n\n${content}`
|
|
1193
|
+
}]
|
|
1194
|
+
}));
|
|
1195
|
+
if (!prompted.result.ok) throw failure(prompted.result.error);
|
|
1196
|
+
}
|
|
1197
|
+
async launch(title, promptText, workspaceId, agentPreset) {
|
|
1198
|
+
await this.assertWorkspaceAvailable(workspaceId);
|
|
1199
|
+
if (agentPreset !== void 0) {
|
|
1200
|
+
const presets = await this.api.agentPresets.list(request({}));
|
|
1201
|
+
if (!presets.result.ok) throw failure(presets.result.error);
|
|
1202
|
+
const preset = presets.result.value.presets.find((item) => item.id === agentPreset);
|
|
1203
|
+
if (preset === void 0 || preset.broken !== void 0) throw new Error("agent preset is unavailable");
|
|
1204
|
+
}
|
|
1205
|
+
const created = await this.api.sessions.create(request({
|
|
1206
|
+
workspaceId,
|
|
1207
|
+
...agentPreset === void 0 ? {} : { agentPreset }
|
|
1208
|
+
}));
|
|
1209
|
+
if (!created.result.ok) throw failure(created.result.error);
|
|
1210
|
+
const sessionId = created.result.value.sessionId;
|
|
1211
|
+
const renamed = await this.api.sessions.rename(request({
|
|
1212
|
+
sessionId,
|
|
1213
|
+
title
|
|
1214
|
+
}));
|
|
1215
|
+
if (!renamed.result.ok) throw failure(renamed.result.error);
|
|
1216
|
+
const prompted = await this.api.sessions.prompt(request({
|
|
1217
|
+
sessionId,
|
|
1218
|
+
mode: "queue",
|
|
1219
|
+
content: [{
|
|
1220
|
+
type: "text",
|
|
1221
|
+
text: promptText.replaceAll("{{SESSION_ID}}", sessionId)
|
|
1222
|
+
}]
|
|
1223
|
+
}));
|
|
1224
|
+
if (!prompted.result.ok) throw failure(prompted.result.error);
|
|
1225
|
+
return sessionId;
|
|
1226
|
+
}
|
|
1227
|
+
};
|
|
1228
|
+
function isObject(value) {
|
|
1229
|
+
return typeof value === "object" && value !== null;
|
|
1230
|
+
}
|
|
1231
|
+
function collectText(value) {
|
|
1232
|
+
if (Array.isArray(value)) return value.flatMap(collectText);
|
|
1233
|
+
if (!isObject(value)) return [];
|
|
1234
|
+
if (value.type === "text" && typeof value.text === "string") return [value.text];
|
|
1235
|
+
return "content" in value ? collectText(value.content) : [];
|
|
1236
|
+
}
|
|
1237
|
+
function common(requirement, context) {
|
|
1238
|
+
return [
|
|
1239
|
+
`Requirement ID: ${requirement.id}`,
|
|
1240
|
+
`Pinned commit: ${requirement.currentCommit}`,
|
|
1241
|
+
"",
|
|
1242
|
+
reviewContextPrompt(context),
|
|
1243
|
+
"",
|
|
1244
|
+
"所有面向用户的输出必须使用简体中文,包括 Review Item 的陈述、影响、问题、成熟度总结、候选 patch 摘要以及评论分析回复。仅保留代码标识、路径、commit SHA、AC ID、FACT / INFERENCE / ASSUMPTION / TO_VERIFY 等固定枚举为原文。",
|
|
1245
|
+
"You are a review worker for a requirements clarification product. You must not implement code, generate downstream test delivery, create worktrees, deploy, or mark the requirement Ready. AI output is proposal data only and requires human confirmation.",
|
|
1246
|
+
"A FACT must cite an accessible, version-pinned source. If evidence is unavailable, use TO_VERIFY; never invent historical or implementation conflicts.",
|
|
1247
|
+
"Use spec_read to retrieve the exact current data. Do not modify files directly.",
|
|
1248
|
+
"每个 Review Item 必须给出至少三个具体、互斥或有明确取舍差异的 recommendedOptions,供用户快速选择;不得只重复“接受、拒绝、待验证”这类通用状态。"
|
|
1249
|
+
].join("\n");
|
|
1250
|
+
}
|
|
1251
|
+
function reviewPrompt(requirement, run, context) {
|
|
1252
|
+
return [
|
|
1253
|
+
common(requirement, context),
|
|
1254
|
+
`Review run ID: ${run.id}`,
|
|
1255
|
+
`Review kind: ${run.kind}`,
|
|
1256
|
+
`AI session ID: {{SESSION_ID}}`,
|
|
1257
|
+
"",
|
|
1258
|
+
{
|
|
1259
|
+
"product-first": "Perform the initial product review across goal, evidence, history-conflict, current-implementation, scope, semantics, completeness, acceptance, and risk. Submit structured findings with spec_submit_review. If the draft needs changes, also submit a candidate patch with spec_propose_patch.",
|
|
1260
|
+
"product-second": "Review product responses against their original Review Items. Do not close vague answers. Submit remaining/new findings with spec_submit_review and a reviewable candidate patch with spec_propose_patch.",
|
|
1261
|
+
"engineering-precheck": "Read the product-confirmed Spec and inspect relevant current code/history available in the workspace. Find implementation fact conflicts, affected entries/roles/states, technical ambiguity, compatibility/permission/data boundaries, and unverifiable acceptance criteria. Submit with spec_submit_review and propose a patch only when needed.",
|
|
1262
|
+
"change-review": "Review only the latest saved commit against its parent. Identify materiality, affected sections/ACs, confirmations or decisions that need reconfirmation, and new conflicts. Submit with spec_submit_review; propose a patch only when needed."
|
|
1263
|
+
}[run.kind]
|
|
1264
|
+
].join("\n");
|
|
1265
|
+
}
|
|
1266
|
+
function commentPrompt(requirement, comment, context) {
|
|
1267
|
+
return [
|
|
1268
|
+
common(requirement, context),
|
|
1269
|
+
`Comment ID: ${comment.id}`,
|
|
1270
|
+
`Anchor quote: ${comment.anchor.quote}`,
|
|
1271
|
+
`Human comment: ${comment.body}`,
|
|
1272
|
+
`AI session ID: {{SESSION_ID}}`,
|
|
1273
|
+
"",
|
|
1274
|
+
"Analyze this substantive comment. First query any code/document facts you can obtain. Then use spec_reply exactly once with your understanding, versioned evidence or TO_VERIFY status, affected sections/ACs, and recommended disposition. Do not silently modify the Spec or choose between conflicting product and engineering positions."
|
|
1275
|
+
].join("\n");
|
|
1276
|
+
}
|
|
1277
|
+
//#endregion
|
|
1278
|
+
//#region src/routes.ts
|
|
1279
|
+
const BODY_LIMIT = 2 * 1024 * 1024;
|
|
1280
|
+
const HEARTBEAT_MS = 15e3;
|
|
1281
|
+
function json(res, status, body) {
|
|
1282
|
+
res.writeHead(status, {
|
|
1283
|
+
"content-type": "application/json; charset=utf-8",
|
|
1284
|
+
"cache-control": "no-store",
|
|
1285
|
+
"referrer-policy": "no-referrer"
|
|
1286
|
+
});
|
|
1287
|
+
res.end(JSON.stringify(body));
|
|
1288
|
+
}
|
|
1289
|
+
function trusted(req) {
|
|
1290
|
+
const remote = req.socket.remoteAddress;
|
|
1291
|
+
if (!(remote === "127.0.0.1" || remote === "::1" || remote === "::ffff:127.0.0.1")) return false;
|
|
1292
|
+
if (req.headers["sec-fetch-site"] === "cross-site") return false;
|
|
1293
|
+
const origin = req.headers.origin;
|
|
1294
|
+
if (origin === void 0) return req.headers["sec-fetch-site"] === "same-origin";
|
|
1295
|
+
try {
|
|
1296
|
+
return new URL(origin).host === req.headers.host;
|
|
1297
|
+
} catch {
|
|
1298
|
+
return false;
|
|
1299
|
+
}
|
|
1300
|
+
}
|
|
1301
|
+
async function readJson(req) {
|
|
1302
|
+
const chunks = [];
|
|
1303
|
+
let size = 0;
|
|
1304
|
+
for await (const chunk of req) {
|
|
1305
|
+
const buffer = chunk;
|
|
1306
|
+
size += buffer.length;
|
|
1307
|
+
if (size > BODY_LIMIT) throw new Error("body-too-large");
|
|
1308
|
+
chunks.push(buffer);
|
|
1309
|
+
}
|
|
1310
|
+
return JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
1311
|
+
}
|
|
1312
|
+
function makeRoutes(engine, coordinator) {
|
|
1313
|
+
const guard = (req, res) => {
|
|
1314
|
+
if (trusted(req)) return true;
|
|
1315
|
+
json(res, 403, {
|
|
1316
|
+
ok: false,
|
|
1317
|
+
error: "forbidden"
|
|
1318
|
+
});
|
|
1319
|
+
return false;
|
|
1320
|
+
};
|
|
1321
|
+
return [
|
|
1322
|
+
{
|
|
1323
|
+
kind: "exact",
|
|
1324
|
+
path: `${API_PREFIX}/state`,
|
|
1325
|
+
handler: (req, res) => {
|
|
1326
|
+
if (req.method !== "GET") return json(res, 405, {
|
|
1327
|
+
ok: false,
|
|
1328
|
+
error: "method-not-allowed"
|
|
1329
|
+
});
|
|
1330
|
+
if (!guard(req, res)) return;
|
|
1331
|
+
const state = engine.snapshot();
|
|
1332
|
+
json(res, 200, {
|
|
1333
|
+
revision: state.revision,
|
|
1334
|
+
participants: state.participants,
|
|
1335
|
+
requirements: engine.list()
|
|
1336
|
+
});
|
|
1337
|
+
}
|
|
1338
|
+
},
|
|
1339
|
+
{
|
|
1340
|
+
kind: "exact",
|
|
1341
|
+
path: `${API_PREFIX}/review-workspaces`,
|
|
1342
|
+
handler: async (req, res) => {
|
|
1343
|
+
if (req.method !== "GET") return json(res, 405, {
|
|
1344
|
+
ok: false,
|
|
1345
|
+
error: "method-not-allowed"
|
|
1346
|
+
});
|
|
1347
|
+
if (!guard(req, res)) return;
|
|
1348
|
+
try {
|
|
1349
|
+
json(res, 200, {
|
|
1350
|
+
ok: true,
|
|
1351
|
+
workspaces: await coordinator.reviewWorkspaces()
|
|
1352
|
+
});
|
|
1353
|
+
} catch (error) {
|
|
1354
|
+
json(res, 400, {
|
|
1355
|
+
ok: false,
|
|
1356
|
+
error: error instanceof Error ? error.message : String(error)
|
|
1357
|
+
});
|
|
1358
|
+
}
|
|
1359
|
+
}
|
|
1360
|
+
},
|
|
1361
|
+
{
|
|
1362
|
+
kind: "exact",
|
|
1363
|
+
path: `${API_PREFIX}/version`,
|
|
1364
|
+
handler: (req, res) => {
|
|
1365
|
+
if (req.method !== "GET") return json(res, 405, {
|
|
1366
|
+
ok: false,
|
|
1367
|
+
error: "method-not-allowed"
|
|
1368
|
+
});
|
|
1369
|
+
if (!guard(req, res)) return;
|
|
1370
|
+
try {
|
|
1371
|
+
const url = new URL(req.url ?? "", `http://${req.headers.host ?? "127.0.0.1"}`);
|
|
1372
|
+
const requirementId = url.searchParams.get("requirementId") ?? "";
|
|
1373
|
+
const commit = url.searchParams.get("commit") ?? "";
|
|
1374
|
+
json(res, 200, {
|
|
1375
|
+
ok: true,
|
|
1376
|
+
version: engine.version(requirementId, commit)
|
|
1377
|
+
});
|
|
1378
|
+
} catch (error) {
|
|
1379
|
+
json(res, 404, {
|
|
1380
|
+
ok: false,
|
|
1381
|
+
error: error instanceof Error ? error.message : String(error)
|
|
1382
|
+
});
|
|
1383
|
+
}
|
|
1384
|
+
}
|
|
1385
|
+
},
|
|
1386
|
+
{
|
|
1387
|
+
kind: "exact",
|
|
1388
|
+
path: `${API_PREFIX}/my-items`,
|
|
1389
|
+
handler: (req, res) => {
|
|
1390
|
+
if (req.method !== "GET") return json(res, 405, {
|
|
1391
|
+
ok: false,
|
|
1392
|
+
error: "method-not-allowed"
|
|
1393
|
+
});
|
|
1394
|
+
if (!guard(req, res)) return;
|
|
1395
|
+
const url = new URL(req.url ?? "", `http://${req.headers.host ?? "127.0.0.1"}`);
|
|
1396
|
+
const participantId = url.searchParams.get("participantId") ?? "";
|
|
1397
|
+
const role = url.searchParams.get("role");
|
|
1398
|
+
if (participantId.length < 8 || role !== "product" && role !== "engineering") return json(res, 400, {
|
|
1399
|
+
ok: false,
|
|
1400
|
+
error: "invalid-participant-query"
|
|
1401
|
+
});
|
|
1402
|
+
return json(res, 200, {
|
|
1403
|
+
ok: true,
|
|
1404
|
+
items: engine.myItems({
|
|
1405
|
+
participantId,
|
|
1406
|
+
nickname: "当前参与者",
|
|
1407
|
+
role,
|
|
1408
|
+
kind: "human"
|
|
1409
|
+
})
|
|
1410
|
+
});
|
|
1411
|
+
}
|
|
1412
|
+
},
|
|
1413
|
+
{
|
|
1414
|
+
kind: "exact",
|
|
1415
|
+
path: `${API_PREFIX}/action`,
|
|
1416
|
+
handler: async (req, res) => {
|
|
1417
|
+
if (req.method !== "POST") return json(res, 405, {
|
|
1418
|
+
ok: false,
|
|
1419
|
+
error: "method-not-allowed"
|
|
1420
|
+
});
|
|
1421
|
+
if (!guard(req, res)) return;
|
|
1422
|
+
if (!(req.headers["content-type"] ?? "").toLowerCase().startsWith("application/json")) return json(res, 415, {
|
|
1423
|
+
ok: false,
|
|
1424
|
+
error: "json-required"
|
|
1425
|
+
});
|
|
1426
|
+
try {
|
|
1427
|
+
const envelope = parseEnvelope(await readJson(req));
|
|
1428
|
+
if (envelope === void 0) return json(res, 400, {
|
|
1429
|
+
ok: false,
|
|
1430
|
+
error: "invalid-action"
|
|
1431
|
+
});
|
|
1432
|
+
if ((envelope.action.kind === "requirement.create" || envelope.action.kind === "requirement.bind-workspace") && typeof envelope.action.workspaceId === "string" && envelope.action.workspaceId.trim() !== "") await coordinator.assertWorkspaceAvailable(envelope.action.workspaceId);
|
|
1433
|
+
const result = engine.apply(envelope.requestId, envelope.action);
|
|
1434
|
+
json(res, result.ok ? 200 : result.error === "base-commit-conflict" ? 409 : 400, result);
|
|
1435
|
+
} catch (error) {
|
|
1436
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
1437
|
+
json(res, message === "body-too-large" ? 413 : 400, {
|
|
1438
|
+
ok: false,
|
|
1439
|
+
error: message
|
|
1440
|
+
});
|
|
1441
|
+
}
|
|
1442
|
+
}
|
|
1443
|
+
},
|
|
1444
|
+
{
|
|
1445
|
+
kind: "exact",
|
|
1446
|
+
path: `${API_PREFIX}/ai-conversation`,
|
|
1447
|
+
handler: async (req, res) => {
|
|
1448
|
+
if (!guard(req, res)) return;
|
|
1449
|
+
try {
|
|
1450
|
+
if (req.method === "GET") {
|
|
1451
|
+
const url = new URL(req.url ?? "", `http://${req.headers.host ?? "127.0.0.1"}`);
|
|
1452
|
+
const requirementId = url.searchParams.get("requirementId") ?? "";
|
|
1453
|
+
const sessionId = url.searchParams.get("sessionId") ?? "";
|
|
1454
|
+
if (!engine.hasAiSession(requirementId, sessionId)) return json(res, 404, {
|
|
1455
|
+
ok: false,
|
|
1456
|
+
error: "AI 会话不属于该需求"
|
|
1457
|
+
});
|
|
1458
|
+
return json(res, 200, {
|
|
1459
|
+
ok: true,
|
|
1460
|
+
messages: await coordinator.conversation(sessionId)
|
|
1461
|
+
});
|
|
1462
|
+
}
|
|
1463
|
+
if (req.method === "POST") {
|
|
1464
|
+
if (!(req.headers["content-type"] ?? "").toLowerCase().startsWith("application/json")) return json(res, 415, {
|
|
1465
|
+
ok: false,
|
|
1466
|
+
error: "json-required"
|
|
1467
|
+
});
|
|
1468
|
+
const body = await readJson(req);
|
|
1469
|
+
if (typeof body.requirementId !== "string" || typeof body.sessionId !== "string" || typeof body.text !== "string") return json(res, 400, {
|
|
1470
|
+
ok: false,
|
|
1471
|
+
error: "invalid-follow-up"
|
|
1472
|
+
});
|
|
1473
|
+
if (!engine.hasAiSession(body.requirementId, body.sessionId)) return json(res, 404, {
|
|
1474
|
+
ok: false,
|
|
1475
|
+
error: "AI 会话不属于该需求"
|
|
1476
|
+
});
|
|
1477
|
+
await coordinator.followUp(body.sessionId, body.text);
|
|
1478
|
+
return json(res, 202, { ok: true });
|
|
1479
|
+
}
|
|
1480
|
+
return json(res, 405, {
|
|
1481
|
+
ok: false,
|
|
1482
|
+
error: "method-not-allowed"
|
|
1483
|
+
});
|
|
1484
|
+
} catch (error) {
|
|
1485
|
+
return json(res, 400, {
|
|
1486
|
+
ok: false,
|
|
1487
|
+
error: error instanceof Error ? error.message : String(error)
|
|
1488
|
+
});
|
|
1489
|
+
}
|
|
1490
|
+
}
|
|
1491
|
+
},
|
|
1492
|
+
{
|
|
1493
|
+
kind: "exact",
|
|
1494
|
+
path: `${API_PREFIX}/events`,
|
|
1495
|
+
handler: (req, res) => {
|
|
1496
|
+
if (req.method !== "GET") {
|
|
1497
|
+
res.writeHead(405);
|
|
1498
|
+
res.end();
|
|
1499
|
+
return;
|
|
1500
|
+
}
|
|
1501
|
+
if (!guard(req, res)) return;
|
|
1502
|
+
res.writeHead(200, {
|
|
1503
|
+
"content-type": "text/event-stream; charset=utf-8",
|
|
1504
|
+
"cache-control": "no-cache",
|
|
1505
|
+
connection: "keep-alive"
|
|
1506
|
+
});
|
|
1507
|
+
const push = () => {
|
|
1508
|
+
res.write(`data: ${JSON.stringify({ revision: engine.snapshot().revision })}\n\n`);
|
|
1509
|
+
};
|
|
1510
|
+
const unsubscribe = engine.subscribe(push);
|
|
1511
|
+
const heartbeat = setInterval(() => {
|
|
1512
|
+
res.write(": ping\n\n");
|
|
1513
|
+
}, HEARTBEAT_MS);
|
|
1514
|
+
const close = () => {
|
|
1515
|
+
clearInterval(heartbeat);
|
|
1516
|
+
unsubscribe();
|
|
1517
|
+
};
|
|
1518
|
+
req.once("close", close);
|
|
1519
|
+
res.once("close", close);
|
|
1520
|
+
push();
|
|
1521
|
+
}
|
|
1522
|
+
}
|
|
1523
|
+
];
|
|
1524
|
+
}
|
|
1525
|
+
//#endregion
|
|
1526
|
+
//#region src/tools.ts
|
|
1527
|
+
function text(value) {
|
|
1528
|
+
return [{
|
|
1529
|
+
type: "text",
|
|
1530
|
+
text: value
|
|
1531
|
+
}];
|
|
1532
|
+
}
|
|
1533
|
+
function ai(nickname, role, sessionId) {
|
|
1534
|
+
return {
|
|
1535
|
+
participantId: `ai:${sessionId}`,
|
|
1536
|
+
nickname,
|
|
1537
|
+
role,
|
|
1538
|
+
kind: "ai",
|
|
1539
|
+
sessionId
|
|
1540
|
+
};
|
|
1541
|
+
}
|
|
1542
|
+
function contentOutput(description) {
|
|
1543
|
+
return {
|
|
1544
|
+
schema: {
|
|
1545
|
+
type: "object",
|
|
1546
|
+
additionalProperties: false,
|
|
1547
|
+
properties: { content: {
|
|
1548
|
+
type: "string",
|
|
1549
|
+
required: true,
|
|
1550
|
+
description
|
|
1551
|
+
} }
|
|
1552
|
+
},
|
|
1553
|
+
render: (_args, value) => text(value.content)
|
|
1554
|
+
};
|
|
1555
|
+
}
|
|
1556
|
+
function specListTool(engine) {
|
|
1557
|
+
return defineTool({
|
|
1558
|
+
name: "spec_list",
|
|
1559
|
+
description: "List shared collaborative requirements and their product-review, joint-review, or Ready stage. This product stops at Ready Spec.",
|
|
1560
|
+
parameters: {},
|
|
1561
|
+
output: contentOutput("Requirement list."),
|
|
1562
|
+
async execute() {
|
|
1563
|
+
return { content: engine.list().map((item) => `${item.id} | ${item.stage} | ${item.currentCommit.slice(0, 10)} | ${item.reviewItems.filter((review) => review.severity === "blocking" && review.status !== "resolved").length} blockers | ${item.title}`).join("\n") || "no requirements" };
|
|
1564
|
+
}
|
|
1565
|
+
});
|
|
1566
|
+
}
|
|
1567
|
+
function specReadTool(engine) {
|
|
1568
|
+
return defineTool({
|
|
1569
|
+
name: "spec_read",
|
|
1570
|
+
description: "Read one requirement at its exact current Git commit, with selected collaboration context. Use this before any review submission.",
|
|
1571
|
+
parameters: {
|
|
1572
|
+
requirementId: {
|
|
1573
|
+
type: "string",
|
|
1574
|
+
required: true
|
|
1575
|
+
},
|
|
1576
|
+
include: {
|
|
1577
|
+
type: "array",
|
|
1578
|
+
items: {
|
|
1579
|
+
type: "string",
|
|
1580
|
+
enum: [
|
|
1581
|
+
"spec",
|
|
1582
|
+
"review-items",
|
|
1583
|
+
"comments",
|
|
1584
|
+
"decisions",
|
|
1585
|
+
"confirmations",
|
|
1586
|
+
"sources",
|
|
1587
|
+
"readiness"
|
|
1588
|
+
]
|
|
1589
|
+
},
|
|
1590
|
+
description: "Sections to include; default includes all current context."
|
|
1591
|
+
}
|
|
1592
|
+
},
|
|
1593
|
+
output: contentOutput("Pinned requirement context."),
|
|
1594
|
+
async execute(args) {
|
|
1595
|
+
const view = engine.view(args.requirementId);
|
|
1596
|
+
const include = new Set(args.include ?? [
|
|
1597
|
+
"spec",
|
|
1598
|
+
"review-items",
|
|
1599
|
+
"comments",
|
|
1600
|
+
"decisions",
|
|
1601
|
+
"confirmations",
|
|
1602
|
+
"sources",
|
|
1603
|
+
"readiness"
|
|
1604
|
+
]);
|
|
1605
|
+
const rows = [
|
|
1606
|
+
`# ${view.title}`,
|
|
1607
|
+
`stage: ${view.stage}`,
|
|
1608
|
+
`commit: ${view.currentCommit}`
|
|
1609
|
+
];
|
|
1610
|
+
if (include.has("spec")) rows.push("", "## Spec", view.version.markdown);
|
|
1611
|
+
if (include.has("review-items")) rows.push("", "## Review Items", ...view.reviewItems.map((item) => `- ${item.id} [${item.severity}/${item.status}/${item.epistemicStatus}] ${item.statement}\n Question: ${item.question}\n Recommended options: ${(item.recommendedOptions ?? []).join(" / ") || "none"}\n Evidence: ${item.evidence.map((evidence) => `${evidence.source}${evidence.version ? `@${evidence.version}` : ""}`).join(", ") || "none"}`));
|
|
1612
|
+
if (include.has("comments")) rows.push("", "## Comments", ...view.comments.map((item) => `- ${item.id} [${item.status}] “${item.anchor.quote}” ${item.author.nickname}: ${item.body}\n Replies: ${item.replies.map((reply) => `${reply.author.nickname}: ${reply.body}`).join(" / ") || "none"}`));
|
|
1613
|
+
if (include.has("decisions")) rows.push("", "## Decisions", ...view.decisions.map((item) => `- ${item.id} [${item.status}] ${item.question}: ${item.decision}`));
|
|
1614
|
+
if (include.has("confirmations")) rows.push("", "## Confirmations", ...view.confirmations.map((item) => `- ${item.role}/${item.scope}/${item.scopeId ?? "document"} [${item.status}] ${item.participant.nickname} @ ${item.commit}`));
|
|
1615
|
+
if (include.has("sources")) rows.push("", "## Sources", ...view.sources.map((item) => `- ${item.id} [${item.accessStatus}] ${item.label}${item.version ? ` @ ${item.version}` : ""}`));
|
|
1616
|
+
if (include.has("readiness")) rows.push("", "## Readiness", ...view.readiness.map((item) => `- ${item.passed ? "PASS" : "FAIL"} ${item.key}: ${item.reasons.join("; ")}`));
|
|
1617
|
+
return { content: rows.join("\n") };
|
|
1618
|
+
}
|
|
1619
|
+
});
|
|
1620
|
+
}
|
|
1621
|
+
function specReplyTool(engine) {
|
|
1622
|
+
return defineTool({
|
|
1623
|
+
name: "spec_reply",
|
|
1624
|
+
description: "Post the required AI analysis to one substantive Spec comment. Include understanding, evidence or TO_VERIFY, affected sections/AC IDs, and proposed disposition.",
|
|
1625
|
+
parameters: {
|
|
1626
|
+
requirementId: {
|
|
1627
|
+
type: "string",
|
|
1628
|
+
required: true
|
|
1629
|
+
},
|
|
1630
|
+
commentId: {
|
|
1631
|
+
type: "string",
|
|
1632
|
+
required: true
|
|
1633
|
+
},
|
|
1634
|
+
body: {
|
|
1635
|
+
type: "string",
|
|
1636
|
+
required: true
|
|
1637
|
+
},
|
|
1638
|
+
nickname: {
|
|
1639
|
+
type: "string",
|
|
1640
|
+
required: true
|
|
1641
|
+
},
|
|
1642
|
+
role: {
|
|
1643
|
+
type: "string",
|
|
1644
|
+
required: true,
|
|
1645
|
+
enum: ["product", "engineering"]
|
|
1646
|
+
},
|
|
1647
|
+
sessionId: {
|
|
1648
|
+
type: "string",
|
|
1649
|
+
required: true
|
|
1650
|
+
}
|
|
1651
|
+
},
|
|
1652
|
+
output: contentOutput("Reply result."),
|
|
1653
|
+
async execute(args) {
|
|
1654
|
+
engine.submitAiReply({
|
|
1655
|
+
requirementId: args.requirementId,
|
|
1656
|
+
commentId: args.commentId,
|
|
1657
|
+
ai: ai(args.nickname, args.role, args.sessionId),
|
|
1658
|
+
body: args.body
|
|
1659
|
+
});
|
|
1660
|
+
return { content: "AI analysis posted" };
|
|
1661
|
+
}
|
|
1662
|
+
});
|
|
1663
|
+
}
|
|
1664
|
+
function specSubmitReviewTool(engine) {
|
|
1665
|
+
return defineTool({
|
|
1666
|
+
name: "spec_submit_review",
|
|
1667
|
+
description: "Submit structured, commit-pinned AI Review Items. AI may propose findings but cannot confirm or mark Ready. FACT requires accessible versioned evidence.",
|
|
1668
|
+
parameters: {
|
|
1669
|
+
requirementId: {
|
|
1670
|
+
type: "string",
|
|
1671
|
+
required: true
|
|
1672
|
+
},
|
|
1673
|
+
commit: {
|
|
1674
|
+
type: "string",
|
|
1675
|
+
required: true
|
|
1676
|
+
},
|
|
1677
|
+
runId: {
|
|
1678
|
+
type: "string",
|
|
1679
|
+
required: true
|
|
1680
|
+
},
|
|
1681
|
+
reviewKind: {
|
|
1682
|
+
type: "string",
|
|
1683
|
+
required: true,
|
|
1684
|
+
enum: [
|
|
1685
|
+
"product-first",
|
|
1686
|
+
"product-second",
|
|
1687
|
+
"engineering-precheck",
|
|
1688
|
+
"change-review"
|
|
1689
|
+
]
|
|
1690
|
+
},
|
|
1691
|
+
nickname: {
|
|
1692
|
+
type: "string",
|
|
1693
|
+
required: true
|
|
1694
|
+
},
|
|
1695
|
+
role: {
|
|
1696
|
+
type: "string",
|
|
1697
|
+
required: true,
|
|
1698
|
+
enum: ["product", "engineering"]
|
|
1699
|
+
},
|
|
1700
|
+
sessionId: {
|
|
1701
|
+
type: "string",
|
|
1702
|
+
required: true
|
|
1703
|
+
},
|
|
1704
|
+
maturitySummary: {
|
|
1705
|
+
type: "string",
|
|
1706
|
+
required: true
|
|
1707
|
+
},
|
|
1708
|
+
items: {
|
|
1709
|
+
type: "array",
|
|
1710
|
+
required: true,
|
|
1711
|
+
items: {
|
|
1712
|
+
type: "object",
|
|
1713
|
+
additionalProperties: false,
|
|
1714
|
+
properties: {
|
|
1715
|
+
type: {
|
|
1716
|
+
type: "string",
|
|
1717
|
+
required: true,
|
|
1718
|
+
enum: [
|
|
1719
|
+
"goal",
|
|
1720
|
+
"evidence",
|
|
1721
|
+
"history-conflict",
|
|
1722
|
+
"current-implementation",
|
|
1723
|
+
"scope",
|
|
1724
|
+
"semantics",
|
|
1725
|
+
"completeness",
|
|
1726
|
+
"acceptance",
|
|
1727
|
+
"risk"
|
|
1728
|
+
]
|
|
1729
|
+
},
|
|
1730
|
+
severity: {
|
|
1731
|
+
type: "string",
|
|
1732
|
+
required: true,
|
|
1733
|
+
enum: [
|
|
1734
|
+
"blocking",
|
|
1735
|
+
"major",
|
|
1736
|
+
"minor"
|
|
1737
|
+
]
|
|
1738
|
+
},
|
|
1739
|
+
statement: {
|
|
1740
|
+
type: "string",
|
|
1741
|
+
required: true
|
|
1742
|
+
},
|
|
1743
|
+
epistemicStatus: {
|
|
1744
|
+
type: "string",
|
|
1745
|
+
required: true,
|
|
1746
|
+
enum: [
|
|
1747
|
+
"FACT",
|
|
1748
|
+
"INFERENCE",
|
|
1749
|
+
"ASSUMPTION",
|
|
1750
|
+
"TO_VERIFY"
|
|
1751
|
+
]
|
|
1752
|
+
},
|
|
1753
|
+
impact: {
|
|
1754
|
+
type: "string",
|
|
1755
|
+
required: true
|
|
1756
|
+
},
|
|
1757
|
+
question: {
|
|
1758
|
+
type: "string",
|
|
1759
|
+
required: true
|
|
1760
|
+
},
|
|
1761
|
+
recommendedOptions: {
|
|
1762
|
+
type: "array",
|
|
1763
|
+
required: true,
|
|
1764
|
+
items: { type: "string" },
|
|
1765
|
+
description: "至少三个可直接供用户选择的具体中文建议,不得只是同义改写。"
|
|
1766
|
+
},
|
|
1767
|
+
affectedSections: {
|
|
1768
|
+
type: "array",
|
|
1769
|
+
required: true,
|
|
1770
|
+
items: { type: "string" }
|
|
1771
|
+
},
|
|
1772
|
+
affectedAcceptanceIds: {
|
|
1773
|
+
type: "array",
|
|
1774
|
+
required: true,
|
|
1775
|
+
items: { type: "string" }
|
|
1776
|
+
},
|
|
1777
|
+
ownerRole: {
|
|
1778
|
+
type: "string",
|
|
1779
|
+
required: true,
|
|
1780
|
+
enum: ["product", "engineering"]
|
|
1781
|
+
},
|
|
1782
|
+
status: {
|
|
1783
|
+
type: "string",
|
|
1784
|
+
required: true,
|
|
1785
|
+
enum: [
|
|
1786
|
+
"open",
|
|
1787
|
+
"joint-review",
|
|
1788
|
+
"non-blocking-verify"
|
|
1789
|
+
]
|
|
1790
|
+
},
|
|
1791
|
+
evidence: {
|
|
1792
|
+
type: "array",
|
|
1793
|
+
required: true,
|
|
1794
|
+
items: {
|
|
1795
|
+
type: "object",
|
|
1796
|
+
additionalProperties: false,
|
|
1797
|
+
properties: {
|
|
1798
|
+
statement: {
|
|
1799
|
+
type: "string",
|
|
1800
|
+
required: true
|
|
1801
|
+
},
|
|
1802
|
+
source: {
|
|
1803
|
+
type: "string",
|
|
1804
|
+
required: true
|
|
1805
|
+
},
|
|
1806
|
+
version: { type: "string" },
|
|
1807
|
+
accessible: {
|
|
1808
|
+
type: "boolean",
|
|
1809
|
+
required: true
|
|
1810
|
+
}
|
|
1811
|
+
}
|
|
1812
|
+
}
|
|
1813
|
+
}
|
|
1814
|
+
}
|
|
1815
|
+
}
|
|
1816
|
+
}
|
|
1817
|
+
},
|
|
1818
|
+
output: contentOutput("Review submission result."),
|
|
1819
|
+
async execute(args) {
|
|
1820
|
+
for (const item of args.items) {
|
|
1821
|
+
const options = item.recommendedOptions.map((option) => option.trim()).filter(Boolean);
|
|
1822
|
+
if (options.length < 3 || new Set(options).size < 3) throw new Error("each review item requires at least three distinct recommended options");
|
|
1823
|
+
if (item.epistemicStatus === "FACT" && !item.evidence.some((evidence) => evidence.accessible && typeof evidence.version === "string" && evidence.version !== "")) throw new Error("FACT requires accessible versioned evidence");
|
|
1824
|
+
}
|
|
1825
|
+
engine.submitReview({
|
|
1826
|
+
requirementId: args.requirementId,
|
|
1827
|
+
commit: args.commit,
|
|
1828
|
+
runId: args.runId,
|
|
1829
|
+
ai: ai(args.nickname, args.role, args.sessionId),
|
|
1830
|
+
maturitySummary: args.maturitySummary,
|
|
1831
|
+
items: args.items.map((item) => ({
|
|
1832
|
+
type: item.type,
|
|
1833
|
+
severity: item.severity,
|
|
1834
|
+
statement: item.statement,
|
|
1835
|
+
evidence: item.evidence,
|
|
1836
|
+
epistemicStatus: item.epistemicStatus,
|
|
1837
|
+
impact: item.impact,
|
|
1838
|
+
question: item.question,
|
|
1839
|
+
recommendedOptions: item.recommendedOptions,
|
|
1840
|
+
affectedSections: item.affectedSections,
|
|
1841
|
+
affectedAcceptanceIds: item.affectedAcceptanceIds,
|
|
1842
|
+
ownerRole: item.ownerRole,
|
|
1843
|
+
status: item.status
|
|
1844
|
+
}))
|
|
1845
|
+
});
|
|
1846
|
+
return { content: `submitted ${args.items.length} review items for ${args.commit}` };
|
|
1847
|
+
}
|
|
1848
|
+
});
|
|
1849
|
+
}
|
|
1850
|
+
function specProposePatchTool(engine) {
|
|
1851
|
+
return defineTool({
|
|
1852
|
+
name: "spec_propose_patch",
|
|
1853
|
+
description: "Propose a complete revised Markdown Spec against an exact base commit. This creates a reviewable candidate only; it never writes Git.",
|
|
1854
|
+
parameters: {
|
|
1855
|
+
requirementId: {
|
|
1856
|
+
type: "string",
|
|
1857
|
+
required: true
|
|
1858
|
+
},
|
|
1859
|
+
baseCommit: {
|
|
1860
|
+
type: "string",
|
|
1861
|
+
required: true
|
|
1862
|
+
},
|
|
1863
|
+
reviewKind: {
|
|
1864
|
+
type: "string",
|
|
1865
|
+
required: true,
|
|
1866
|
+
enum: [
|
|
1867
|
+
"product-first",
|
|
1868
|
+
"product-second",
|
|
1869
|
+
"engineering-precheck",
|
|
1870
|
+
"change-review"
|
|
1871
|
+
]
|
|
1872
|
+
},
|
|
1873
|
+
proposedMarkdown: {
|
|
1874
|
+
type: "string",
|
|
1875
|
+
required: true
|
|
1876
|
+
},
|
|
1877
|
+
summary: {
|
|
1878
|
+
type: "string",
|
|
1879
|
+
required: true
|
|
1880
|
+
},
|
|
1881
|
+
affectedReviewItemIds: {
|
|
1882
|
+
type: "array",
|
|
1883
|
+
required: true,
|
|
1884
|
+
items: { type: "string" }
|
|
1885
|
+
},
|
|
1886
|
+
affectedSections: {
|
|
1887
|
+
type: "array",
|
|
1888
|
+
required: true,
|
|
1889
|
+
items: { type: "string" }
|
|
1890
|
+
},
|
|
1891
|
+
affectedAcceptanceIds: {
|
|
1892
|
+
type: "array",
|
|
1893
|
+
required: true,
|
|
1894
|
+
items: { type: "string" }
|
|
1895
|
+
},
|
|
1896
|
+
nickname: {
|
|
1897
|
+
type: "string",
|
|
1898
|
+
required: true
|
|
1899
|
+
},
|
|
1900
|
+
role: {
|
|
1901
|
+
type: "string",
|
|
1902
|
+
required: true,
|
|
1903
|
+
enum: ["product", "engineering"]
|
|
1904
|
+
},
|
|
1905
|
+
sessionId: {
|
|
1906
|
+
type: "string",
|
|
1907
|
+
required: true
|
|
1908
|
+
}
|
|
1909
|
+
},
|
|
1910
|
+
output: contentOutput("Patch proposal result."),
|
|
1911
|
+
async execute(args) {
|
|
1912
|
+
engine.submitPatch({
|
|
1913
|
+
requirementId: args.requirementId,
|
|
1914
|
+
baseCommit: args.baseCommit,
|
|
1915
|
+
reviewKind: args.reviewKind,
|
|
1916
|
+
ai: ai(args.nickname, args.role, args.sessionId),
|
|
1917
|
+
proposedMarkdown: args.proposedMarkdown,
|
|
1918
|
+
summary: args.summary,
|
|
1919
|
+
affectedReviewItemIds: args.affectedReviewItemIds,
|
|
1920
|
+
affectedSections: args.affectedSections,
|
|
1921
|
+
affectedAcceptanceIds: args.affectedAcceptanceIds
|
|
1922
|
+
});
|
|
1923
|
+
return { content: `candidate patch proposed for ${args.baseCommit}` };
|
|
1924
|
+
}
|
|
1925
|
+
});
|
|
1926
|
+
}
|
|
1927
|
+
function allSpecTools(engine) {
|
|
1928
|
+
return [
|
|
1929
|
+
specListTool(engine),
|
|
1930
|
+
specReadTool(engine),
|
|
1931
|
+
specReplyTool(engine),
|
|
1932
|
+
specSubmitReviewTool(engine),
|
|
1933
|
+
specProposePatchTool(engine)
|
|
1934
|
+
];
|
|
1935
|
+
}
|
|
1936
|
+
//#endregion
|
|
1937
|
+
//#region src/index.ts
|
|
1938
|
+
const name = "spec-collab";
|
|
1939
|
+
const inject = [
|
|
1940
|
+
"webServer",
|
|
1941
|
+
"apiProxy",
|
|
1942
|
+
"tools",
|
|
1943
|
+
"systemPrompt"
|
|
1944
|
+
];
|
|
1945
|
+
const stringList = () => Schema.array(Schema.string()).default([]);
|
|
1946
|
+
const contextFields = () => ({
|
|
1947
|
+
skills: stringList().description("当前上下文必须先加载的 Skill 名称。"),
|
|
1948
|
+
mcpServers: stringList().description("当前上下文可使用的 MCP serverName;工具 namespace 为 mcp__<serverName>__*。"),
|
|
1949
|
+
documentPaths: stringList().description("AI 分析前可读取的本地文件或目录路径;相对路径按需求工作区根目录解析。"),
|
|
1950
|
+
agentPreset: Schema.string().description("实际挂载这些 Skill/MCP 工具的 DSH Agent Preset ID。")
|
|
1951
|
+
});
|
|
1952
|
+
const Config = Schema.object({
|
|
1953
|
+
dataRoot: Schema.string().description("协作账本数据目录。"),
|
|
1954
|
+
repositoryPath: Schema.string().description("正式 Spec Git 仓库目录。"),
|
|
1955
|
+
defaultContext: Schema.object(contextFields()).description("所有需求工作区都会合并的默认 AI 上下文。"),
|
|
1956
|
+
workspaces: Schema.array(Schema.object({
|
|
1957
|
+
workspaceId: Schema.string().required().description("需要追加项目专属 AI 上下文的 DSH workspaceId。"),
|
|
1958
|
+
...contextFields()
|
|
1959
|
+
})).default([]).description("按 DSH 工作区追加的 AI 上下文;未列出的工作区仍继承 defaultContext。")
|
|
1960
|
+
});
|
|
1961
|
+
function apply(ctx, config = {}) {
|
|
1962
|
+
const dataRoot = config.dataRoot ?? join(homedir(), ".dsh", "spec-collab");
|
|
1963
|
+
const contexts = new ReviewContextCatalog(config);
|
|
1964
|
+
const engine = new CollaborationEngine(join(dataRoot, "collaboration-v2.json"), new GitRequirementStore(config.repositoryPath ?? join(dataRoot, "repository")));
|
|
1965
|
+
const coordinator = new DshReviewCoordinator(ctx.apiProxy, contexts);
|
|
1966
|
+
engine.setCoordinator(coordinator);
|
|
1967
|
+
ctx.effect(() => {
|
|
1968
|
+
const disposers = makeRoutes(engine, coordinator).map((route) => ctx.webServer.register(route));
|
|
1969
|
+
return () => {
|
|
1970
|
+
for (const dispose of disposers) dispose();
|
|
1971
|
+
};
|
|
1972
|
+
}, "spec-collab: routes");
|
|
1973
|
+
ctx.effect(() => {
|
|
1974
|
+
const disposers = allSpecTools(engine).map((tool) => ctx.tools.register(tool));
|
|
1975
|
+
return () => {
|
|
1976
|
+
for (const dispose of disposers) dispose();
|
|
1977
|
+
};
|
|
1978
|
+
}, "spec-collab: tools");
|
|
1979
|
+
ctx.effect(() => ctx.systemPrompt.section({
|
|
1980
|
+
name: "plugin:spec-collab",
|
|
1981
|
+
order: 190,
|
|
1982
|
+
text: "本机已安装 dsh-spec-collab「AI 需求澄清与 Spec 共创工作台」。产品输入原始需求后,产品 AI 初审并生成结构化 Review Item,产品逐项回应,AI 二次审核并提出候选 patch;产品确认后进入产研与双方 AI 共审,最终通过 Ready 质量门输出 commit 绑定的 Ready Spec。正式 Spec 版本只存 Git+Markdown;AI 只能提出 Review Item、分析回复和候选 patch,不能确认产品/技术语义,也不能直接写 Git 或标记 Ready。该产品严格止于 Ready Spec,不执行代码开发、测试、worktree、部署或发布。使用 spec_list/spec_read 读取,spec_reply/spec_submit_review/spec_propose_patch 参与审核。"
|
|
1983
|
+
}), "spec-collab: prompt");
|
|
1984
|
+
}
|
|
1985
|
+
//#endregion
|
|
1986
|
+
export { Config, apply, inject, name };
|