@kangyishuai/dsh-projects 0.0.0-stage → 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/lib/service.js ADDED
@@ -0,0 +1,1710 @@
1
+ // @ts-check
2
+ // host 半的 Typert Remote Service:项目 CRUD、会话归属、上下文注入的挂载点。
3
+ // 注意(docs/runtime/0.2.1-rc.5.md §6.10):Remote 方法必须声明在**这个被导出的类自身原型**上,
4
+ // 否则网关不会 claim 端点,所有 /api/projects/* 返回 404。
5
+ import {
6
+ existsSync,
7
+ mkdirSync,
8
+ readdirSync,
9
+ readFileSync,
10
+ renameSync,
11
+ statSync,
12
+ writeFileSync,
13
+ } from "node:fs";
14
+ import { dirname, join } from "node:path";
15
+
16
+ import { Remote, TypertRemoteService } from "@deepseek-ai/dsh-typert-protocol";
17
+
18
+ import { registerProjectContext } from "./attach.js";
19
+ import { buildFixTask, errorSignature, shouldContinueFix } from "./autofix.js";
20
+ import { buildPrText, nextPrAction, parsePrNumber, planPrCreate } from "./autopr.js";
21
+ import { checkThreadBudget, checkTokenBudget, tokensOf } from "./budget.js";
22
+ import { runCommand } from "./exec.js";
23
+ import { checkExecutable, planCommand, recoveryEvidence } from "./executor.js";
24
+ import { appendEntry } from "./memory.js";
25
+ import { initialView, reduce, sortRows } from "./overview.js";
26
+ import { buildPersona } from "./persona.js";
27
+ import { readProjectFiles } from "./project-files.js";
28
+ import { decideRoute } from "./routing.js";
29
+ import { ProjectStore } from "./store.js";
30
+ import { createIsolatedThread, reclaimThreadWorktree, reconcileWorktrees } from "./thread.js";
31
+ import { buildCoordinatorTools, REQUESTABLE_ACTIONS } from "./tools.js";
32
+ import { impactOf, trashDirFor } from "./trash.js";
33
+ import { buildEnvelope, createInjectionGuard, decideWake, pendingWakes } from "./wake.js";
34
+
35
+ /**
36
+ * 运行时不支持装饰器语法,用命令式方式登记 Remote(与 advisor / next-step 同法)。
37
+ * @param {any} Proto
38
+ * @param {string} method
39
+ * @returns {void}
40
+ */
41
+ function declareRemote(Proto, method) {
42
+ /** @type {Function[]} */
43
+ const initializers = [];
44
+ Remote(method)(void 0, {
45
+ name: method,
46
+ static: false,
47
+ private: false,
48
+ addInitializer(/** @type {Function} */ initializer) {
49
+ initializers.push(initializer);
50
+ },
51
+ });
52
+ if (initializers.length !== 1) {
53
+ throw new Error(`projects: cannot declare Remote method ${method}`);
54
+ }
55
+ initializers[0].call(Object.create(Proto.prototype));
56
+ }
57
+
58
+ /**
59
+ * 跑一次 git。
60
+ * 为什么不用 ctx.subprocess:那是个策略 seam(SubprocessSpawnSpec 要 argv/stdio/graceMs,
61
+ * 返回的是带采集上限的句柄),而这里只需要一次短命令的 stdout/exit code。
62
+ * 插件本身就跑在宿主 Node 进程里,node:child_process 总是可用;git 的失败一律由调用方降级。
63
+ * @param {string[]} args
64
+ * @param {string} cwd
65
+ * @returns {Promise<{ code: number, stdout: string, stderr: string }>}
66
+ */
67
+ async function runGit(args, cwd) {
68
+ return runCommand("git", args, { cwd });
69
+ }
70
+
71
+ /**
72
+ * 跑一次 gh。argv 里不含 "gh" 本身(由这里补)。
73
+ * @param {string[]} args
74
+ * @returns {Promise<{ code: number, stdout: string, stderr: string }>}
75
+ */
76
+ async function runGh(args) {
77
+ return runCommand("gh", args);
78
+ }
79
+
80
+ /**
81
+ * 取一条消息里的纯文本(用于唤醒信封的 report)。
82
+ * @param {any} message
83
+ * @returns {string}
84
+ */
85
+ function extractText(message) {
86
+ const content = Array.isArray(message?.content) ? message.content : [];
87
+ const parts = [];
88
+ for (const block of content) {
89
+ if (block && block.type === "text" && typeof block.text === "string") parts.push(block.text);
90
+ }
91
+ return parts.join("\n").trim();
92
+ }
93
+
94
+ /**
95
+ * 递归统计目录体积(只用于影响面展示,不追求精确到字节)。
96
+ * @param {string} dir
97
+ * @returns {number}
98
+ */
99
+ function dirSize(dir) {
100
+ let total = 0;
101
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
102
+ const path = `${dir}/${entry.name}`;
103
+ try {
104
+ if (entry.isDirectory()) total += dirSize(path);
105
+ else if (entry.isFile()) total += statSync(path).size;
106
+ } catch {
107
+ /* 读不到就跳过,不因为统计失败阻断删除 */
108
+ }
109
+ }
110
+ return total;
111
+ }
112
+
113
+ /**
114
+ * 数据根必须可注入:优先配置项,其次进程环境给的 DSH_HOME。
115
+ * @param {Record<string, unknown>|undefined} config
116
+ * @returns {string}
117
+ */
118
+ export function resolveDataRoot(config) {
119
+ const configured = config?.dataRoot;
120
+ if (typeof configured === "string" && configured.trim() !== "") return configured;
121
+ const home = process.env.DSH_HOME;
122
+ if (typeof home === "string" && home !== "") return `${home}/projects`;
123
+ throw new Error("projects: no data root; set config.dataRoot or export DSH_HOME");
124
+ }
125
+
126
+ export class ProjectsService extends TypertRemoteService {
127
+ /**
128
+ * @param {any} ctx
129
+ * @param {Record<string, unknown>} [config]
130
+ */
131
+ constructor(ctx, config) {
132
+ super(ctx, "projects");
133
+ this.logger = ctx?.logger ?? console;
134
+ /** @type {ProjectStore|undefined} */
135
+ this.store = undefined;
136
+ /** @type {string} */
137
+ this.dataRoot = "";
138
+ /** @type {Map<string, () => void>} */
139
+ this.attached = new Map();
140
+ /** 每个线程会话的状态视图(从持久事件归约,重启后可由 replay 重建)。 @type {Map<string, any>} */
141
+ this.views = new Map();
142
+ /** 上下文渲染诊断计数(describe() 暴露,便于真机排查)。 @type {any} */
143
+ this.renderStats = {};
144
+ /**
145
+ * 信封防重:同一个 wakeId 只注入一次。
146
+ * lastWakeTurn 水位只能挡住"已经写回状态"的重复,挡不住两个并发的 turn/end
147
+ * 在写回之前同时通过检查——这个 guard 是同步的,用来闭掉那个竞态。
148
+ * @type {{ shouldInject: (wakeId: string) => boolean, reset: () => void, size: () => number }}
149
+ */
150
+ this.wakeGuard = createInjectionGuard();
151
+ /** 协调器会话的 agent(用于后续工具约束/提示)。 @type {Map<string, any>} */
152
+ this.coordinatorAgents = new Map();
153
+ /** 协调器工具注册的清理函数。 @type {Map<string, (() => void)[]>} */
154
+ this.coordinatorToolDisposers = new Map();
155
+ /** 每个线程会话最近一条 assistant 文本(唤醒信封要带它,M0 实测不带模型读不到结果)。 @type {Map<string, string>} */
156
+ this.lastMessages = new Map();
157
+ /** @type {any} */
158
+ this.agents = undefined;
159
+ /** @type {any} */
160
+ this.sessionController = undefined;
161
+
162
+ // Cordis 里未 inject 的服务属性访问会抛错(0.2.2-rc.3 实测),必须显式 inject。
163
+ // inject 回调是异步的:外部可能在本服务刚构造、回调还没跑时就调 createThread。
164
+ // 用一个就绪 Promise 兜住这个时序(配上超时,避免依赖缺失时永久挂起)。
165
+ /** @type {() => void} */
166
+ let markReady = () => {};
167
+ this.servicesReady = new Promise((resolve) => {
168
+ markReady = () => resolve(undefined);
169
+ });
170
+ ctx.inject?.(["agents", "sessionController"], (/** @type {any} */ scope) => {
171
+ this.agents = scope.agents;
172
+ this.sessionController = scope.sessionController;
173
+ markReady();
174
+ // 冷会话唤醒:应用关着时线程跑完,协调器从没收到信封;启动后补一次(延迟到视图有数据时)
175
+ setTimeout(() => {
176
+ void this.reconcileWakes().catch((/** @type {any} */ error) => {
177
+ this.logger?.warn?.(
178
+ `[projects] cold-session wake skipped: ${String(error?.message ?? error).slice(0, 160)}`,
179
+ );
180
+ });
181
+ }, 5000);
182
+ });
183
+
184
+ // 项目上下文:**全局注册一个按会话求值的条目**。
185
+ // 依据 docs/runtime §11.18/§11.19:per-agent 注册在 agent/created 时无效;
186
+ // 这里的 text 是函数,宿主 refreshContext 会用 resolveContext 按当前 agent/session 求值。
187
+ /** @type {any} */
188
+ this.workspaceRegistry = undefined;
189
+ ctx.inject?.(["workspaceRegistry"], (/** @type {any} */ scope) => {
190
+ this.workspaceRegistry = scope.workspaceRegistry;
191
+ });
192
+
193
+ ctx.inject?.(["systemPrompt"], (/** @type {any} */ scope) => {
194
+ try {
195
+ this.disposeProjectContext = registerProjectContext({
196
+ getStore: () => this.store,
197
+ getDataRoot: () => this.dataRoot,
198
+ register: (definition) => scope.systemPrompt.context(definition),
199
+ onRender: (/** @type {string} */ sessionId, /** @type {string} */ kind) => {
200
+ if (!this.renderStats) this.renderStats = {};
201
+ const stats = this.renderStats;
202
+ stats[kind] = (stats[kind] ?? 0) + 1;
203
+ stats.lastSession = String(sessionId).slice(0, 18);
204
+ if (kind === "coordinator") stats.lastCoordinator = String(sessionId).slice(0, 18);
205
+ },
206
+ renderPersona: (project) =>
207
+ buildPersona({
208
+ projectName: project?.name ?? "",
209
+ persona: project?.policy?.persona ?? "",
210
+ }),
211
+ });
212
+ this.logger?.info?.("[projects] project context registered (global, per-session render)");
213
+ } catch (error) {
214
+ this.logger?.warn?.(
215
+ `[projects] context registration failed: ${String(/** @type {any} */ (error)?.message ?? error)}`,
216
+ );
217
+ }
218
+ });
219
+ ctx.inject?.(["sessionController"], (/** @type {any} */ scope) => {
220
+ this.sessionController = scope.sessionController;
221
+ });
222
+
223
+ try {
224
+ this.dataRoot = resolveDataRoot(config);
225
+ this.store = new ProjectStore({ root: this.dataRoot }).load();
226
+ this.logger.info?.(
227
+ `[projects] loaded ${this.store.listProjects().length} project(s) from ${this.store.file}`,
228
+ );
229
+ } catch (error) {
230
+ const message = error instanceof Error ? error.message : String(error);
231
+ this.logger.warn?.(`[projects] store unavailable: ${message}`);
232
+ }
233
+
234
+ ctx.on?.("agent/created", (/** @type {any} */ payload) => this.onAgentCreated(payload?.agent));
235
+ ctx.on?.("agent/disposed", (/** @type {any} */ payload) =>
236
+ this.onAgentDisposed(payload?.agent?.id),
237
+ );
238
+ // 启动对账:记录有、磁盘没的 worktree 直接清掉记录(反向不删,只报告)
239
+ try {
240
+ if (this.store) {
241
+ const changes = reconcileWorktrees(this.store, { exists: (path) => existsSync(path) });
242
+ if (changes.length > 0) {
243
+ for (const change of changes) {
244
+ this.store.appendAudit({
245
+ action: "worktree/missing",
246
+ projectId: null,
247
+ sessionId: change.sessionId,
248
+ });
249
+ }
250
+ this.store.save();
251
+ this.logger.info?.(`[projects] reconciled ${changes.length} missing worktree(s)`);
252
+ }
253
+ }
254
+ } catch (error) {
255
+ this.logger.warn?.(
256
+ `[projects] reconcile failed: ${String(/** @type {any} */ (error)?.message ?? error)}`,
257
+ );
258
+ }
259
+
260
+ // 归档一个会话 → 尽力回收它的 worktree(脏/未推送/当前会话会被拒绝)
261
+ ctx.on?.("workspace/session-archived", (/** @type {any} */ request) => {
262
+ const sessionId = String(request?.sessionId ?? "");
263
+ if (sessionId === "") return undefined;
264
+ void this.onSessionArchived(sessionId);
265
+ return undefined;
266
+ });
267
+
268
+ ctx.on?.("session/event", (/** @type {any} */ session, /** @type {any} */ event) => {
269
+ const sessionId = String(session?.id ?? "");
270
+ if (sessionId === "" || !this.store) return;
271
+ // 只跟项目线程,其它会话零开销
272
+ if (!this.store.projectOfSession(sessionId)) return;
273
+ const previous = this.views.get(sessionId) ?? initialView();
274
+ const next = reduce(previous, event);
275
+ this.views.set(sessionId, next);
276
+ if (String(event?.type) === "assistant/message") {
277
+ const text = extractText(event?.data?.message);
278
+ if (text !== "") this.lastMessages.set(sessionId, text);
279
+ // token 用量挂在同一条事件上(宿主无独立 usage 记录);累计到项目当天分桶
280
+ const threadProject = this.store?.projectOfSession?.(sessionId);
281
+ const usage = event?.data?.message?.usage ?? event?.data?.usage;
282
+ if (threadProject && usage) {
283
+ const nowMs = Date.now();
284
+ const tokens = tokensOf({ at: new Date(nowMs).toISOString(), usage }, nowMs);
285
+ if (tokens > 0) {
286
+ this.store.addTokenUsage(threadProject.id, tokens, nowMs);
287
+ // 必须落盘:token 分桶的设计要求「跨重启保留」(store 单测覆盖了 save 路径,
288
+ // 但这里曾经只改内存不保存 —— 重启就丢,等于预算闸永远从 0 开始)。
289
+ this.store.save();
290
+ void this.enforceTokenBudget(threadProject.id, nowMs);
291
+ }
292
+ }
293
+ }
294
+ if (String(event?.type) === "turn/end") {
295
+ void this.maybeWakeCoordinator(sessionId, next);
296
+ }
297
+ });
298
+ ctx.effect?.(() => () => {
299
+ for (const dispose of this.attached.values()) {
300
+ try {
301
+ dispose();
302
+ } catch {
303
+ /* ignore */
304
+ }
305
+ }
306
+ this.attached.clear();
307
+ });
308
+ }
309
+
310
+ /**
311
+ * 不能用 `#` 私有方法:Cordis 把 service 实例包成 Proxy,私有方法经代理调用会抛
312
+ * `Receiver must be an instance of class ProjectsService`(0.2.2-rc.3 实测)。
313
+ * @param {any} agent
314
+ */
315
+ /**
316
+ * token 到线就暂停项目(只暂停一次,避免每轮重复写审计)。
317
+ * 「暂停」是保守且可逆的处置:不删数据、不打断正在跑的线程。
318
+ * @param {string} projectId
319
+ * @param {number} now
320
+ */
321
+ async enforceTokenBudget(projectId, now) {
322
+ try {
323
+ const store = this.requireStore();
324
+ const project = store.getProject(projectId);
325
+ if (!project) return;
326
+ const verdict = checkTokenBudget({
327
+ dailyTokens: project.budget?.dailyTokens,
328
+ usedTokens: store.tokenUsageToday(projectId, now),
329
+ });
330
+ if (verdict.ok || project.state === "paused") return;
331
+ store.updateProject(projectId, { state: "paused" });
332
+ store.appendAudit({
333
+ action: "budget/paused",
334
+ projectId,
335
+ reason: verdict.reason,
336
+ used: verdict.used,
337
+ limit: verdict.limit,
338
+ });
339
+ store.save();
340
+ } catch (error) {
341
+ this.logger?.warn?.(
342
+ `[projects] token budget enforce failed: ${String(/** @type {any} */ (error)?.message ?? error)}`,
343
+ );
344
+ }
345
+ }
346
+
347
+ /**
348
+ * 给协调器 agent 注册 project_* 工具(**agent 作用域**,不影响其它会话)。
349
+ * 篮子只有 4 个工具:没有 bash / 写文件 / 删除 / 推送 / 合并。
350
+ * @param {any} agent
351
+ * @param {any} project
352
+ */
353
+ attachCoordinatorTools(agent, project) {
354
+ try {
355
+ const tools = agent?.ctx?.tools;
356
+ if (!tools || typeof tools.register !== "function") {
357
+ this.auditSkip(project?.id, "tools-skip", "no-tools-service");
358
+ return;
359
+ }
360
+ const definitions = buildCoordinatorTools({
361
+ startThread: (/** @type {string} */ task) => this.createThread(project.id, task),
362
+ listThreads: async () => this.progress(project.id),
363
+ messageThread: (/** @type {string} */ sessionId, /** @type {string} */ text) =>
364
+ this.promptThread(sessionId, text),
365
+ writeMemory: async (/** @type {string} */ text) => this.appendMemory(project.id, text),
366
+ readMemory: async () => this.getProjectContent(project.id),
367
+ requestAction: async (/** @type {any} */ request) => {
368
+ const created = this.requireStore().appendApproval({ projectId: project.id, ...request });
369
+ this.requireStore().appendAudit({
370
+ action: "approval/requested",
371
+ projectId: project.id,
372
+ requestId: created.requestId,
373
+ dangerAction: request.action,
374
+ });
375
+ this.requireStore().save();
376
+ return created;
377
+ },
378
+ });
379
+ /** @type {(() => void)[]} */
380
+ const disposers = [];
381
+ for (const definition of definitions) {
382
+ const dispose = tools.register(definition);
383
+ if (typeof dispose === "function") disposers.push(dispose);
384
+ }
385
+ this.coordinatorToolDisposers?.set?.(String(agent?.id ?? ""), disposers);
386
+ const store = this.requireStore();
387
+ store.appendAudit({
388
+ action: "coordinator/tools",
389
+ projectId: project.id,
390
+ count: definitions.length,
391
+ });
392
+ store.save();
393
+ } catch (error) {
394
+ this.auditSkip(
395
+ project?.id,
396
+ "tools-skip",
397
+ String(/** @type {any} */ (error)?.message ?? error).slice(0, 200),
398
+ );
399
+ }
400
+ }
401
+
402
+ /**
403
+ * 把「装不上」记成可观测的审计,而不是只写日志(宿主默认看不到插件日志)。
404
+ * @param {string|undefined} projectId
405
+ * @param {string} action
406
+ * @param {string} reason
407
+ */
408
+ auditSkip(projectId, action, reason) {
409
+ try {
410
+ const store = this.requireStore();
411
+ store.appendAudit({ action: `coordinator/${action}`, projectId: projectId ?? null, reason });
412
+ store.save();
413
+ } catch {
414
+ /* 审计都写不了就只能放弃 */
415
+ }
416
+ }
417
+
418
+ /**
419
+ * 往项目记忆里追加一条(幂等、有上限;写盘后写审计)。
420
+ * @param {string} projectId
421
+ * @param {string} text
422
+ */
423
+ appendMemory(projectId, text) {
424
+ const store = this.requireStore();
425
+ if (!store.getProject(projectId)) throw new Error(`projects: unknown project ${projectId}`);
426
+ const file = join(this.dataRoot, projectId, "memory", "MEMORY.md");
427
+ const existing = existsSync(file) ? readFileSync(file, "utf8") : "";
428
+ const result = appendEntry(existing, text, { at: new Date().toISOString() });
429
+ if (!result.ok) {
430
+ store.appendAudit({ action: "memory/rejected", projectId, reason: result.reason });
431
+ store.save();
432
+ return { ok: false, reason: result.reason, added: false };
433
+ }
434
+ if (result.added) {
435
+ mkdirSync(dirname(file), { recursive: true });
436
+ writeFileSync(file, result.text, { mode: 0o600 });
437
+ store.appendAudit({ action: "memory/appended", projectId, chars: result.text.length });
438
+ store.save();
439
+ // 无需刷新挂载:上下文条目是函数,宿主每次请求都会重新渲染(见 attach.js)
440
+ }
441
+ return {
442
+ ok: true,
443
+ added: result.added,
444
+ ...(result.reason ? { reason: result.reason } : {}),
445
+ };
446
+ }
447
+
448
+ /**
449
+ * 给一个线程会话投递一条消息。
450
+ * @param {string} sessionId
451
+ * @param {string} text
452
+ */
453
+ async promptThread(sessionId, text) {
454
+ const sc = this.sessionController;
455
+ if (!sc) throw new Error("projects: session controller unavailable");
456
+ await sc.prompt(
457
+ {
458
+ requestId: `projects-thread-msg-${Date.now()}`,
459
+ sessionId,
460
+ mode: "queue",
461
+ content: [{ type: "text", text }],
462
+ },
463
+ new AbortController().signal,
464
+ );
465
+ return { ok: true };
466
+ }
467
+
468
+ /**
469
+ * 预热协调器会话并挂载人格。
470
+ * @param {string} projectId
471
+ * @param {string} sessionId
472
+ * @returns {Promise<boolean>}
473
+ */
474
+ async warmUpCoordinator(projectId, sessionId) {
475
+ const sc = this.sessionController;
476
+ if (!sc) return false;
477
+ try {
478
+ await sc.prompt(
479
+ {
480
+ requestId: `projects-coordinator-warmup-${Date.now()}`,
481
+ sessionId,
482
+ mode: "queue",
483
+ content: [{ type: "text", text: "(系统)协调器已就绪,等待项目事件。" }],
484
+ },
485
+ new AbortController().signal,
486
+ );
487
+ } catch {
488
+ /* 预热失败不影响创建;下面还会重试挂载 */
489
+ }
490
+ const deadline = Date.now() + 4000;
491
+ while (Date.now() < deadline) {
492
+ const agent = this.agents?.get?.(sessionId);
493
+ if (agent) return true;
494
+ await new Promise((resolve) => setTimeout(resolve, 200));
495
+ }
496
+ const store = this.requireStore();
497
+ store.appendAudit({
498
+ action: "coordinator/persona-skip",
499
+ projectId,
500
+ sessionId,
501
+ reason: "agent-not-ready",
502
+ });
503
+ store.save();
504
+ return false;
505
+ }
506
+
507
+ /**
508
+ * agent 起来时的钩子。这里**不做任何 per-agent systemPrompt 注册**:
509
+ * 实测在 agent/created 里注册进不了提示词(runtime §11.18)。
510
+ * 项目上下文与协调器人格由构造函数里 registerProjectContext 全局注册、按会话求值(§11.20)。
511
+ * @param {any} agent
512
+ */
513
+ onAgentCreated(agent) {
514
+ const sessionId = String(agent?.id ?? "");
515
+ if (sessionId === "") return;
516
+ // 记下在线 agent,供工具注册/诊断使用
517
+ this.coordinatorAgents?.set?.(sessionId, agent);
518
+ }
519
+
520
+ /** @param {string|undefined} sessionId */
521
+ onAgentDisposed(sessionId) {
522
+ if (typeof sessionId !== "string") return;
523
+ const dispose = this.attached.get(sessionId);
524
+ this.attached.delete(sessionId);
525
+ try {
526
+ dispose?.();
527
+ } catch {
528
+ /* ignore */
529
+ }
530
+ }
531
+
532
+ /**
533
+ * 会话归档后的回收钩子:不抛错(归档已经成功,回收失败只记录)。
534
+ * @param {string} sessionId
535
+ */
536
+ async onSessionArchived(sessionId) {
537
+ try {
538
+ const store = this.requireStore();
539
+ if (!store.projectOfSession(sessionId)) return;
540
+ const result = await reclaimThreadWorktree({
541
+ store,
542
+ sessionId,
543
+ deps: { runGit },
544
+ });
545
+ store.appendAudit({
546
+ action: "worktree/reclaim",
547
+ projectId: null,
548
+ sessionId,
549
+ result: result.reason || "ok",
550
+ });
551
+ store.save();
552
+ if (!result.reclaimed) {
553
+ this.logger.info?.(`[projects] kept worktree for ${sessionId}: ${result.reason}`);
554
+ }
555
+ } catch (error) {
556
+ this.logger.warn?.(
557
+ `[projects] archive reclaim failed for ${sessionId}: ${String(/** @type {any} */ (error)?.message ?? error)}`,
558
+ );
559
+ }
560
+ }
561
+
562
+ /** 等注入就绪(最多 5s);超时视为依赖缺失,由调用方报错。 */
563
+ async waitServices() {
564
+ await Promise.race([this.servicesReady, new Promise((resolve) => setTimeout(resolve, 5000))]);
565
+ }
566
+
567
+ /** @returns {any} */
568
+ requireStore() {
569
+ if (!this.store) throw new Error("projects: store is unavailable");
570
+ return this.store;
571
+ }
572
+
573
+ // ---- Remote:只读 ----
574
+
575
+ listProjects() {
576
+ const store = this.requireStore();
577
+ // 顺带给出线程数:面板要用它显示「N 个线程」,避免每个项目再发一次 RPC。
578
+ return store.listProjects().map((/** @type {any} */ project) => ({
579
+ ...project,
580
+ threadCount: store.listThreads(project.id).length,
581
+ }));
582
+ }
583
+
584
+ /** @param {string} id */
585
+ getProject(id) {
586
+ return this.requireStore().getProject(id) ?? null;
587
+ }
588
+
589
+ /** @param {string} projectId */
590
+ listThreads(projectId) {
591
+ return this.requireStore().listThreads(projectId);
592
+ }
593
+
594
+ /** @param {string} sessionId */
595
+ projectOfSession(sessionId) {
596
+ return this.requireStore().projectOfSession(sessionId) ?? null;
597
+ }
598
+
599
+ /**
600
+ * 项目内容文件(只读):常设规则与记忆索引。
601
+ * @param {string} projectId
602
+ */
603
+ getProjectContent(projectId) {
604
+ const store = this.requireStore();
605
+ if (!store.getProject(projectId)) throw new Error(`projects: unknown project ${projectId}`);
606
+ const files = readProjectFiles(this.dataRoot, projectId);
607
+ return { instructions: files.instructions, memoryIndex: files.memoryIndex };
608
+ }
609
+
610
+ /**
611
+ * 审计尾巴(只读):默认返回全局最近 100 条,给了 projectId 就只返回该项目的。
612
+ * @param {string|undefined} projectId
613
+ */
614
+ listAudit(projectId) {
615
+ const store = this.requireStore();
616
+ const entries = Array.isArray(store.state?.audit) ? store.state.audit : [];
617
+ const filtered = projectId
618
+ ? entries.filter((/** @type {any} */ entry) => entry.projectId === projectId)
619
+ : entries;
620
+ return filtered.slice(-100);
621
+ }
622
+
623
+ // ---- Remote:写 ----
624
+
625
+ /**
626
+ * @param {string} name
627
+ * @param {{goal?: string, dirs?: string[]}} [input]
628
+ */
629
+ createProject(name, input) {
630
+ // SRC 模式(无生成描述符)要求 Remote 方法不带默认参数/解构/rest,否则网关直接拒绝。
631
+ const store = this.requireStore();
632
+ const project = store.createProject(name, input ?? {});
633
+ store.save();
634
+ return project;
635
+ }
636
+
637
+ /**
638
+ * @param {string} id
639
+ * @param {any} patch
640
+ */
641
+ updateProject(id, patch) {
642
+ const store = this.requireStore();
643
+ const project = store.updateProject(id, patch);
644
+ store.save();
645
+ return project;
646
+ }
647
+
648
+ /**
649
+ * 暂停项目:不再能建新线程,已有线程不受影响(可逆)。
650
+ * @param {string} id
651
+ */
652
+ pauseProject(id) {
653
+ const store = this.requireStore();
654
+ const project = store.updateProject(id, { state: "paused" });
655
+ store.save();
656
+ return project;
657
+ }
658
+
659
+ /**
660
+ * 恢复项目。
661
+ * @param {string} id
662
+ */
663
+ resumeProject(id) {
664
+ const store = this.requireStore();
665
+ const project = store.updateProject(id, { state: "active" });
666
+ store.save();
667
+ return project;
668
+ }
669
+
670
+ /** @param {string} id */
671
+ /**
672
+ * 取消归档:回到 active,线程归属与内容文件都还在(归档从不删数据)。
673
+ * @param {string} id
674
+ */
675
+ unarchiveProject(id) {
676
+ const store = this.requireStore();
677
+ const project = store.updateProject(id, { state: "active" });
678
+ store.appendAudit({ action: "project/unarchived", projectId: id });
679
+ store.save();
680
+ return project;
681
+ }
682
+
683
+ /**
684
+ * @param {string} id
685
+ */
686
+ archiveProject(id) {
687
+ const store = this.requireStore();
688
+ const project = store.archiveProject(id);
689
+ store.save();
690
+ // 归档后立刻摘掉在线会话的项目上下文:否则已挂上的 agent 会带着归档项目的规则继续跑。
691
+ for (const thread of store.listThreads(id)) {
692
+ this.detachSession(thread.sessionId);
693
+ }
694
+ return project;
695
+ }
696
+
697
+ /**
698
+ * dry-run:删除这个项目会影响什么(数量/体积/是否在跑/能否恢复)。
699
+ * @param {string} id
700
+ */
701
+ previewDeleteProject(id) {
702
+ const store = this.requireStore();
703
+ const project = store.getProject(id);
704
+ if (!project) throw new Error(`projects: unknown project ${id}`);
705
+ const threads = store.listThreads(id);
706
+ const contentDir = `${this.dataRoot}/${id}`;
707
+ let contentBytes = 0;
708
+ let hasContentDir = false;
709
+ try {
710
+ if (existsSync(contentDir)) {
711
+ hasContentDir = true;
712
+ contentBytes = dirSize(contentDir);
713
+ }
714
+ } catch {
715
+ hasContentDir = false;
716
+ }
717
+ return {
718
+ projectId: id,
719
+ name: project.name,
720
+ impact: impactOf({ threads, contentBytes, hasContentDir, name: project.name }),
721
+ threads: threads.map((/** @type {any} */ thread) => ({
722
+ sessionId: thread.sessionId,
723
+ state: thread.state,
724
+ })),
725
+ contentDir,
726
+ };
727
+ }
728
+
729
+ /**
730
+ * 删除项目:记录与内容文件移入回收站(会话日志不动),写审计。
731
+ * 调用方应先跑 previewDeleteProject 把影响面展示给用户。
732
+ * @param {string} id
733
+ */
734
+ deleteProject(id) {
735
+ const store = this.requireStore();
736
+ const preview = this.previewDeleteProject(id);
737
+ const trashDir = trashDirFor({ dataRoot: this.dataRoot, projectId: id });
738
+ mkdirSync(trashDir, { recursive: true, mode: 0o700 });
739
+ const removed = store.removeProject(id);
740
+ // 内容文件(如果有)整体搬进回收站;搬不动就把元数据留在回收站里并报错
741
+ if (preview.impact.hasContentDir && existsSync(preview.contentDir)) {
742
+ try {
743
+ renameSync(preview.contentDir, `${trashDir}/content`);
744
+ } catch (error) {
745
+ writeFileSync(
746
+ `${trashDir}/manifest.json`,
747
+ `${JSON.stringify({ project: removed.project, threads: removed.threads, contentDir: preview.contentDir, moved: false }, null, 2)}\n`,
748
+ { mode: 0o600 },
749
+ );
750
+ store.save();
751
+ throw new Error(
752
+ `projects: content move failed (${String(/** @type {any} */ (error)?.message ?? error)})`,
753
+ );
754
+ }
755
+ }
756
+ writeFileSync(
757
+ `${trashDir}/manifest.json`,
758
+ `${JSON.stringify(
759
+ {
760
+ format: 1,
761
+ deletedAt: new Date().toISOString(),
762
+ project: removed.project,
763
+ threads: removed.threads,
764
+ contentDir: preview.contentDir,
765
+ moved: preview.impact.hasContentDir,
766
+ summary: preview.impact.summary,
767
+ },
768
+ null,
769
+ 2,
770
+ )}\n`,
771
+ { mode: 0o600 },
772
+ );
773
+ for (const thread of removed.threads) this.detachSession(thread.sessionId);
774
+ store.appendAudit({ action: "project/deleted", projectId: id, reason: "trash", trashDir });
775
+ store.save();
776
+ return { deleted: true, trashDir, summary: preview.impact.summary };
777
+ }
778
+
779
+ /**
780
+ * 摘掉一个会话已挂的项目上下文(不动归属记录)。
781
+ * @param {string} sessionId
782
+ */
783
+ detachSession(sessionId) {
784
+ const dispose = this.attached.get(sessionId);
785
+ if (!dispose) return false;
786
+ this.attached.delete(sessionId);
787
+ try {
788
+ dispose();
789
+ } catch {
790
+ /* ignore */
791
+ }
792
+ return true;
793
+ }
794
+
795
+ /**
796
+ * @param {string} sessionId
797
+ * @param {string} projectId
798
+ */
799
+ attachThread(sessionId, projectId) {
800
+ const store = this.requireStore();
801
+ const thread = store.attachThread(sessionId, projectId);
802
+ store.save();
803
+ // 不需要在这里补挂上下文:项目上下文是**全局注册 + 按会话求值**的
804
+ // (见构造函数的 registerProjectContext),归属一落盘,下一次请求就会渲染出来。
805
+ return thread;
806
+ }
807
+
808
+ /**
809
+ * 冷会话唤醒:启动后补发「应用关着时欠下的」协调器信封。
810
+ * 为什么需要:wake 原本只在 turn/end 触发;应用关着时线程跑完,协调器永远不知道。
811
+ * 只处理需要人看的终态(done/failed/waiting-user),且由 decideWake 统一去重。
812
+ * @returns {Promise<{ scanned: number, woken: number }>}
813
+ */
814
+ async reconcileWakes() {
815
+ const store = this.requireStore();
816
+ let scanned = 0;
817
+ let woken = 0;
818
+ for (const project of store.listProjects()) {
819
+ if (project?.state !== "active") continue;
820
+ if (typeof project.coordinatorSessionId !== "string" || project.coordinatorSessionId === "")
821
+ continue;
822
+ const threads = store.listThreads(project.id);
823
+ scanned += threads.length;
824
+ /** @type {Map<string, any>} */
825
+ const views = new Map();
826
+ for (const thread of threads) {
827
+ const view = this.views.get(thread.sessionId);
828
+ if (view) views.set(thread.sessionId, view);
829
+ }
830
+ for (const pending of pendingWakes(threads, views)) {
831
+ await this.maybeWakeCoordinator(pending.sessionId, {
832
+ turn: pending.turn,
833
+ state: pending.state,
834
+ });
835
+ woken += 1;
836
+ }
837
+ }
838
+ if (woken > 0) this.logger?.info?.(`[projects] cold-session wake: ${woken}/${scanned}`);
839
+ return { scanned, woken };
840
+ }
841
+
842
+ /**
843
+ * 给信封用的项目上下文摘要:常设规则 + 记忆索引,拼成一段文本。
844
+ * 为什么放进信封:协调器会话拿不到宿主的 runtime context(runtime §11.24),
845
+ * 而信封这条路已被实测证明能到达协调器(§11.8)。
846
+ * @param {any} project
847
+ * @returns {string}
848
+ */
849
+ renderProjectContextFor(project) {
850
+ try {
851
+ const files = readProjectFiles(this.dataRoot, project.id);
852
+ const blocks = [];
853
+ if (files.instructions !== "") blocks.push(`# 项目规则\n${files.instructions}`);
854
+ if (files.memoryIndex !== "") blocks.push(`# 项目记忆索引\n${files.memoryIndex}`);
855
+ return blocks.join("\n\n");
856
+ } catch {
857
+ return "";
858
+ }
859
+ }
860
+
861
+ /**
862
+ * 确保项目有一个协调器会话(没有就建一个),返回会话 id。
863
+ * @param {string} projectId
864
+ */
865
+ async ensureCoordinator(projectId) {
866
+ await this.waitServices();
867
+ // 单飞:并发调用(面板 + 探针 + 唤醒路径)不能各建一个协调器会话。
868
+ // 用 per-project Promise 复用同一个在途创建;完成后清掉,失败也不留脏。
869
+ this.coordinatorInFlight = this.coordinatorInFlight ?? new Map();
870
+ const inFlight = this.coordinatorInFlight.get(projectId);
871
+ if (inFlight) return inFlight;
872
+ const task = this.createCoordinator(projectId).finally(() => {
873
+ this.coordinatorInFlight.delete(projectId);
874
+ });
875
+ this.coordinatorInFlight.set(projectId, task);
876
+ return task;
877
+ }
878
+
879
+ /**
880
+ * 真正的协调器创建逻辑(只由 ensureCoordinator 调用,保证单飞)。
881
+ * @param {string} projectId
882
+ */
883
+ async createCoordinator(projectId) {
884
+ const store = this.requireStore();
885
+ const project = store.getProject(projectId);
886
+ if (!project) throw new Error(`projects: unknown project ${projectId}`);
887
+ if (typeof project.coordinatorSessionId === "string" && project.coordinatorSessionId !== "") {
888
+ return { sessionId: project.coordinatorSessionId, created: false };
889
+ }
890
+ const sc = this.sessionController;
891
+ if (!sc) throw new Error("projects: session controller unavailable");
892
+ const cwd =
893
+ Array.isArray(project.dirs) && project.dirs.length > 0 ? project.dirs[0] : this.dataRoot;
894
+ const created = await sc.create({ cwd });
895
+ const sessionId = String(created.sessionId);
896
+
897
+ // 把协调器会话挂进对应目录的 workspace,让它成为「正常工作区会话」。
898
+ // 依据 runtime §11.21:裸会话拿不到运行时上下文提醒,于是项目上下文/人格都进不去。
899
+ // 失败不阻断(协调器仍可用,只是暂时没有上下文)。
900
+ try {
901
+ const registry = this.workspaceRegistry;
902
+ if (registry && typeof registry.create === "function") {
903
+ const ws = await registry.create(cwd, project.name);
904
+ if (ws && typeof ws.attachSession === "function") {
905
+ await ws.attachSession(sessionId);
906
+ store.appendAudit({
907
+ action: "coordinator/workspace",
908
+ projectId,
909
+ sessionId,
910
+ result: "attached",
911
+ });
912
+ }
913
+ }
914
+ } catch (error) {
915
+ store.appendAudit({
916
+ action: "coordinator/workspace",
917
+ projectId,
918
+ sessionId,
919
+ result: "skipped",
920
+ reason: String(/** @type {any} */ (error)?.message ?? error).slice(0, 160),
921
+ });
922
+ }
923
+
924
+ store.updateProject(projectId, { coordinatorSessionId: sessionId });
925
+ store.appendAudit({ action: "coordinator/created", projectId, sessionId });
926
+ store.save();
927
+ // 显式挂人格:agent 是懒创建的,靠 agent/created 钩子会受时序影响。
928
+ // 这里主动预热一轮(轻量文本)并在几秒内重试挂载;失败只记审计,不阻断。
929
+ const attached = await this.warmUpCoordinator(projectId, sessionId);
930
+ return { sessionId, created: true, personaAttached: attached };
931
+ }
932
+
933
+ /**
934
+ * 线程一轮结束时唤醒协调器(同一轮只唤醒一次)。
935
+ * 失败只记日志,不影响线程本身。
936
+ * @param {string} sessionId
937
+ * @param {any} view
938
+ */
939
+ async maybeWakeCoordinator(sessionId, view) {
940
+ try {
941
+ const store = this.store;
942
+ if (!store) return;
943
+ const project = store.projectOfSession(sessionId);
944
+ if (!project) return;
945
+ const coordinatorSessionId = project.coordinatorSessionId;
946
+ if (typeof coordinatorSessionId !== "string" || coordinatorSessionId === "") {
947
+ store.appendAudit({
948
+ action: "wake/skipped",
949
+ projectId: project.id,
950
+ sessionId,
951
+ reason: "no-coordinator",
952
+ });
953
+ store.save(); // 不落盘的话,重启后「为什么没反应」就查不到了
954
+ return;
955
+ }
956
+ const thread = store
957
+ .listThreads(project.id)
958
+ .find((/** @type {any} */ item) => item.sessionId === sessionId);
959
+ if (!thread) return;
960
+ const turn = Number(view?.turn ?? 0);
961
+
962
+ const envelope = buildEnvelope({
963
+ reason: "thread-activity",
964
+ trust: "principal",
965
+ project: { id: project.id, name: project.name },
966
+ thread: {
967
+ sessionId,
968
+ state: view?.state ?? "done",
969
+ turn,
970
+ branch: thread.branch ?? null,
971
+ },
972
+ context: this.renderProjectContextFor(project),
973
+ // 人格同样走信封:宿主的 runtime-context 投递不到协调器会话(§11.24)
974
+ persona: buildPersona({
975
+ projectName: project.name,
976
+ persona: project.policy?.persona ?? "",
977
+ }),
978
+ report: this.lastMessages.get(sessionId) ?? "",
979
+ next:
980
+ view?.state === "failed"
981
+ ? "tell the user which thread failed and why, in one sentence"
982
+ : "tell the user the thread's result in one short sentence",
983
+ wakeId: `thread-activity:${sessionId}:${turn}`,
984
+ });
985
+
986
+ const decision = decideWake({
987
+ turn,
988
+ lastWakeTurn: Number(thread.lastWakeTurn ?? 0),
989
+ wakeId: envelope.wakeId,
990
+ guard: this.wakeGuard,
991
+ });
992
+ if (decision !== "send") {
993
+ store.appendAudit({
994
+ action: decision === "skip-dedupe" ? "wake/deduped" : "wake/skipped",
995
+ projectId: project.id,
996
+ sessionId,
997
+ turn,
998
+ wakeId: envelope.wakeId,
999
+ reason: decision,
1000
+ });
1001
+ store.save();
1002
+ return;
1003
+ }
1004
+ if (this.wakeGuard.size() > 1000) this.wakeGuard.reset(); // 长跑不无限增长
1005
+
1006
+ const sc = this.sessionController;
1007
+ if (!sc) return;
1008
+ await sc.prompt(
1009
+ {
1010
+ requestId: `projects-wake-${envelope.wakeId}`,
1011
+ sessionId: coordinatorSessionId,
1012
+ mode: "queue",
1013
+ content: [{ type: "text", text: envelope.text }],
1014
+ },
1015
+ new AbortController().signal,
1016
+ );
1017
+ store.setThreadWakeState(sessionId, turn);
1018
+ store.appendAudit({
1019
+ action: "wake/sent",
1020
+ projectId: project.id,
1021
+ sessionId,
1022
+ turn,
1023
+ wakeId: envelope.wakeId,
1024
+ });
1025
+ store.save();
1026
+ } catch (error) {
1027
+ this.logger?.warn?.(
1028
+ `[projects] wake failed: ${String(/** @type {any} */ (error)?.message ?? error)}`,
1029
+ );
1030
+ }
1031
+ }
1032
+
1033
+ /**
1034
+ * 按规则处理一条输入:决策 → 必要时执行 → **一律写审计**。
1035
+ * L0/L1 下「新建线程」会被拦成提议(规格 §7.4:级别只增不减地放宽,默认只提议)。
1036
+ * @param {string} projectId
1037
+ * @param {string} text
1038
+ */
1039
+ async route(projectId, text) {
1040
+ await this.waitServices();
1041
+ const store = this.requireStore();
1042
+ const project = store.getProject(projectId);
1043
+ if (!project) throw new Error(`projects: unknown project ${projectId}`);
1044
+ const input = String(text ?? "").trim();
1045
+ if (input === "") throw new Error("projects: route requires text");
1046
+
1047
+ const decision = this.previewRoute(projectId, input);
1048
+ /** @type {any} */
1049
+ const record = {
1050
+ action: "route",
1051
+ projectId,
1052
+ input: input.slice(0, 120),
1053
+ decision: { by: decision.by, action: decision.action, ruleId: decision.ruleId ?? null },
1054
+ autonomy: decision.autonomy,
1055
+ };
1056
+
1057
+ if (decision.by === "blocked") {
1058
+ store.appendAudit({ ...record, result: "blocked", reason: decision.blockedReason ?? "" });
1059
+ store.save();
1060
+ return { executed: false, decision, reason: decision.blockedReason ?? "" };
1061
+ }
1062
+
1063
+ if (decision.action === "new-thread") {
1064
+ try {
1065
+ const thread = await this.createThread(projectId, input);
1066
+ store.appendAudit({ ...record, result: "thread-created", sessionId: thread.sessionId });
1067
+ store.save();
1068
+ return { executed: true, decision, sessionId: thread.sessionId, isolated: thread.isolated };
1069
+ } catch (error) {
1070
+ store.appendAudit({
1071
+ ...record,
1072
+ result: "failed",
1073
+ reason: String(/** @type {any} */ (error)?.message ?? error),
1074
+ });
1075
+ store.save();
1076
+ return {
1077
+ executed: false,
1078
+ decision,
1079
+ reason: String(/** @type {any} */ (error)?.message ?? error),
1080
+ };
1081
+ }
1082
+ }
1083
+
1084
+ // answer-inline / reuse-thread / propose:执行留给调用方(面板/协调器),这里只给决策
1085
+ store.appendAudit({
1086
+ ...record,
1087
+ result: decision.action === "propose" ? "proposed" : "handled-by-caller",
1088
+ });
1089
+ store.save();
1090
+ return { executed: false, decision, reason: "" };
1091
+ }
1092
+
1093
+ /**
1094
+ * 申请一个危险动作(入审批队列,**不执行**)。
1095
+ * 协调器工具走同一条路径;面板也可以直接调用。
1096
+ * @param {string} projectId
1097
+ * @param {{ action?: string, reason?: string, args?: any }} request
1098
+ */
1099
+ requestAction(projectId, request) {
1100
+ const store = this.requireStore();
1101
+ const project = store.getProject(projectId);
1102
+ if (!project) throw new Error(`projects: unknown project ${projectId}`);
1103
+ const action = String(request?.action ?? "");
1104
+ const reason = String(request?.reason ?? "").trim();
1105
+ if (!REQUESTABLE_ACTIONS.includes(action)) {
1106
+ return { ok: false, error: `action-not-requestable: ${action || "(empty)"}` };
1107
+ }
1108
+ if (reason === "") return { ok: false, error: "reason-required" };
1109
+ const created = store.appendApproval({
1110
+ projectId,
1111
+ action,
1112
+ args: request?.args ?? null,
1113
+ reason,
1114
+ });
1115
+ store.appendAudit({
1116
+ action: "approval/requested",
1117
+ projectId,
1118
+ requestId: created.requestId,
1119
+ dangerAction: action,
1120
+ });
1121
+ store.save();
1122
+ return { ok: true, requestId: created.requestId };
1123
+ }
1124
+
1125
+ /**
1126
+ * 待审批队列(面板用)。
1127
+ * @param {string|undefined} projectId
1128
+ */
1129
+ listApprovals(projectId) {
1130
+ return this.requireStore().listApprovals(projectId);
1131
+ }
1132
+
1133
+ /**
1134
+ * 根据一次 CI 失败决定要不要再修一轮;要修就给该线程投递修复任务。
1135
+ * **不 push、不开 PR**(ADR 0003);碰到测试文件或无进展就停。
1136
+ * @param {string} projectId
1137
+ * @param {{ sessionId: string, log: string, changedFiles?: string[] }} input
1138
+ */
1139
+ async autoFixStep(projectId, input) {
1140
+ await this.waitServices();
1141
+ const store = this.requireStore();
1142
+ const project = store.getProject(projectId);
1143
+ if (!project) throw new Error(`projects: unknown project ${projectId}`);
1144
+ const sessionId = String(input?.sessionId ?? "");
1145
+ const thread = store
1146
+ .listThreads(projectId)
1147
+ .find((/** @type {any} */ item) => item.sessionId === sessionId);
1148
+ if (!thread) throw new Error(`projects: unknown thread ${sessionId}`);
1149
+
1150
+ const signature = errorSignature(String(input?.log ?? ""));
1151
+ const verdict = shouldContinueFix({
1152
+ round: Number(thread.autoFixRound ?? 0),
1153
+ changedFiles: input?.changedFiles ?? thread.autoFixChanged ?? [],
1154
+ previousSignature: String(thread.autoFixSignature ?? ""),
1155
+ currentSignature: signature,
1156
+ });
1157
+
1158
+ if (!verdict.continue) {
1159
+ store.appendAudit({
1160
+ action: "autofix/stopped",
1161
+ projectId,
1162
+ sessionId,
1163
+ reason: verdict.reason,
1164
+ });
1165
+ store.save();
1166
+ return { continued: false, reason: verdict.reason };
1167
+ }
1168
+
1169
+ const task = buildFixTask({
1170
+ round: Number(thread.autoFixRound ?? 0),
1171
+ signature,
1172
+ projectName: project.name,
1173
+ });
1174
+ await this.promptThread(sessionId, task);
1175
+ store.setThreadAutoFix(sessionId, {
1176
+ round: Number(thread.autoFixRound ?? 0) + 1,
1177
+ signature,
1178
+ changedFiles: [],
1179
+ });
1180
+ store.appendAudit({
1181
+ action: "autofix/round",
1182
+ projectId,
1183
+ sessionId,
1184
+ round: Number(thread.autoFixRound ?? 0) + 1,
1185
+ });
1186
+ store.save();
1187
+ return { continued: true, reason: "", round: Number(thread.autoFixRound ?? 0) + 1 };
1188
+ }
1189
+
1190
+ /**
1191
+ * 按档位给一个线程开 PR:推分支 →(需要时)gh pr create → 记录 PR 号与审计。
1192
+ * 档位 off 时什么都不做。gh 缺失/失败只降级并写审计,不重试到天荒地老。
1193
+ * @param {string} projectId
1194
+ * @param {string} sessionId
1195
+ * @param {{ tier?: string, base?: string, repo?: string, ciState?: string }} [options]
1196
+ */
1197
+ async openPr(projectId, sessionId, options) {
1198
+ await this.waitServices();
1199
+ const store = this.requireStore();
1200
+ const project = store.getProject(projectId);
1201
+ if (!project) throw new Error(`projects: unknown project ${projectId}`);
1202
+ const thread = store
1203
+ .listThreads(projectId)
1204
+ .find((/** @type {any} */ item) => item.sessionId === sessionId);
1205
+ if (!thread) throw new Error(`projects: unknown thread ${sessionId}`);
1206
+
1207
+ const tier = String(options?.tier ?? "off");
1208
+
1209
+ // 线程上没有 commits 字段:直接数(base..branch),否则任何线程都会被判成"没有提交"
1210
+ const repoRoot = Array.isArray(project.dirs) && project.dirs.length > 0 ? project.dirs[0] : "";
1211
+ let commits = Number(thread.commits ?? 0);
1212
+ if (repoRoot !== "" && typeof thread.branch === "string" && thread.branch !== "") {
1213
+ const base = String(options?.base ?? "HEAD");
1214
+ const counted = await runGit(["rev-list", "--count", `${base}..${thread.branch}`], repoRoot);
1215
+ if (counted.code === 0) commits = Number(String(counted.stdout).trim() || "0");
1216
+ }
1217
+
1218
+ const decision = nextPrAction({
1219
+ tier,
1220
+ thread: {
1221
+ branch: thread.branch ?? null,
1222
+ prNumber: thread.prNumber ?? null,
1223
+ commits,
1224
+ attempts: Number(thread.prAttempts ?? 0),
1225
+ ciState: options?.ciState ?? undefined,
1226
+ },
1227
+ });
1228
+
1229
+ if (
1230
+ decision.action === "none" ||
1231
+ decision.action === "give-up" ||
1232
+ decision.action === "wait-ci"
1233
+ ) {
1234
+ store.appendAudit({
1235
+ action: "pr/decided",
1236
+ projectId,
1237
+ sessionId,
1238
+ decision: decision.action,
1239
+ reason: decision.reason,
1240
+ });
1241
+ store.save();
1242
+ return { opened: false, decision };
1243
+ }
1244
+ if (decision.action === "update") {
1245
+ store.appendAudit({
1246
+ action: "pr/decided",
1247
+ projectId,
1248
+ sessionId,
1249
+ decision: "update",
1250
+ prNumber: thread.prNumber,
1251
+ });
1252
+ store.save();
1253
+ return { opened: false, decision, prNumber: thread.prNumber ?? null };
1254
+ }
1255
+
1256
+ const draft = decision.action === "open-draft";
1257
+ const text = buildPrText({
1258
+ projectName: project.name,
1259
+ task: this.lastMessages.get(sessionId) ?? project.goal ?? "",
1260
+ sessionId,
1261
+ branch: thread.branch ?? "",
1262
+ });
1263
+ const planned = planPrCreate({
1264
+ title: text.title,
1265
+ body: text.body,
1266
+ branch: String(thread.branch ?? ""),
1267
+ base: options?.base,
1268
+ repo: options?.repo,
1269
+ draft,
1270
+ });
1271
+ if ("error" in planned) {
1272
+ store.appendAudit({ action: "pr/failed", projectId, sessionId, reason: planned.error });
1273
+ store.save();
1274
+ return { opened: false, decision, reason: planned.error };
1275
+ }
1276
+
1277
+ // 先推分支(worktree 内),再开 PR
1278
+ const worktree =
1279
+ typeof thread.worktree === "string" && thread.worktree !== "" ? thread.worktree : "";
1280
+ if (worktree !== "") {
1281
+ const pushed = await runGit(["push", "-u", "origin", String(thread.branch)], worktree);
1282
+ if (pushed.code !== 0) {
1283
+ store.appendAudit({ action: "pr/failed", projectId, sessionId, reason: "push-failed" });
1284
+ store.save();
1285
+ return { opened: false, decision, reason: "push-failed" };
1286
+ }
1287
+ }
1288
+
1289
+ const gh = await runGh(planned.argv);
1290
+ const prNumber = gh.code === 0 ? parsePrNumber(gh.stdout) : null;
1291
+ if (gh.code !== 0 || prNumber === null) {
1292
+ const tryCount = Number(thread.prAttempts ?? 0) + 1;
1293
+ store.setThreadAutoFix(sessionId, {});
1294
+ store.appendAudit({
1295
+ action: "pr/failed",
1296
+ projectId,
1297
+ sessionId,
1298
+ reason: String(gh.stderr).split("\n")[0].slice(0, 160) || "gh-failed",
1299
+ attempts: tryCount,
1300
+ });
1301
+ store.save();
1302
+ return { opened: false, decision, reason: "gh-failed" };
1303
+ }
1304
+
1305
+ store.setThreadWakeState(sessionId, Number(thread.lastWakeTurn ?? 0));
1306
+ store.appendAudit({ action: "pr/opened", projectId, sessionId, prNumber, draft });
1307
+ store.save();
1308
+ return { opened: true, decision, prNumber, draft, argv: planned.argv };
1309
+ }
1310
+
1311
+ /**
1312
+ * 执行一条已批准的申请。**默认什么都不会执行**:危险开关全关。
1313
+ * 顺序固定:已批准 → 动作在白名单 → 开关打开 → 影响面在阈值内 → 执行 → 写恢复证据。
1314
+ * @param {string} requestId
1315
+ */
1316
+ async executeApproval(requestId) {
1317
+ const store = this.requireStore();
1318
+ const approval = store
1319
+ .listApprovals(undefined)
1320
+ .find((/** @type {any} */ item) => item.requestId === requestId);
1321
+ if (!approval) throw new Error(`projects: unknown approval ${requestId}`);
1322
+
1323
+ // 幂等判定必须**最先**:删除类动作执行后项目已不存在,
1324
+ // 若先查项目就会抛 "unknown project",把「重复执行」误报成「项目丢了」。
1325
+ if (typeof approval.executedAt === "string" && approval.executedAt !== "") {
1326
+ store.appendAudit({
1327
+ action: "approval/execution-refused",
1328
+ projectId: approval.projectId,
1329
+ requestId,
1330
+ dangerAction: approval.action,
1331
+ reason: "already-executed",
1332
+ });
1333
+ store.save();
1334
+ return { executed: false, reason: "already-executed" };
1335
+ }
1336
+
1337
+ const project = store.getProject(approval.projectId);
1338
+ if (!project) {
1339
+ store.appendAudit({
1340
+ action: "approval/execution-refused",
1341
+ projectId: approval.projectId,
1342
+ requestId,
1343
+ dangerAction: approval.action,
1344
+ reason: "project-missing",
1345
+ });
1346
+ store.save();
1347
+ return { executed: false, reason: "project-missing" };
1348
+ }
1349
+
1350
+ const verdict = checkExecutable({
1351
+ approval,
1352
+ danger: project.policy?.danger ?? {},
1353
+ limits: project.policy?.danger?.merge
1354
+ ? {
1355
+ maxDiffFiles: Number(project.policy.danger.merge?.maxDiffFiles ?? 20),
1356
+ maxDiffLines: Number(project.policy.danger.merge?.maxDiffLines ?? 600),
1357
+ }
1358
+ : undefined,
1359
+ impact: approval.args?.impact ?? {},
1360
+ });
1361
+ if (!verdict.ok) {
1362
+ store.appendAudit({
1363
+ action: "approval/execution-refused",
1364
+ projectId: approval.projectId,
1365
+ requestId,
1366
+ dangerAction: approval.action,
1367
+ reason: verdict.reason,
1368
+ });
1369
+ store.save();
1370
+ return { executed: false, reason: verdict.reason };
1371
+ }
1372
+
1373
+ // 幂等:先占位(占用失败说明已经执行过),再真正执行。
1374
+ // 否则并发两次 executeApproval 会重复推送/重复删除。
1375
+ try {
1376
+ store.markApprovalExecuted(requestId, null);
1377
+ } catch {
1378
+ store.appendAudit({
1379
+ action: "approval/execution-refused",
1380
+ projectId: approval.projectId,
1381
+ requestId,
1382
+ dangerAction: approval.action,
1383
+ reason: "already-executed",
1384
+ });
1385
+ store.save();
1386
+ return { executed: false, reason: "already-executed" };
1387
+ }
1388
+
1389
+ const planned = planCommand(approval.action, approval.args ?? {});
1390
+ if ("error" in planned) {
1391
+ store.appendAudit({
1392
+ action: "approval/execution-refused",
1393
+ projectId: approval.projectId,
1394
+ requestId,
1395
+ dangerAction: approval.action,
1396
+ reason: planned.error,
1397
+ });
1398
+ store.save();
1399
+ return { executed: false, reason: planned.error };
1400
+ }
1401
+
1402
+ // push-branch:在工作树里跑真实 git(argv 数组,不经 shell),只推我们自己的分支
1403
+ if (approval.action === "push-branch") {
1404
+ const sessionId = String(approval.args?.sessionId ?? approval.args?.threadSessionId ?? "");
1405
+ const thread = store
1406
+ .listThreads(approval.projectId)
1407
+ .find((/** @type {any} */ item) => item.sessionId === sessionId);
1408
+ const worktree =
1409
+ typeof thread?.worktree === "string" && thread.worktree !== "" ? thread.worktree : "";
1410
+ if (worktree === "") {
1411
+ store.appendAudit({
1412
+ action: "approval/execution-refused",
1413
+ projectId: approval.projectId,
1414
+ requestId,
1415
+ dangerAction: approval.action,
1416
+ reason: "no-worktree",
1417
+ });
1418
+ store.save();
1419
+ return { executed: false, reason: "no-worktree" };
1420
+ }
1421
+ const branch = String(approval.args?.branch ?? thread?.branch ?? "");
1422
+ const pushed = await runGit(["push", "-u", "origin", branch], worktree);
1423
+ const ok = pushed.code === 0;
1424
+ const evidence = recoveryEvidence(approval.action, { branch }, { stdout: pushed.stdout });
1425
+ store.appendAudit({
1426
+ action: ok ? "approval/executed" : "approval/execution-failed",
1427
+ projectId: approval.projectId,
1428
+ requestId,
1429
+ dangerAction: approval.action,
1430
+ evidence,
1431
+ ...(ok ? {} : { reason: String(pushed.stderr).split("\n")[0].slice(0, 200) }),
1432
+ });
1433
+ store.save();
1434
+ return ok ? { executed: true, evidence } : { executed: false, reason: "push-failed" };
1435
+ }
1436
+
1437
+ // merge 走 gh:需要真实远端与 PR 号,留给后续步骤(这里只回报计划)
1438
+ if (approval.action === "delete-project") {
1439
+ const result = this.deleteProject(approval.projectId);
1440
+ const evidence = recoveryEvidence(approval.action, approval.args ?? {}, result);
1441
+ store.appendAudit({
1442
+ action: "approval/executed",
1443
+ projectId: approval.projectId,
1444
+ requestId,
1445
+ dangerAction: approval.action,
1446
+ evidence,
1447
+ });
1448
+ store.save();
1449
+ return { executed: true, evidence };
1450
+ }
1451
+
1452
+ // merge:走 gh pr merge(argv 里已含 --squash,不带 --admin/--force)。
1453
+ // 只合并我们自己的 PR:planCommand 已保证 PR 号是正整数,且危险开关与阈值都过了。
1454
+ if (approval.action === "merge") {
1455
+ const ghArgs = planned.argv.slice(1); // 去掉 argv[0] 的 "gh"
1456
+ const merged = await runGh(ghArgs);
1457
+ const ok = merged.code === 0;
1458
+ const evidence = recoveryEvidence(approval.action, approval.args ?? {}, {
1459
+ stdout: merged.stdout,
1460
+ });
1461
+ store.appendAudit({
1462
+ action: ok ? "approval/executed" : "approval/execution-failed",
1463
+ projectId: approval.projectId,
1464
+ requestId,
1465
+ dangerAction: approval.action,
1466
+ evidence,
1467
+ ...(ok
1468
+ ? {}
1469
+ : { reason: String(merged.stderr).split("\n")[0].slice(0, 200) || "gh-merge-failed" }),
1470
+ });
1471
+ store.save();
1472
+ return ok ? { executed: true, evidence } : { executed: false, reason: "gh-merge-failed" };
1473
+ }
1474
+
1475
+ store.appendAudit({
1476
+ action: "approval/execution-deferred",
1477
+ projectId: approval.projectId,
1478
+ requestId,
1479
+ dangerAction: approval.action,
1480
+ reason: "remote-action-not-implemented",
1481
+ planned: planned.argv,
1482
+ });
1483
+ store.save();
1484
+ return { executed: false, reason: "remote-action-not-implemented", planned: planned.argv };
1485
+ }
1486
+
1487
+ /**
1488
+ * 决议一条申请。**只改状态,不执行动作**——执行留给 M4 的受控执行器。
1489
+ * @param {string} requestId
1490
+ * @param {"approved"|"rejected"} status
1491
+ */
1492
+ resolveApproval(requestId, status) {
1493
+ const store = this.requireStore();
1494
+ const resolved = store.resolveApproval(
1495
+ requestId,
1496
+ status === "approved" ? "approved" : "rejected",
1497
+ );
1498
+ store.appendAudit({
1499
+ action: "approval/resolved",
1500
+ projectId: resolved.projectId,
1501
+ requestId,
1502
+ result: resolved.status,
1503
+ });
1504
+ store.save();
1505
+ return resolved;
1506
+ }
1507
+
1508
+ /**
1509
+ * 路由 dry-run:给定一段输入,说清「按哪条规则、会做什么、被谁拦」。
1510
+ * 纯决策、零副作用——真正的执行(建线程等)留给 M3 后续步骤。
1511
+ * @param {string} projectId
1512
+ * @param {string} text
1513
+ */
1514
+ previewRoute(projectId, text) {
1515
+ const store = this.requireStore();
1516
+ const project = store.getProject(projectId);
1517
+ if (!project) throw new Error(`projects: unknown project ${projectId}`);
1518
+ const input = String(text ?? "");
1519
+ const decision = decideRoute({
1520
+ text: input,
1521
+ rules: project.policy?.routing?.rules ?? [],
1522
+ autonomy: project.policy?.autonomy ?? "L1",
1523
+ isQuestion:
1524
+ /[??]\s*$/u.test(input.trim()) ||
1525
+ /^(why|how|what|when|where|who|is|are|can|should|能否|为什么|怎么|如何)/iu.test(
1526
+ input.trim(),
1527
+ ),
1528
+ });
1529
+ return {
1530
+ ...decision,
1531
+ autonomy: project.policy?.autonomy ?? "L1",
1532
+ allowFallback: project.policy?.routing?.fallback !== false,
1533
+ inputLength: input.length,
1534
+ };
1535
+ }
1536
+
1537
+ /**
1538
+ * 线程进度(面板用):状态由持久事件归约,按「需要我」优先排序。
1539
+ * @param {string} projectId
1540
+ */
1541
+ progress(projectId) {
1542
+ const store = this.requireStore();
1543
+ const threads = store.listThreads(projectId);
1544
+ const rows = threads.map((/** @type {any} */ thread) => ({
1545
+ sessionId: thread.sessionId,
1546
+ branch: thread.branch ?? null,
1547
+ worktree: thread.worktree ?? null,
1548
+ view: this.views.get(thread.sessionId) ?? initialView(),
1549
+ }));
1550
+ const sorted = sortRows(rows);
1551
+ /** @type {Record<string, number>} */
1552
+ const counts = { "waiting-user": 0, failed: 0, working: 0, done: 0, idle: 0 };
1553
+ for (const row of rows) counts[row.view.state] = (counts[row.view.state] ?? 0) + 1;
1554
+ const project = store.getProject(projectId);
1555
+ const budget = checkThreadBudget({ project, threads, now: Date.now() });
1556
+ return {
1557
+ rows: sorted,
1558
+ counts,
1559
+ total: rows.length,
1560
+ attention: counts["waiting-user"] + counts.failed,
1561
+ budget: {
1562
+ ok: budget.ok,
1563
+ reason: budget.reason,
1564
+ used: budget.used,
1565
+ limits: project?.budget ?? null,
1566
+ tokensToday: store.tokenUsageToday(projectId, Date.now()),
1567
+ },
1568
+ projectState: project?.state ?? "active",
1569
+ };
1570
+ }
1571
+
1572
+ /** 诊断:哪些会话已挂上项目上下文(只读,供冒烟/排障)。 */
1573
+ debugAttached() {
1574
+ return [...this.attached.keys()];
1575
+ }
1576
+
1577
+ /** 只读概览:数据根、项目数、已挂上下文的会话数(给客户端首屏与冒烟用)。 */
1578
+ describe() {
1579
+ const projects = this.store ? this.store.listProjects() : [];
1580
+ return {
1581
+ dataRoot: this.dataRoot,
1582
+ available: Boolean(this.store),
1583
+ projectCount: projects.length,
1584
+ activeCount: projects.filter((p) => p.state === "active").length,
1585
+ attachedSessions: this.attached.size,
1586
+ renderStats: this.renderStats ?? {},
1587
+ };
1588
+ }
1589
+
1590
+ /**
1591
+ * 建一个线程(尽力隔离到独立 worktree)。
1592
+ * @param {string} projectId
1593
+ * @param {string} task
1594
+ */
1595
+ async createThread(projectId, task) {
1596
+ await this.waitServices();
1597
+ const store = this.requireStore();
1598
+ // 预算闸:暂停/归档、每日线程数、并发数。拒绝时给可读原因,不静默降级。
1599
+ const project = store.getProject(projectId);
1600
+ if (!project) throw new Error(`projects: unknown project ${projectId}`);
1601
+ const nowMs = Date.now();
1602
+ const tokenVerdict = checkTokenBudget({
1603
+ dailyTokens: project.budget?.dailyTokens,
1604
+ usedTokens: store.tokenUsageToday(projectId, nowMs),
1605
+ });
1606
+ if (!tokenVerdict.ok) {
1607
+ store.appendAudit({ action: "thread/rejected", projectId, reason: tokenVerdict.reason });
1608
+ store.save();
1609
+ throw new Error(
1610
+ `projects: ${tokenVerdict.reason} (used=${tokenVerdict.used}, limit=${tokenVerdict.limit})`,
1611
+ );
1612
+ }
1613
+ const verdict = checkThreadBudget({
1614
+ project,
1615
+ threads: store.listThreads(projectId),
1616
+ now: nowMs,
1617
+ });
1618
+ if (!verdict.ok) {
1619
+ store.appendAudit({ action: "thread/rejected", projectId, reason: verdict.reason });
1620
+ store.save();
1621
+ throw new Error(
1622
+ `projects: ${verdict.reason} (today=${verdict.used.today}, running=${verdict.used.running})`,
1623
+ );
1624
+ }
1625
+ const sc = this.sessionController;
1626
+ if (!sc) throw new Error("projects: session controller unavailable");
1627
+ const thread = await createIsolatedThread({
1628
+ store,
1629
+ dataRoot: this.dataRoot,
1630
+ projectId,
1631
+ deps: {
1632
+ runGit: runGit,
1633
+ createSession: async (/** @type {{cwd: string}} */ request) => {
1634
+ const created = await sc.create({ cwd: request.cwd });
1635
+ return { sessionId: String(created.sessionId) };
1636
+ },
1637
+ },
1638
+ });
1639
+ store.save();
1640
+ if (typeof task === "string" && task.trim() !== "") {
1641
+ try {
1642
+ await sc.prompt(
1643
+ {
1644
+ requestId: `projects-thread-${Date.now()}`,
1645
+ sessionId: thread.sessionId,
1646
+ mode: "queue",
1647
+ content: [{ type: "text", text: task }],
1648
+ },
1649
+ new AbortController().signal,
1650
+ );
1651
+ } catch {
1652
+ /* 投递失败不影响线程本身;面板会显示 idle */
1653
+ }
1654
+ }
1655
+ return thread;
1656
+ }
1657
+
1658
+ /**
1659
+ * 回收一个线程的 worktree(三重判据不满足就拒绝)。
1660
+ * @param {string} sessionId
1661
+ */
1662
+ async reclaimThread(sessionId) {
1663
+ const store = this.requireStore();
1664
+ const result = await reclaimThreadWorktree({ store, sessionId, deps: { runGit } });
1665
+ store.save();
1666
+ return result;
1667
+ }
1668
+
1669
+ /** @param {string} sessionId */
1670
+ detachThread(sessionId) {
1671
+ const store = this.requireStore();
1672
+ const removed = store.detachThread(sessionId);
1673
+ store.save();
1674
+ return removed;
1675
+ }
1676
+ }
1677
+
1678
+ declareRemote(ProjectsService, "listProjects");
1679
+ declareRemote(ProjectsService, "getProject");
1680
+ declareRemote(ProjectsService, "listThreads");
1681
+ declareRemote(ProjectsService, "projectOfSession");
1682
+ declareRemote(ProjectsService, "createProject");
1683
+ declareRemote(ProjectsService, "updateProject");
1684
+ declareRemote(ProjectsService, "pauseProject");
1685
+ declareRemote(ProjectsService, "resumeProject");
1686
+ declareRemote(ProjectsService, "archiveProject");
1687
+ declareRemote(ProjectsService, "unarchiveProject");
1688
+ declareRemote(ProjectsService, "reconcileWakes");
1689
+ declareRemote(ProjectsService, "previewDeleteProject");
1690
+ declareRemote(ProjectsService, "deleteProject");
1691
+ declareRemote(ProjectsService, "attachThread");
1692
+ declareRemote(ProjectsService, "detachThread");
1693
+ declareRemote(ProjectsService, "createThread");
1694
+ declareRemote(ProjectsService, "reclaimThread");
1695
+ declareRemote(ProjectsService, "progress");
1696
+ declareRemote(ProjectsService, "previewRoute");
1697
+ declareRemote(ProjectsService, "route");
1698
+ declareRemote(ProjectsService, "requestAction");
1699
+ declareRemote(ProjectsService, "listApprovals");
1700
+ declareRemote(ProjectsService, "resolveApproval");
1701
+ declareRemote(ProjectsService, "executeApproval");
1702
+ declareRemote(ProjectsService, "autoFixStep");
1703
+ declareRemote(ProjectsService, "openPr");
1704
+ declareRemote(ProjectsService, "ensureCoordinator");
1705
+ declareRemote(ProjectsService, "debugAttached");
1706
+ declareRemote(ProjectsService, "detachSession");
1707
+ declareRemote(ProjectsService, "describe");
1708
+ declareRemote(ProjectsService, "getProjectContent");
1709
+ declareRemote(ProjectsService, "appendMemory");
1710
+ declareRemote(ProjectsService, "listAudit");