mpt-workflow 0.0.0-stage → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +144 -0
- package/LICENSE +21 -0
- package/README.md +323 -2
- package/README.zh-CN.md +272 -0
- package/dist/cli.js +479 -0
- package/dist/cli.js.map +1 -0
- package/dist/core/acl.js +120 -0
- package/dist/core/acl.js.map +1 -0
- package/dist/core/config.js +100 -0
- package/dist/core/config.js.map +1 -0
- package/dist/core/demo.js +50 -0
- package/dist/core/demo.js.map +1 -0
- package/dist/core/docs.js +291 -0
- package/dist/core/docs.js.map +1 -0
- package/dist/core/fsutil.js +89 -0
- package/dist/core/fsutil.js.map +1 -0
- package/dist/core/git.js +126 -0
- package/dist/core/git.js.map +1 -0
- package/dist/core/glob.js +36 -0
- package/dist/core/glob.js.map +1 -0
- package/dist/core/hooks.js +277 -0
- package/dist/core/hooks.js.map +1 -0
- package/dist/core/init.js +382 -0
- package/dist/core/init.js.map +1 -0
- package/dist/core/markdown.js +109 -0
- package/dist/core/markdown.js.map +1 -0
- package/dist/core/messages.js +365 -0
- package/dist/core/messages.js.map +1 -0
- package/dist/core/questions.js +240 -0
- package/dist/core/questions.js.map +1 -0
- package/dist/core/state.js +139 -0
- package/dist/core/state.js.map +1 -0
- package/dist/core/types.js +8 -0
- package/dist/core/types.js.map +1 -0
- package/dist/core/workflow.js +1050 -0
- package/dist/core/workflow.js.map +1 -0
- package/dist/mcp/server.js +852 -0
- package/dist/mcp/server.js.map +1 -0
- package/dist/version.js +2 -0
- package/dist/version.js.map +1 -0
- package/dist/web/public/index.html +1094 -0
- package/dist/web/server.js +249 -0
- package/dist/web/server.js.map +1 -0
- package/package.json +63 -4
|
@@ -0,0 +1,1050 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import { spawn } from 'node:child_process';
|
|
3
|
+
import { exists, ensureDir, readText, readTextRequired, writeAtomic, within, truncate, isoNow, } from './fsutil.js';
|
|
4
|
+
import { loadConfig, saveConfig, findRoot, evidenceDir, } from './config.js';
|
|
5
|
+
import { listTodoFiles, parsePlan, parseTodo, parseEvidence, setTodoStatus, setTodoSha, appendEvidenceSection, statusLabel, } from './docs.js';
|
|
6
|
+
import { parseQuestionsFile, questionsFile, updateQuestion, } from './questions.js';
|
|
7
|
+
import { gitInfo, allChangedFiles, workingTreeHash, workingTreeOid, stageAll, commit as gitCommit, diffStat, } from './git.js';
|
|
8
|
+
import { checkAcl } from './acl.js';
|
|
9
|
+
import { appendToSection } from './markdown.js';
|
|
10
|
+
import { createApproval, readApproval, writeApproval, listApprovals, logEvent, withLock, } from './state.js';
|
|
11
|
+
import { MessageStore, actorKey, actorFromRole } from './messages.js';
|
|
12
|
+
export class Workflow {
|
|
13
|
+
root;
|
|
14
|
+
cfg;
|
|
15
|
+
_msgs;
|
|
16
|
+
constructor(root, cfg) {
|
|
17
|
+
this.root = path.resolve(root);
|
|
18
|
+
const loaded = cfg || loadConfig(this.root);
|
|
19
|
+
if (!loaded)
|
|
20
|
+
throw new Error(`未找到 ${path.join(this.root, '.workflow/program.yaml')}`);
|
|
21
|
+
this.cfg = loaded;
|
|
22
|
+
}
|
|
23
|
+
/** Message store for this program (lazy). */
|
|
24
|
+
get msgs() {
|
|
25
|
+
if (!this._msgs) {
|
|
26
|
+
this._msgs = new MessageStore({
|
|
27
|
+
root: this.root,
|
|
28
|
+
project: this.cfg.program,
|
|
29
|
+
repos: this.cfg.repos.map((r) => r.id),
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
return this._msgs;
|
|
33
|
+
}
|
|
34
|
+
actor(role, repo) {
|
|
35
|
+
return { role, repo };
|
|
36
|
+
}
|
|
37
|
+
/** Idempotent workflow event; never fails the state transition. */
|
|
38
|
+
notifyEvent(input) {
|
|
39
|
+
try {
|
|
40
|
+
this.msgs.emit({
|
|
41
|
+
from: { role: input.from, repo: input.repo },
|
|
42
|
+
to: input.to,
|
|
43
|
+
kind: input.kind,
|
|
44
|
+
subject: input.subject,
|
|
45
|
+
body: input.body,
|
|
46
|
+
refs: input.refs,
|
|
47
|
+
blocking: input.blocking,
|
|
48
|
+
repo: input.repo,
|
|
49
|
+
idempotencyBase: `${this.cfg.program}:${input.key}`,
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
catch {
|
|
53
|
+
/* notification must not break the state machine */
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
/** Unacked blocking messages for an actor; used to gate transitions. */
|
|
57
|
+
assertNotBlocked(role, repoId) {
|
|
58
|
+
const blocked = this.msgs.blockingFor({ role, repo: repoId });
|
|
59
|
+
if (blocked.length) {
|
|
60
|
+
throw new Error(`有未处理的 blocking 消息,先读并 ack:${blocked.map((m) => m.id).join(', ')}\n` +
|
|
61
|
+
blocked.map((m) => ` ${m.id} ${m.subject}`).join('\n'));
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
static discover(start) {
|
|
65
|
+
const root = findRoot(start);
|
|
66
|
+
if (!root)
|
|
67
|
+
return null;
|
|
68
|
+
return new Workflow(root);
|
|
69
|
+
}
|
|
70
|
+
/* ------------------------------ repos ------------------------------ */
|
|
71
|
+
repoRefs() {
|
|
72
|
+
return this.cfg.repos.map((r) => ({
|
|
73
|
+
id: r.id,
|
|
74
|
+
abs: path.isAbsolute(r.path) ? r.path : path.join(this.root, r.path),
|
|
75
|
+
}));
|
|
76
|
+
}
|
|
77
|
+
repoRef(id) {
|
|
78
|
+
const r = this.repoRefs().find((x) => x.id === id);
|
|
79
|
+
if (!r)
|
|
80
|
+
throw new Error(`未知仓库 ${id};已配置: ${this.cfg.repos.map((x) => x.id).join(', ')}`);
|
|
81
|
+
return r;
|
|
82
|
+
}
|
|
83
|
+
repoConfig(id) {
|
|
84
|
+
const c = this.cfg.repos.find((r) => r.id === id);
|
|
85
|
+
if (!c)
|
|
86
|
+
throw new Error(`未知仓库 ${id}`);
|
|
87
|
+
return c;
|
|
88
|
+
}
|
|
89
|
+
/** Map an absolute path to the repo that owns it. */
|
|
90
|
+
repoForPath(absPath) {
|
|
91
|
+
for (const r of this.repoRefs()) {
|
|
92
|
+
if (within(r.abs, absPath))
|
|
93
|
+
return r;
|
|
94
|
+
}
|
|
95
|
+
return null;
|
|
96
|
+
}
|
|
97
|
+
save() {
|
|
98
|
+
saveConfig(this.root, this.cfg);
|
|
99
|
+
}
|
|
100
|
+
/* --------------------------- questions ---------------------------- */
|
|
101
|
+
questionFiles() {
|
|
102
|
+
const out = [];
|
|
103
|
+
for (const r of this.repoRefs()) {
|
|
104
|
+
const f = questionsFile(r.abs);
|
|
105
|
+
if (exists(f))
|
|
106
|
+
out.push({ abs: f, repo: r.id });
|
|
107
|
+
}
|
|
108
|
+
const rootF = path.join(this.root, 'docs', 'agent-questions.md');
|
|
109
|
+
if (exists(rootF))
|
|
110
|
+
out.push({ abs: rootF });
|
|
111
|
+
return out;
|
|
112
|
+
}
|
|
113
|
+
allQuestions() {
|
|
114
|
+
return this.questionFiles().flatMap((f) => parseQuestionsFile(f.abs, f.repo));
|
|
115
|
+
}
|
|
116
|
+
findQuestion(id) {
|
|
117
|
+
return this.allQuestions().find((q) => q.id === id) || null;
|
|
118
|
+
}
|
|
119
|
+
/** Answer a question: update the file, notify the asker, clear the blocker. */
|
|
120
|
+
answerQuestion(q, answer, resolution, by) {
|
|
121
|
+
updateQuestion(q.file, q.id, { status: 'answered', answer, resolution });
|
|
122
|
+
const asker = actorFromRole(String(q.from), q.repo);
|
|
123
|
+
try {
|
|
124
|
+
this.msgs.send({
|
|
125
|
+
from: by,
|
|
126
|
+
to: asker,
|
|
127
|
+
kind: 'answer',
|
|
128
|
+
subject: `${q.id} 已回答:${q.context.split('\n')[0].slice(0, 80)}`,
|
|
129
|
+
body: answer,
|
|
130
|
+
refs: { question_id: q.id, repo: q.repo || '' },
|
|
131
|
+
idempotency_key: `${this.cfg.program}:answer:${q.id}`,
|
|
132
|
+
repo: q.repo,
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
catch {
|
|
136
|
+
/* the file is updated; notification is best-effort */
|
|
137
|
+
}
|
|
138
|
+
// Clear the blocker for whoever the question was addressed to, even when a
|
|
139
|
+
// human answered on their behalf (e.g. the user answering a PLAN question).
|
|
140
|
+
this.msgs.ackByRef(by, 'question_id', q.id);
|
|
141
|
+
const addressee = actorFromRole(String(q.to), q.repo);
|
|
142
|
+
if (actorKey(addressee) !== actorKey(by)) {
|
|
143
|
+
this.msgs.ackByRef(addressee, 'question_id', q.id);
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
/** Close a question: update the file, notify the other party. */
|
|
147
|
+
closeQuestion(q, resolution, by) {
|
|
148
|
+
updateQuestion(q.file, q.id, { status: 'closed', resolution });
|
|
149
|
+
const asker = actorFromRole(String(q.from), q.repo);
|
|
150
|
+
const addressee = actorFromRole(String(q.to), q.repo);
|
|
151
|
+
const other = actorKey(by) === actorKey(asker) ? addressee : asker;
|
|
152
|
+
try {
|
|
153
|
+
this.msgs.send({
|
|
154
|
+
from: by,
|
|
155
|
+
to: other,
|
|
156
|
+
kind: 'event',
|
|
157
|
+
subject: `${q.id} 已关闭`,
|
|
158
|
+
body: q.resolution || resolution || '',
|
|
159
|
+
refs: { question_id: q.id, repo: q.repo || '' },
|
|
160
|
+
idempotency_key: `${this.cfg.program}:close:${q.id}`,
|
|
161
|
+
repo: q.repo,
|
|
162
|
+
});
|
|
163
|
+
}
|
|
164
|
+
catch {
|
|
165
|
+
/* best-effort */
|
|
166
|
+
}
|
|
167
|
+
this.msgs.ackByRef(by, 'question_id', q.id);
|
|
168
|
+
}
|
|
169
|
+
/* -------------------------- repo state ---------------------------- */
|
|
170
|
+
repoState(id) {
|
|
171
|
+
const ref = this.repoRef(id);
|
|
172
|
+
const conf = this.repoConfig(id);
|
|
173
|
+
const plan = parsePlan(ref.abs); // PlanDoc | null
|
|
174
|
+
const todoFiles = listTodoFiles(ref.abs);
|
|
175
|
+
const todos = new Map();
|
|
176
|
+
for (const f of todoFiles) {
|
|
177
|
+
const doc = parseTodo(path.join(ref.abs, f));
|
|
178
|
+
if (doc)
|
|
179
|
+
todos.set(doc.id, doc);
|
|
180
|
+
}
|
|
181
|
+
const ids = new Set();
|
|
182
|
+
for (const m of plan?.milestoneIds || [])
|
|
183
|
+
ids.add(m);
|
|
184
|
+
for (const m of todos.keys())
|
|
185
|
+
ids.add(m);
|
|
186
|
+
const git = gitInfo(ref.abs);
|
|
187
|
+
const milestones = [...ids]
|
|
188
|
+
.sort((a, b) => Number(/(\d+)/.exec(a)?.[1]) - Number(/(\d+)/.exec(b)?.[1]))
|
|
189
|
+
.map((mid) => {
|
|
190
|
+
const todo = todos.get(mid);
|
|
191
|
+
const evidence = todo ? parseEvidence(todo) : [];
|
|
192
|
+
let status = todo ? todo.status : 'planned';
|
|
193
|
+
// `committed` is derived, never written: an accepted TODO whose record is
|
|
194
|
+
// clean in git means the acceptance itself has landed in history.
|
|
195
|
+
if (status === 'accepted' && todo && git.available) {
|
|
196
|
+
const rel = path.relative(ref.abs, todo.file).split(path.sep).join('/');
|
|
197
|
+
if (!git.changed.includes(rel) && !git.untracked.includes(rel)) {
|
|
198
|
+
status = 'committed';
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
return {
|
|
202
|
+
id: mid,
|
|
203
|
+
title: todo?.title || plan?.milestoneTitles[mid] || mid,
|
|
204
|
+
status,
|
|
205
|
+
statusRaw: todo ? todo.statusRaw : '无 TODO',
|
|
206
|
+
repo: id,
|
|
207
|
+
todoFile: todo ? path.relative(this.root, todo.file) : undefined,
|
|
208
|
+
sha: todo?.sha,
|
|
209
|
+
acceptance: todo?.acceptance || [],
|
|
210
|
+
evidence: evidence.map((e) => ({
|
|
211
|
+
id: e.id,
|
|
212
|
+
at: e.at,
|
|
213
|
+
command: e.command,
|
|
214
|
+
exitCode: e.exitCode,
|
|
215
|
+
head: e.head,
|
|
216
|
+
tree: e.tree,
|
|
217
|
+
dirty: e.dirty,
|
|
218
|
+
outputTail: e.outputTail,
|
|
219
|
+
})),
|
|
220
|
+
planRef: todo?.planRef,
|
|
221
|
+
};
|
|
222
|
+
});
|
|
223
|
+
const current = milestones.find((m) => !['accepted', 'committed'].includes(m.status)) || null;
|
|
224
|
+
const questions = exists(questionsFile(ref.abs))
|
|
225
|
+
? parseQuestionsFile(questionsFile(ref.abs), id)
|
|
226
|
+
: [];
|
|
227
|
+
const problems = [];
|
|
228
|
+
if (!plan)
|
|
229
|
+
problems.push('缺少 PLAN.md');
|
|
230
|
+
if (milestones.length === 0)
|
|
231
|
+
problems.push('PLAN 中未解析到任何 M,且无 TODO-Mn.md');
|
|
232
|
+
if (git.dirty)
|
|
233
|
+
problems.push(`工作区有未提交改动: ${git.changed.length + git.untracked.length} 个文件`);
|
|
234
|
+
if (current && current.status === 'accepted')
|
|
235
|
+
problems.push(`${current.id} 已验收但尚未提交`);
|
|
236
|
+
for (const q of questions.filter((q) => q.blocking && q.status === 'open')) {
|
|
237
|
+
problems.push(`阻塞问题未回答: ${q.id}`);
|
|
238
|
+
}
|
|
239
|
+
// phase: explicit PLAN phase, else the phase that lists this repo
|
|
240
|
+
const phase = plan?.phase ||
|
|
241
|
+
this.cfg.phases.find((p) => p.repos.includes(id))?.id;
|
|
242
|
+
return {
|
|
243
|
+
id,
|
|
244
|
+
path: conf.path,
|
|
245
|
+
absPath: ref.abs,
|
|
246
|
+
branch: conf.branch,
|
|
247
|
+
phase,
|
|
248
|
+
plan: plan
|
|
249
|
+
? {
|
|
250
|
+
file: path.relative(this.root, plan.file),
|
|
251
|
+
title: plan.title,
|
|
252
|
+
version: plan.version,
|
|
253
|
+
statusRaw: plan.statusRaw,
|
|
254
|
+
phase: plan.phase,
|
|
255
|
+
milestoneIds: plan.milestoneIds,
|
|
256
|
+
}
|
|
257
|
+
: undefined,
|
|
258
|
+
milestones,
|
|
259
|
+
currentMilestone: current,
|
|
260
|
+
questions,
|
|
261
|
+
git,
|
|
262
|
+
problems,
|
|
263
|
+
};
|
|
264
|
+
}
|
|
265
|
+
/* --------------------------- program ------------------------------ */
|
|
266
|
+
programStatus() {
|
|
267
|
+
try {
|
|
268
|
+
this.msgs.expireDue();
|
|
269
|
+
}
|
|
270
|
+
catch {
|
|
271
|
+
/* expiry is best-effort */
|
|
272
|
+
}
|
|
273
|
+
const repos = this.repoRefs().map((r) => this.repoState(r.id));
|
|
274
|
+
const questions = this.allQuestions();
|
|
275
|
+
const blocking = questions.filter((q) => q.blocking && q.status === 'open');
|
|
276
|
+
return {
|
|
277
|
+
program: this.cfg.program,
|
|
278
|
+
root: this.root,
|
|
279
|
+
activeRepo: this.cfg.active_repo,
|
|
280
|
+
phases: this.cfg.phases,
|
|
281
|
+
repos,
|
|
282
|
+
questions,
|
|
283
|
+
blockingQuestions: blocking,
|
|
284
|
+
next: this.nextActions(repos, blocking),
|
|
285
|
+
generatedAt: isoNow(),
|
|
286
|
+
};
|
|
287
|
+
}
|
|
288
|
+
nextActions(repos, blocking) {
|
|
289
|
+
const out = [];
|
|
290
|
+
const toMe = blocking.filter((q) => q.to === 'main' || q.to === 'user');
|
|
291
|
+
for (const q of toMe) {
|
|
292
|
+
out.push({
|
|
293
|
+
actor: q.to === 'user' ? 'user' : 'main',
|
|
294
|
+
action: '回答阻塞问题',
|
|
295
|
+
detail: `${q.id} (${q.from} → ${q.to}):${q.context.split('\n')[0].slice(0, 120)}`,
|
|
296
|
+
question: q.id,
|
|
297
|
+
blocking: true,
|
|
298
|
+
});
|
|
299
|
+
}
|
|
300
|
+
const activeId = this.cfg.active_repo;
|
|
301
|
+
if (!activeId) {
|
|
302
|
+
const nextPhase = this.cfg.phases.find((p) => p.status !== 'accepted' && p.status !== 'done');
|
|
303
|
+
out.push({
|
|
304
|
+
actor: 'main',
|
|
305
|
+
action: '激活一个仓',
|
|
306
|
+
detail: nextPhase
|
|
307
|
+
? `程序阶段 ${nextPhase.id}「${nextPhase.title}」尚未完成;选择一个仓开始`
|
|
308
|
+
: '所有阶段已完成,准备最终验收',
|
|
309
|
+
blocking: false,
|
|
310
|
+
});
|
|
311
|
+
return out;
|
|
312
|
+
}
|
|
313
|
+
const active = repos.find((r) => r.id === activeId);
|
|
314
|
+
if (!active) {
|
|
315
|
+
out.push({
|
|
316
|
+
actor: 'main',
|
|
317
|
+
action: '修正配置',
|
|
318
|
+
detail: `active_repo=${activeId} 不在 repos 列表中`,
|
|
319
|
+
blocking: true,
|
|
320
|
+
});
|
|
321
|
+
return out;
|
|
322
|
+
}
|
|
323
|
+
const m = active.currentMilestone;
|
|
324
|
+
if (active.milestones.length === 0) {
|
|
325
|
+
out.push({
|
|
326
|
+
actor: 'plan',
|
|
327
|
+
action: '补 PLAN.md / 里程碑',
|
|
328
|
+
detail: `${activeId} 没有解析到任何 M;先写 PLAN 的里程碑总览和 TODO-M1`,
|
|
329
|
+
repo: activeId,
|
|
330
|
+
blocking: false,
|
|
331
|
+
});
|
|
332
|
+
return out;
|
|
333
|
+
}
|
|
334
|
+
if (!m) {
|
|
335
|
+
out.push({
|
|
336
|
+
actor: 'main',
|
|
337
|
+
action: '阶段收尾',
|
|
338
|
+
detail: `${activeId} 所有 M 已验收;确认后 activate 下一个仓或进行阶段验收`,
|
|
339
|
+
repo: activeId,
|
|
340
|
+
blocking: false,
|
|
341
|
+
});
|
|
342
|
+
return out;
|
|
343
|
+
}
|
|
344
|
+
const base = { repo: activeId, milestone: m.id, blocking: false };
|
|
345
|
+
switch (m.status) {
|
|
346
|
+
case 'planned':
|
|
347
|
+
out.push({
|
|
348
|
+
...base,
|
|
349
|
+
actor: 'plan',
|
|
350
|
+
action: `写 TODO-${m.id}.md`,
|
|
351
|
+
detail: `${activeId} / ${m.id}「${m.title}」还没有 TODO;PLAN agent 按 PLAN 生成`,
|
|
352
|
+
});
|
|
353
|
+
break;
|
|
354
|
+
case 'todo_ready':
|
|
355
|
+
out.push({
|
|
356
|
+
...base,
|
|
357
|
+
actor: 'todo',
|
|
358
|
+
action: `claim 并实现 ${m.id}`,
|
|
359
|
+
detail: `${activeId} / ${m.id}「${m.title}」TODO 已就绪`,
|
|
360
|
+
});
|
|
361
|
+
break;
|
|
362
|
+
case 'implementing':
|
|
363
|
+
out.push({
|
|
364
|
+
...base,
|
|
365
|
+
actor: 'todo',
|
|
366
|
+
action: `实现并用 evidence_run 记录证据`,
|
|
367
|
+
detail: `${activeId} / ${m.id}「${m.title}」实现中;完成后调用 milestone_complete`,
|
|
368
|
+
});
|
|
369
|
+
break;
|
|
370
|
+
case 'review':
|
|
371
|
+
out.push({
|
|
372
|
+
...base,
|
|
373
|
+
actor: 'plan',
|
|
374
|
+
action: `验收 ${m.id}`,
|
|
375
|
+
detail: `${activeId} / ${m.id}「${m.title}」待验收;证据 ${m.evidence.length} 条`,
|
|
376
|
+
});
|
|
377
|
+
break;
|
|
378
|
+
case 'rejected':
|
|
379
|
+
out.push({
|
|
380
|
+
...base,
|
|
381
|
+
actor: 'todo',
|
|
382
|
+
action: `按打回意见返工 ${m.id}`,
|
|
383
|
+
detail: `${activeId} / ${m.id}「${m.title}」已被打回`,
|
|
384
|
+
});
|
|
385
|
+
break;
|
|
386
|
+
case 'accepted':
|
|
387
|
+
case 'committed':
|
|
388
|
+
out.push({
|
|
389
|
+
...base,
|
|
390
|
+
actor: 'user',
|
|
391
|
+
action: '评审并通过 commit',
|
|
392
|
+
detail: `${activeId} / ${m.id} 已验收,等待用户 review diff 后提权提交`,
|
|
393
|
+
});
|
|
394
|
+
break;
|
|
395
|
+
}
|
|
396
|
+
const repoBlocking = blocking.filter((q) => q.to === 'PLAN' || q.to === 'main');
|
|
397
|
+
if (repoBlocking.length === 0) {
|
|
398
|
+
// no-op; kept for clarity
|
|
399
|
+
}
|
|
400
|
+
return out;
|
|
401
|
+
}
|
|
402
|
+
/* --------------------------- mutations ---------------------------- */
|
|
403
|
+
setActiveRepo(id) {
|
|
404
|
+
if (id !== null) {
|
|
405
|
+
const ref = this.repoRef(id); // validate
|
|
406
|
+
if (!exists(ref.abs))
|
|
407
|
+
throw new Error(`仓库目录不存在: ${ref.abs}`);
|
|
408
|
+
}
|
|
409
|
+
withLock(this.root, 'program', () => {
|
|
410
|
+
this.cfg.active_repo = id;
|
|
411
|
+
this.save();
|
|
412
|
+
});
|
|
413
|
+
if (id) {
|
|
414
|
+
this.notifyEvent({
|
|
415
|
+
from: 'main',
|
|
416
|
+
to: this.cfg.repos.flatMap((r) => [
|
|
417
|
+
{ role: 'plan', repo: r.id },
|
|
418
|
+
{ role: 'todo', repo: r.id },
|
|
419
|
+
]),
|
|
420
|
+
kind: 'event',
|
|
421
|
+
subject: `active repo 切换为 ${id}`,
|
|
422
|
+
body: '串行锁:一次只激活一个仓。未激活的仓暂停实现。',
|
|
423
|
+
refs: { repo: id },
|
|
424
|
+
key: `activate:${id}:${Date.now()}`,
|
|
425
|
+
});
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
updatePhase(id, status) {
|
|
429
|
+
const p = this.cfg.phases.find((x) => x.id === id);
|
|
430
|
+
if (!p)
|
|
431
|
+
throw new Error(`未知阶段 ${id}`);
|
|
432
|
+
withLock(this.root, 'program', () => {
|
|
433
|
+
const idx = this.cfg.phases.indexOf(p);
|
|
434
|
+
// keep only one active phase
|
|
435
|
+
if (status === 'active') {
|
|
436
|
+
for (const q of this.cfg.phases)
|
|
437
|
+
if (q.status === 'active')
|
|
438
|
+
q.status = 'accepted';
|
|
439
|
+
}
|
|
440
|
+
this.cfg.phases[idx].status = status;
|
|
441
|
+
this.save();
|
|
442
|
+
});
|
|
443
|
+
}
|
|
444
|
+
todoPath(repoId, milestone) {
|
|
445
|
+
return path.join(this.repoRef(repoId).abs, `TODO-${milestone}.md`);
|
|
446
|
+
}
|
|
447
|
+
requireTodo(repoId, milestone) {
|
|
448
|
+
const abs = this.todoPath(repoId, milestone);
|
|
449
|
+
const doc = parseTodo(abs);
|
|
450
|
+
if (!doc)
|
|
451
|
+
throw new Error(`${repoId} 缺少 TODO-${milestone}.md;先由 PLAN agent 生成`);
|
|
452
|
+
return { abs, doc };
|
|
453
|
+
}
|
|
454
|
+
claim(repoId, milestone, role) {
|
|
455
|
+
this.assertNotBlocked(role, repoId);
|
|
456
|
+
const { abs, doc } = this.requireTodo(repoId, milestone);
|
|
457
|
+
if (!['todo_ready', 'rejected', 'planned'].includes(doc.status)) {
|
|
458
|
+
throw new Error(`${milestone} 当前状态为 ${doc.statusRaw},不能 claim(需 待实现/已打回)`);
|
|
459
|
+
}
|
|
460
|
+
writeAtomic(abs, setTodoStatus(readTextRequired(abs), 'implementing'));
|
|
461
|
+
logEvent(this.root, { role, tool: 'milestone_claim', repo: repoId, milestone, ok: true });
|
|
462
|
+
this.notifyEvent({
|
|
463
|
+
from: role,
|
|
464
|
+
repo: repoId,
|
|
465
|
+
to: [{ role: 'plan', repo: repoId }],
|
|
466
|
+
kind: 'event',
|
|
467
|
+
subject: `${repoId}/${milestone} 开始实现`,
|
|
468
|
+
refs: { repo: repoId, milestone },
|
|
469
|
+
key: `${repoId}:${milestone}:claim`,
|
|
470
|
+
});
|
|
471
|
+
return this.milestone(repoId, milestone);
|
|
472
|
+
}
|
|
473
|
+
complete(repoId, milestone, role) {
|
|
474
|
+
this.assertNotBlocked(role, repoId);
|
|
475
|
+
const { abs, doc } = this.requireTodo(repoId, milestone);
|
|
476
|
+
if (doc.status !== 'implementing') {
|
|
477
|
+
throw new Error(`${milestone} 当前状态为 ${doc.statusRaw},不能 complete(需 实现中)`);
|
|
478
|
+
}
|
|
479
|
+
const evidence = parseEvidence(doc);
|
|
480
|
+
if (evidence.length === 0) {
|
|
481
|
+
throw new Error(`${milestone} 没有任何证据;先调用 evidence_run 运行测试/构建`);
|
|
482
|
+
}
|
|
483
|
+
writeAtomic(abs, setTodoStatus(readTextRequired(abs), 'review'));
|
|
484
|
+
logEvent(this.root, { role, tool: 'milestone_complete', repo: repoId, milestone, ok: true });
|
|
485
|
+
this.notifyEvent({
|
|
486
|
+
from: role,
|
|
487
|
+
repo: repoId,
|
|
488
|
+
to: [{ role: 'plan', repo: repoId }],
|
|
489
|
+
kind: 'event',
|
|
490
|
+
subject: `${repoId}/${milestone} 实现完成,待验收`,
|
|
491
|
+
body: `证据 ${evidence.length} 条;最后一条 ${evidence[evidence.length - 1]?.command || '-'}`,
|
|
492
|
+
refs: {
|
|
493
|
+
repo: repoId,
|
|
494
|
+
milestone,
|
|
495
|
+
evidence_id: evidence[evidence.length - 1]?.id || '',
|
|
496
|
+
},
|
|
497
|
+
key: `${repoId}:${milestone}:complete:${evidence.length}`,
|
|
498
|
+
});
|
|
499
|
+
return this.milestone(repoId, milestone);
|
|
500
|
+
}
|
|
501
|
+
milestone(repoId, milestone) {
|
|
502
|
+
const st = this.repoState(repoId);
|
|
503
|
+
const m = st.milestones.find((x) => x.id === milestone);
|
|
504
|
+
if (!m)
|
|
505
|
+
throw new Error(`${repoId} 没有里程碑 ${milestone}`);
|
|
506
|
+
return m;
|
|
507
|
+
}
|
|
508
|
+
accept(repoId, milestone, role, opts = {}) {
|
|
509
|
+
if (role !== 'plan' && role !== 'main') {
|
|
510
|
+
throw new Error(`只有 PLAN/主 agent 能验收;当前角色 ${role}`);
|
|
511
|
+
}
|
|
512
|
+
this.assertNotBlocked(role, repoId);
|
|
513
|
+
const { abs, doc } = this.requireTodo(repoId, milestone);
|
|
514
|
+
if (doc.status !== 'review' && !opts.force) {
|
|
515
|
+
throw new Error(`${milestone} 当前状态为 ${doc.statusRaw},需先 milestone_complete 进入待验收`);
|
|
516
|
+
}
|
|
517
|
+
const evidence = parseEvidence(doc);
|
|
518
|
+
const passing = evidence.filter((e) => e.exitCode === 0);
|
|
519
|
+
if (passing.length === 0 && !opts.force) {
|
|
520
|
+
throw new Error(`${milestone} 没有成功的证据(exit=0);拒绝验收`);
|
|
521
|
+
}
|
|
522
|
+
const ref = this.repoRef(repoId);
|
|
523
|
+
const gi = gitInfo(ref.abs);
|
|
524
|
+
const currentHash = workingTreeHash(ref.abs);
|
|
525
|
+
const latest = passing[passing.length - 1];
|
|
526
|
+
let note = opts.note || '';
|
|
527
|
+
if (latest?.tree && latest.tree !== workingTreeOid(ref.abs)) {
|
|
528
|
+
note += '\n⚠️ 最新证据之后工作区又发生了变化,建议重新跑 evidence_run。';
|
|
529
|
+
}
|
|
530
|
+
let text = readTextRequired(abs);
|
|
531
|
+
text = setTodoStatus(text, 'accepted');
|
|
532
|
+
text = setTodoSha(text, gi.head || 'working-tree');
|
|
533
|
+
text = appendReview(text, {
|
|
534
|
+
at: isoNow(),
|
|
535
|
+
action: 'accept',
|
|
536
|
+
by: role,
|
|
537
|
+
note: note.trim(),
|
|
538
|
+
head: gi.shortHead,
|
|
539
|
+
dirty: gi.dirty,
|
|
540
|
+
evidence: latest ? `${latest.command} (exit ${latest.exitCode})` : '(force)',
|
|
541
|
+
});
|
|
542
|
+
writeAtomic(abs, text);
|
|
543
|
+
logEvent(this.root, {
|
|
544
|
+
role,
|
|
545
|
+
tool: 'milestone_accept',
|
|
546
|
+
repo: repoId,
|
|
547
|
+
milestone,
|
|
548
|
+
ok: true,
|
|
549
|
+
detail: { head: gi.head, tree_hash: currentHash, evidence: evidence.length },
|
|
550
|
+
});
|
|
551
|
+
this.notifyEvent({
|
|
552
|
+
from: role,
|
|
553
|
+
repo: repoId,
|
|
554
|
+
to: [{ role: 'main' }, { role: 'user' }],
|
|
555
|
+
kind: 'event',
|
|
556
|
+
subject: `${repoId}/${milestone} 已验收,待 review/提交`,
|
|
557
|
+
body: `受验 SHA ${gi.head || 'working-tree'};证据 ${evidence.length} 条。`,
|
|
558
|
+
refs: { repo: repoId, milestone, sha: gi.head || '' },
|
|
559
|
+
key: `${repoId}:${milestone}:accept:${gi.head || 'wt'}`,
|
|
560
|
+
});
|
|
561
|
+
return this.milestone(repoId, milestone);
|
|
562
|
+
}
|
|
563
|
+
reject(repoId, milestone, role, reason) {
|
|
564
|
+
if (role !== 'plan' && role !== 'main') {
|
|
565
|
+
throw new Error(`只有 PLAN/主 agent 能打回;当前角色 ${role}`);
|
|
566
|
+
}
|
|
567
|
+
if (!reason.trim())
|
|
568
|
+
throw new Error('打回必须写原因');
|
|
569
|
+
this.assertNotBlocked(role, repoId);
|
|
570
|
+
const { abs, doc } = this.requireTodo(repoId, milestone);
|
|
571
|
+
if (doc.status !== 'review') {
|
|
572
|
+
throw new Error(`${milestone} 当前状态为 ${doc.statusRaw},只有待验收的 M 可以打回`);
|
|
573
|
+
}
|
|
574
|
+
const gi = gitInfo(this.repoRef(repoId).abs);
|
|
575
|
+
let text = readTextRequired(abs);
|
|
576
|
+
text = setTodoStatus(text, 'rejected');
|
|
577
|
+
text = appendReview(text, {
|
|
578
|
+
at: isoNow(),
|
|
579
|
+
action: 'reject',
|
|
580
|
+
by: role,
|
|
581
|
+
note: reason,
|
|
582
|
+
head: gi.shortHead,
|
|
583
|
+
dirty: gi.dirty,
|
|
584
|
+
evidence: '',
|
|
585
|
+
});
|
|
586
|
+
writeAtomic(abs, text);
|
|
587
|
+
logEvent(this.root, {
|
|
588
|
+
role,
|
|
589
|
+
tool: 'milestone_reject',
|
|
590
|
+
repo: repoId,
|
|
591
|
+
milestone,
|
|
592
|
+
ok: true,
|
|
593
|
+
detail: { reason },
|
|
594
|
+
});
|
|
595
|
+
this.notifyEvent({
|
|
596
|
+
from: role,
|
|
597
|
+
repo: repoId,
|
|
598
|
+
to: [{ role: 'todo', repo: repoId }],
|
|
599
|
+
kind: 'event',
|
|
600
|
+
subject: `${repoId}/${milestone} 被打回`,
|
|
601
|
+
body: reason,
|
|
602
|
+
refs: { repo: repoId, milestone, reason },
|
|
603
|
+
key: `${repoId}:${milestone}:reject:${Date.now()}`,
|
|
604
|
+
});
|
|
605
|
+
return this.milestone(repoId, milestone);
|
|
606
|
+
}
|
|
607
|
+
/* ---------------------------- evidence ----------------------------- */
|
|
608
|
+
async runEvidence(input) {
|
|
609
|
+
const { repoId, milestone, command, role } = input;
|
|
610
|
+
const ref = this.repoRef(repoId);
|
|
611
|
+
const { abs, doc } = this.requireTodo(repoId, milestone);
|
|
612
|
+
const cwd = input.cwd ? path.resolve(ref.abs, input.cwd) : ref.abs;
|
|
613
|
+
if (!within(ref.abs, cwd))
|
|
614
|
+
throw new Error(`evidence cwd 必须在仓库内: ${cwd}`);
|
|
615
|
+
const started = Date.now();
|
|
616
|
+
const result = await runCommand(command, cwd, input.timeoutMs ?? 900_000);
|
|
617
|
+
const gi = gitInfo(ref.abs);
|
|
618
|
+
const tree = workingTreeOid(ref.abs);
|
|
619
|
+
const list = parseEvidence(doc);
|
|
620
|
+
const id = `E${list.length + 1}`;
|
|
621
|
+
const at = isoNow();
|
|
622
|
+
const fullOutput = [
|
|
623
|
+
`$ ${command}`,
|
|
624
|
+
`exit: ${result.code}`,
|
|
625
|
+
`head: ${gi.head}`,
|
|
626
|
+
`tree: ${tree}`,
|
|
627
|
+
`dirty: ${gi.dirty}`,
|
|
628
|
+
'',
|
|
629
|
+
'--- stdout ---',
|
|
630
|
+
result.stdout,
|
|
631
|
+
'--- stderr ---',
|
|
632
|
+
result.stderr,
|
|
633
|
+
].join('\n');
|
|
634
|
+
const dir = path.join(evidenceDir(this.root), repoId, milestone);
|
|
635
|
+
ensureDir(dir);
|
|
636
|
+
writeAtomic(path.join(dir, `${id}-${Date.now()}.log`), fullOutput);
|
|
637
|
+
const tail = truncate([result.stdout, result.stderr].filter(Boolean).join('\n'), 4000);
|
|
638
|
+
const text = appendEvidenceSection(readTextRequired(abs), {
|
|
639
|
+
id,
|
|
640
|
+
at,
|
|
641
|
+
command,
|
|
642
|
+
exitCode: result.code,
|
|
643
|
+
head: gi.shortHead,
|
|
644
|
+
tree,
|
|
645
|
+
dirty: gi.dirty,
|
|
646
|
+
output: tail,
|
|
647
|
+
});
|
|
648
|
+
writeAtomic(abs, text);
|
|
649
|
+
logEvent(this.root, {
|
|
650
|
+
role,
|
|
651
|
+
tool: 'evidence_run',
|
|
652
|
+
repo: repoId,
|
|
653
|
+
milestone,
|
|
654
|
+
ok: result.code === 0,
|
|
655
|
+
detail: { command, exit: result.code, ms: Date.now() - started },
|
|
656
|
+
});
|
|
657
|
+
return {
|
|
658
|
+
id,
|
|
659
|
+
exitCode: result.code,
|
|
660
|
+
head: gi.shortHead,
|
|
661
|
+
tree,
|
|
662
|
+
dirty: gi.dirty,
|
|
663
|
+
output: tail,
|
|
664
|
+
todoFile: path.relative(this.root, abs),
|
|
665
|
+
};
|
|
666
|
+
}
|
|
667
|
+
/* --------------------------- scope check --------------------------- */
|
|
668
|
+
scopeCheck(repoId, milestone, role = 'todo', opts = {}) {
|
|
669
|
+
const enforceAcl = opts.enforceAcl ?? role === 'todo';
|
|
670
|
+
const ref = this.repoRef(repoId);
|
|
671
|
+
const changed = allChangedFiles(ref.abs);
|
|
672
|
+
const st = this.repoState(repoId);
|
|
673
|
+
const m = milestone
|
|
674
|
+
? st.milestones.find((x) => x.id === milestone)
|
|
675
|
+
: st.currentMilestone;
|
|
676
|
+
const todo = m ? parseTodo(path.join(ref.abs, `TODO-${m.id}.md`)) : null;
|
|
677
|
+
const allowed = todo?.allowedFiles || [];
|
|
678
|
+
const violations = [];
|
|
679
|
+
const outOfScope = [];
|
|
680
|
+
const warnings = [];
|
|
681
|
+
const repos = this.repoRefs().map((r) => ({ id: r.id, abs: r.abs }));
|
|
682
|
+
if (enforceAcl) {
|
|
683
|
+
for (const f of changed) {
|
|
684
|
+
if (isWorkflowManaged(f))
|
|
685
|
+
continue; // workflow tools maintain these by design
|
|
686
|
+
const abs = path.join(ref.abs, f);
|
|
687
|
+
const acl = checkAcl(role, abs, this.root, repoId, ref.abs, repos);
|
|
688
|
+
if (!acl.allowed)
|
|
689
|
+
violations.push({ file: f, reason: acl.reason });
|
|
690
|
+
}
|
|
691
|
+
}
|
|
692
|
+
if (allowed.length > 0) {
|
|
693
|
+
for (const f of changed) {
|
|
694
|
+
if (isWorkflowManaged(f))
|
|
695
|
+
continue;
|
|
696
|
+
const ok = allowed.some((a) => globMatchPath(f, a));
|
|
697
|
+
if (!ok) {
|
|
698
|
+
outOfScope.push(f);
|
|
699
|
+
warnings.push(`${f} 不在 TODO 声明的「影响文件」里`);
|
|
700
|
+
}
|
|
701
|
+
}
|
|
702
|
+
}
|
|
703
|
+
else if (changed.length > 0) {
|
|
704
|
+
warnings.push('TODO 未声明可修改文件清单,只能按角色 ACL 判断');
|
|
705
|
+
}
|
|
706
|
+
return {
|
|
707
|
+
repo: repoId,
|
|
708
|
+
milestone: m?.id,
|
|
709
|
+
changed: changed.filter((f) => !isWorkflowManaged(f)),
|
|
710
|
+
allowedFiles: allowed,
|
|
711
|
+
outOfScope,
|
|
712
|
+
violations,
|
|
713
|
+
warnings,
|
|
714
|
+
pass: violations.length === 0,
|
|
715
|
+
};
|
|
716
|
+
}
|
|
717
|
+
/* ----------------------------- commit ------------------------------ */
|
|
718
|
+
requestCommit(input) {
|
|
719
|
+
const ref = this.repoRef(input.repoId);
|
|
720
|
+
const files = allChangedFiles(ref.abs);
|
|
721
|
+
if (files.length === 0)
|
|
722
|
+
throw new Error('没有可提交的改动');
|
|
723
|
+
const scope = this.scopeCheck(input.repoId, undefined, input.role, { enforceAcl: false });
|
|
724
|
+
assertCommitScope(scope, input.role);
|
|
725
|
+
const a = createApproval(this.root, {
|
|
726
|
+
repo: input.repoId,
|
|
727
|
+
tree_hash: workingTreeHash(ref.abs),
|
|
728
|
+
message: input.message,
|
|
729
|
+
files,
|
|
730
|
+
});
|
|
731
|
+
logEvent(this.root, {
|
|
732
|
+
role: input.role,
|
|
733
|
+
tool: 'commit_request',
|
|
734
|
+
repo: input.repoId,
|
|
735
|
+
ok: true,
|
|
736
|
+
detail: { approval: a.id, files: files.length },
|
|
737
|
+
});
|
|
738
|
+
this.notifyEvent({
|
|
739
|
+
from: input.role,
|
|
740
|
+
repo: input.repoId,
|
|
741
|
+
to: [{ role: 'user' }],
|
|
742
|
+
kind: 'approval_request',
|
|
743
|
+
subject: `${input.repoId} 请求提交:${input.message}`,
|
|
744
|
+
body: `${files.length} 个文件\n${diffStat(ref.abs)}`,
|
|
745
|
+
refs: {
|
|
746
|
+
repo: input.repoId,
|
|
747
|
+
approval_id: a.id,
|
|
748
|
+
files,
|
|
749
|
+
},
|
|
750
|
+
key: `${input.repoId}:commit-request:${a.id}`,
|
|
751
|
+
});
|
|
752
|
+
return { approval: a, diffStat: diffStat(ref.abs), files };
|
|
753
|
+
}
|
|
754
|
+
approve(id, by = 'user') {
|
|
755
|
+
const a = readApproval(this.root, id);
|
|
756
|
+
if (!a)
|
|
757
|
+
throw new Error(`审批 ${id} 不存在`);
|
|
758
|
+
if (a.used_at)
|
|
759
|
+
throw new Error(`审批 ${id} 已使用`);
|
|
760
|
+
a.approved_at = isoNow();
|
|
761
|
+
a.approved_by = by;
|
|
762
|
+
writeApproval(this.root, a);
|
|
763
|
+
logEvent(this.root, { role: 'user', tool: 'approve', repo: a.repo, ok: true, detail: { approval: id } });
|
|
764
|
+
// Approving is how the human handles the notification; clear it from the inbox.
|
|
765
|
+
try {
|
|
766
|
+
this.msgs.ackByRef({ role: 'user' }, 'approval_id', id);
|
|
767
|
+
}
|
|
768
|
+
catch {
|
|
769
|
+
/* the approval is recorded; notification cleanup is best-effort */
|
|
770
|
+
}
|
|
771
|
+
return a;
|
|
772
|
+
}
|
|
773
|
+
commitApproved(input) {
|
|
774
|
+
const ref = this.repoRef(input.repoId);
|
|
775
|
+
const a = readApproval(this.root, input.approvalId);
|
|
776
|
+
if (!a)
|
|
777
|
+
throw new Error(`审批 ${input.approvalId} 不存在`);
|
|
778
|
+
if (a.repo !== input.repoId)
|
|
779
|
+
throw new Error(`审批属于 ${a.repo},不是 ${input.repoId}`);
|
|
780
|
+
if (!a.approved_at)
|
|
781
|
+
throw new Error(`审批 ${a.id} 尚未由用户批准(mpt-workflow approve ${a.id})`);
|
|
782
|
+
if (a.used_at)
|
|
783
|
+
throw new Error(`审批 ${a.id} 已在 ${a.used_at} 使用`);
|
|
784
|
+
const hash = workingTreeHash(ref.abs);
|
|
785
|
+
if (hash !== a.tree_hash) {
|
|
786
|
+
throw new Error(`工作区内容已变化(审批时 ${a.tree_hash},现在 ${hash});请重新 commit_request 并批准`);
|
|
787
|
+
}
|
|
788
|
+
const scope = this.scopeCheck(input.repoId, undefined, input.role, { enforceAcl: false });
|
|
789
|
+
assertCommitScope(scope, input.role);
|
|
790
|
+
const files = allChangedFiles(ref.abs);
|
|
791
|
+
if (input.dryRun) {
|
|
792
|
+
return { dryRun: true, files, message: a.message, tree_hash: hash };
|
|
793
|
+
}
|
|
794
|
+
const stage = stageAll(ref.abs);
|
|
795
|
+
if (!stage.ok)
|
|
796
|
+
throw new Error(`git add 失败: ${stage.err}`);
|
|
797
|
+
const res = gitCommit(ref.abs, a.message);
|
|
798
|
+
if (!res.ok)
|
|
799
|
+
throw new Error(`git commit 失败: ${res.err || res.out}`);
|
|
800
|
+
const head = gitInfo(ref.abs).head;
|
|
801
|
+
a.used_at = isoNow();
|
|
802
|
+
writeApproval(this.root, a);
|
|
803
|
+
logEvent(this.root, {
|
|
804
|
+
role: input.role,
|
|
805
|
+
tool: 'commit',
|
|
806
|
+
repo: input.repoId,
|
|
807
|
+
ok: true,
|
|
808
|
+
detail: { approval: a.id, head, files: files.length },
|
|
809
|
+
});
|
|
810
|
+
this.notifyEvent({
|
|
811
|
+
from: input.role,
|
|
812
|
+
repo: input.repoId,
|
|
813
|
+
to: [{ role: 'main' }, { role: 'user' }],
|
|
814
|
+
kind: 'event',
|
|
815
|
+
subject: `${input.repoId} 已提交 @ ${head.slice(0, 8)}`,
|
|
816
|
+
body: a.message,
|
|
817
|
+
refs: { repo: input.repoId, commit: head, sha: head, approval_id: a.id },
|
|
818
|
+
key: `${input.repoId}:commit:${head}`,
|
|
819
|
+
});
|
|
820
|
+
return { ok: true, head, files, message: a.message };
|
|
821
|
+
}
|
|
822
|
+
approvals() {
|
|
823
|
+
return listApprovals(this.root);
|
|
824
|
+
}
|
|
825
|
+
/* ----------------------------- doctor ------------------------------ */
|
|
826
|
+
doctor() {
|
|
827
|
+
const out = [];
|
|
828
|
+
const push = (f) => out.push(f);
|
|
829
|
+
// config
|
|
830
|
+
if (!exists(path.join(this.root, '.workflow/program.yaml'))) {
|
|
831
|
+
push({ level: 'FAIL', code: 'config', message: '缺少 .workflow/program.yaml' });
|
|
832
|
+
}
|
|
833
|
+
const active = this.cfg.active_repo;
|
|
834
|
+
if (active && !this.cfg.repos.some((r) => r.id === active)) {
|
|
835
|
+
push({ level: 'FAIL', code: 'active-repo', message: `active_repo=${active} 不在 repos 列表` });
|
|
836
|
+
}
|
|
837
|
+
if (!active) {
|
|
838
|
+
push({ level: 'WARN', code: 'active-repo', message: '没有激活的仓库,所有实现工作都会停滞', hint: 'mpt-workflow activate <repo>' });
|
|
839
|
+
}
|
|
840
|
+
for (const ref of this.repoRefs()) {
|
|
841
|
+
if (!exists(ref.abs)) {
|
|
842
|
+
push({ level: 'FAIL', code: 'repo-missing', repo: ref.id, message: `仓库目录不存在: ${ref.abs}` });
|
|
843
|
+
continue;
|
|
844
|
+
}
|
|
845
|
+
const conf = this.repoConfig(ref.id);
|
|
846
|
+
const gi = gitInfo(ref.abs);
|
|
847
|
+
if (!gi.available) {
|
|
848
|
+
push({ level: 'FAIL', code: 'git', repo: ref.id, message: '不是 git 仓库或无法读取 HEAD', hint: gi.error });
|
|
849
|
+
continue;
|
|
850
|
+
}
|
|
851
|
+
if (conf.branch && gi.branch && conf.branch !== gi.branch) {
|
|
852
|
+
push({
|
|
853
|
+
level: 'WARN',
|
|
854
|
+
code: 'branch',
|
|
855
|
+
repo: ref.id,
|
|
856
|
+
message: `配置分支 ${conf.branch},当前 ${gi.branch}`,
|
|
857
|
+
});
|
|
858
|
+
}
|
|
859
|
+
if (gi.dirty) {
|
|
860
|
+
const lock = gi.changed.filter((f) => f.endsWith('Cargo.lock'));
|
|
861
|
+
push({
|
|
862
|
+
level: lock.length ? 'FAIL' : 'WARN',
|
|
863
|
+
code: 'dirty',
|
|
864
|
+
repo: ref.id,
|
|
865
|
+
message: `工作区有未提交改动 ${gi.changed.length + gi.untracked.length} 个`,
|
|
866
|
+
hint: gi.changed.concat(gi.untracked).slice(0, 8).join(', '),
|
|
867
|
+
});
|
|
868
|
+
if (lock.length) {
|
|
869
|
+
push({
|
|
870
|
+
level: 'FAIL',
|
|
871
|
+
code: 'cargo-lock',
|
|
872
|
+
repo: ref.id,
|
|
873
|
+
message: 'Cargo.lock 被修改;依赖版本漂移会破坏跨仓契约',
|
|
874
|
+
hint: 'git diff Cargo.lock 确认后回滚或显式锁定',
|
|
875
|
+
});
|
|
876
|
+
}
|
|
877
|
+
}
|
|
878
|
+
if (!exists(path.join(ref.abs, 'PLAN.md'))) {
|
|
879
|
+
push({ level: 'WARN', code: 'plan', repo: ref.id, message: '缺少 PLAN.md' });
|
|
880
|
+
}
|
|
881
|
+
if (!exists(questionsFile(ref.abs))) {
|
|
882
|
+
push({
|
|
883
|
+
level: 'WARN',
|
|
884
|
+
code: 'questions',
|
|
885
|
+
repo: ref.id,
|
|
886
|
+
message: '缺少 docs/agent-questions.md(CLAUDE.md 要求 agent 写这里)',
|
|
887
|
+
hint: 'mpt-workflow init --adopt 会创建',
|
|
888
|
+
});
|
|
889
|
+
}
|
|
890
|
+
if (exists(path.join(ref.abs, 'rust-toolchain.toml'))) {
|
|
891
|
+
const tc = readText(path.join(ref.abs, 'rust-toolchain.toml'));
|
|
892
|
+
const ch = /channel\s*=\s*"([^"]+)"/.exec(tc)?.[1];
|
|
893
|
+
if (ch && ch.includes('nightly')) {
|
|
894
|
+
push({ level: 'OK', code: 'toolchain', repo: ref.id, message: `rust-toolchain: ${ch}` });
|
|
895
|
+
}
|
|
896
|
+
}
|
|
897
|
+
if (exists(path.join(ref.abs, 'Cargo.toml')) && !exists(path.join(ref.abs, 'Cargo.lock'))) {
|
|
898
|
+
push({ level: 'WARN', code: 'cargo-lock-missing', repo: ref.id, message: 'Cargo.toml 存在但没有 Cargo.lock' });
|
|
899
|
+
}
|
|
900
|
+
// questions parse health
|
|
901
|
+
const qs = exists(questionsFile(ref.abs))
|
|
902
|
+
? parseQuestionsFile(questionsFile(ref.abs), ref.id)
|
|
903
|
+
: [];
|
|
904
|
+
const openBlocking = qs.filter((q) => q.blocking && q.status === 'open');
|
|
905
|
+
if (openBlocking.length) {
|
|
906
|
+
push({
|
|
907
|
+
level: 'FAIL',
|
|
908
|
+
code: 'blocking-question',
|
|
909
|
+
repo: ref.id,
|
|
910
|
+
message: `${openBlocking.length} 个阻塞问题未回答: ${openBlocking.map((q) => q.id).join(', ')}`,
|
|
911
|
+
});
|
|
912
|
+
}
|
|
913
|
+
const st = this.repoState(ref.id);
|
|
914
|
+
if (st.milestones.length === 0) {
|
|
915
|
+
push({ level: 'WARN', code: 'milestones', repo: ref.id, message: '没有 M(PLAN 表未解析到,也没有 TODO)' });
|
|
916
|
+
}
|
|
917
|
+
const acceptedDirty = st.milestones.filter((m) => m.status === 'accepted');
|
|
918
|
+
if (acceptedDirty.length && gi.dirty) {
|
|
919
|
+
push({
|
|
920
|
+
level: 'WARN',
|
|
921
|
+
code: 'accepted-uncommitted',
|
|
922
|
+
repo: ref.id,
|
|
923
|
+
message: `${acceptedDirty.map((m) => m.id).join(', ')} 已验收但工作区未提交`,
|
|
924
|
+
});
|
|
925
|
+
}
|
|
926
|
+
}
|
|
927
|
+
for (const a of this.approvals().filter((x) => !x.used_at)) {
|
|
928
|
+
push({
|
|
929
|
+
level: a.approved_at ? 'WARN' : 'OK',
|
|
930
|
+
code: 'approval',
|
|
931
|
+
repo: a.repo,
|
|
932
|
+
message: a.approved_at
|
|
933
|
+
? `审批 ${a.id} 已批准但未使用`
|
|
934
|
+
: `审批 ${a.id} 等待用户批准`,
|
|
935
|
+
hint: `mpt-workflow approve ${a.id}`,
|
|
936
|
+
});
|
|
937
|
+
}
|
|
938
|
+
if (!out.some((f) => f.level === 'FAIL')) {
|
|
939
|
+
push({ level: 'OK', code: 'overall', message: '没有阻断性问题' });
|
|
940
|
+
}
|
|
941
|
+
return out;
|
|
942
|
+
}
|
|
943
|
+
}
|
|
944
|
+
/* ------------------------------ helpers ------------------------------ */
|
|
945
|
+
/**
|
|
946
|
+
* Files the workflow tools themselves maintain. They are excluded from scope
|
|
947
|
+
* checks and from the pre-commit ACL backstop: the TODO status line and the
|
|
948
|
+
* questions board change as a normal part of the workflow.
|
|
949
|
+
*/
|
|
950
|
+
export function isMachineManagedFile(file) {
|
|
951
|
+
return (/^TODO-M\d+\.md$/.test(file) ||
|
|
952
|
+
file === 'docs/agent-questions.md' ||
|
|
953
|
+
file === '.mcp.json' ||
|
|
954
|
+
file.startsWith('.claude/') ||
|
|
955
|
+
file.startsWith('.workflow/'));
|
|
956
|
+
}
|
|
957
|
+
/** Machine-managed files plus the plan itself (derived-scope checks only). */
|
|
958
|
+
export function isWorkflowManaged(file) {
|
|
959
|
+
return file === 'PLAN.md' || isMachineManagedFile(file);
|
|
960
|
+
}
|
|
961
|
+
function assertCommitScope(scope, role) {
|
|
962
|
+
// The TODO file list describes implementation scope. A plan/main commit that
|
|
963
|
+
// adds planning docs is not scope creep, so only enforce it for the implementer.
|
|
964
|
+
const outOfScope = role === 'todo' ? scope.outOfScope : [];
|
|
965
|
+
if (!scope.violations.length && !outOfScope.length)
|
|
966
|
+
return;
|
|
967
|
+
const lines = [
|
|
968
|
+
...scope.violations.map((v) => `${v.file}: ${v.reason}`),
|
|
969
|
+
...outOfScope.map((f) => `${f}: 不在当前 TODO 的「影响文件」清单内`),
|
|
970
|
+
];
|
|
971
|
+
throw new Error('scope 检查未通过,不能提交:\n' +
|
|
972
|
+
lines.map((l) => `- ${l}`).join('\n') +
|
|
973
|
+
'\n把相关文件加入 TODO 的「影响文件」,或撤销这些改动后重新 commit_request。');
|
|
974
|
+
}
|
|
975
|
+
function runCommand(command, cwd, timeoutMs) {
|
|
976
|
+
return new Promise((resolve) => {
|
|
977
|
+
// `detached` gives the shell its own process group, so a timeout can kill
|
|
978
|
+
// the whole tree instead of leaving orphaned test/build processes behind.
|
|
979
|
+
const child = spawn('/bin/bash', ['-lc', command], {
|
|
980
|
+
cwd,
|
|
981
|
+
detached: true,
|
|
982
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
983
|
+
});
|
|
984
|
+
const maxBytes = 64 * 1024 * 1024;
|
|
985
|
+
let stdout = '';
|
|
986
|
+
let stderr = '';
|
|
987
|
+
let bytes = 0;
|
|
988
|
+
let timedOut = false;
|
|
989
|
+
const collect = (chunk, into) => {
|
|
990
|
+
if (bytes >= maxBytes)
|
|
991
|
+
return;
|
|
992
|
+
bytes += chunk.length;
|
|
993
|
+
if (into === 'out')
|
|
994
|
+
stdout += chunk.toString('utf8');
|
|
995
|
+
else
|
|
996
|
+
stderr += chunk.toString('utf8');
|
|
997
|
+
};
|
|
998
|
+
child.stdout?.on('data', (chunk) => collect(chunk, 'out'));
|
|
999
|
+
child.stderr?.on('data', (chunk) => collect(chunk, 'err'));
|
|
1000
|
+
const timer = setTimeout(() => {
|
|
1001
|
+
timedOut = true;
|
|
1002
|
+
try {
|
|
1003
|
+
if (child.pid)
|
|
1004
|
+
process.kill(-child.pid, 'SIGKILL');
|
|
1005
|
+
else
|
|
1006
|
+
child.kill('SIGKILL');
|
|
1007
|
+
}
|
|
1008
|
+
catch {
|
|
1009
|
+
child.kill('SIGKILL');
|
|
1010
|
+
}
|
|
1011
|
+
}, timeoutMs);
|
|
1012
|
+
child.on('error', (err) => {
|
|
1013
|
+
clearTimeout(timer);
|
|
1014
|
+
resolve({ code: 1, stdout, stderr: `${stderr}${err.message}` });
|
|
1015
|
+
});
|
|
1016
|
+
child.on('close', (code) => {
|
|
1017
|
+
clearTimeout(timer);
|
|
1018
|
+
if (timedOut)
|
|
1019
|
+
stderr += `\n[timeout after ${timeoutMs}ms]`;
|
|
1020
|
+
resolve({
|
|
1021
|
+
code: timedOut ? 124 : typeof code === 'number' ? code : 1,
|
|
1022
|
+
stdout,
|
|
1023
|
+
stderr,
|
|
1024
|
+
});
|
|
1025
|
+
});
|
|
1026
|
+
});
|
|
1027
|
+
}
|
|
1028
|
+
function globMatchPath(file, pattern) {
|
|
1029
|
+
const p = pattern.replace(/^\.\//, '');
|
|
1030
|
+
if (p === file)
|
|
1031
|
+
return true;
|
|
1032
|
+
const esc = p.replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*\*/g, '\u0000').replace(/\*/g, '[^/]*').replace(/\u0000/g, '.*');
|
|
1033
|
+
return new RegExp('^' + esc + '$').test(file);
|
|
1034
|
+
}
|
|
1035
|
+
function appendReview(text, r) {
|
|
1036
|
+
const header = '## 验收记录';
|
|
1037
|
+
const line = [
|
|
1038
|
+
`- ${r.at} **${r.action === 'accept' ? '通过' : '打回'}** by ${r.by} — head ${r.head}${r.dirty ? ' (dirty)' : ''}`,
|
|
1039
|
+
r.evidence ? ` - 依据: ${r.evidence}` : '',
|
|
1040
|
+
r.note ? ` - 说明: ${r.note.replace(/\n/g, ' ')}` : '',
|
|
1041
|
+
]
|
|
1042
|
+
.filter(Boolean)
|
|
1043
|
+
.join('\n');
|
|
1044
|
+
const withHeader = /^##\s+验收记录/m.test(text)
|
|
1045
|
+
? text
|
|
1046
|
+
: text.replace(/\s*$/, '\n\n') + `${header}\n`;
|
|
1047
|
+
return appendToSection(withHeader, /验收记录/, line);
|
|
1048
|
+
}
|
|
1049
|
+
export { statusLabel };
|
|
1050
|
+
//# sourceMappingURL=workflow.js.map
|