@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/store.js ADDED
@@ -0,0 +1,547 @@
1
+ // @ts-check
2
+ // 项目仓储:元数据的唯一真源。
3
+ // 为什么不用 ctx.storage.domain:M1 阶段元数据需要「人可读 + 可测试 + 可导出」,
4
+ // 先用带原子写的 JSON 仓储,把 schema 版本与迁移握在自己手里;M2 再评估迁到 storageDomain
5
+ // (届时用同一套 spec 形状,迁移点集中在 load/save 两处)。
6
+
7
+ import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
8
+ import { dirname, join } from "node:path";
9
+
10
+ import { defaultRules } from "./routing.js";
11
+
12
+ /** 当前元数据格式版本。任何不兼容变更都要 +1 并在 migrate() 里补一步。 */
13
+ export const FORMAT_VERSION = 1;
14
+
15
+ /**
16
+ * @typedef {object} ProjectPolicy
17
+ * @property {'L0'|'L1'|'L2'|'L3'} autonomy
18
+ * @property {readonly string[]} preapprove
19
+ * @property {Record<string, boolean>} danger 危险动作开关,默认全 false
20
+ * @property {{ rules: any[], fallback: boolean }} routing 路由规则(扁平结构)与是否允许模型兜底
21
+ * @property {string} persona 协调器人格;空串表示用内置默认人格
22
+ */
23
+
24
+ /**
25
+ * @typedef {object} ProjectRecord
26
+ * @property {string} id
27
+ * @property {string} name
28
+ * @property {string} goal
29
+ * @property {'active'|'paused'|'archived'} state
30
+ * @property {string[]} dirs
31
+ * @property {string|null} coordinatorSessionId
32
+ * @property {ProjectPolicy} policy
33
+ * @property {{dailyTokens:number|null, maxThreadsPerDay:number|null, maxStepsPerThread:number|null}} budget
34
+ * @property {string} createdAt
35
+ * @property {string} updatedAt
36
+ */
37
+
38
+ /**
39
+ * @typedef {object} ThreadRecord
40
+ * @property {string} projectId
41
+ * @property {'idle'|'working'|'waiting'|'done'|'failed'} state
42
+ * @property {string|null} branch
43
+ * @property {string|null} worktree
44
+ * @property {number} seq
45
+ */
46
+
47
+ /** 危险动作开关的默认值:全部关闭("归档"是可逆动作,由 state 表达,不在此列)。 */
48
+ export const DEFAULT_DANGER = Object.freeze({
49
+ forcePushOwnBranch: false,
50
+ pushProtectedBranch: false,
51
+ autoMerge: false,
52
+ trashAuto: false,
53
+ purgeAfterRetention: false,
54
+ editProfile: false,
55
+ });
56
+
57
+ /** @returns {ProjectPolicy} */
58
+ export function defaultPolicy() {
59
+ return {
60
+ autonomy: "L1",
61
+ preapprove: [],
62
+ danger: { ...DEFAULT_DANGER },
63
+ // 路由:扁平规则数组 + 是否允许模型兜底(兜底也只能提议,不能直接执行危险动作)
64
+ routing: { rules: defaultRules(), fallback: true },
65
+ // 协调器人格;空串表示用内置默认人格
66
+ persona: "",
67
+ };
68
+ }
69
+
70
+ /**
71
+ * 把任意 policy 收敛成合法形状(缺失补齐、类型纠正、危险开关默认关)。
72
+ * normalize() 与 updateProject() 共用,避免两套规则漂移。
73
+ * @param {any} raw
74
+ * @param {any} [fallbackPolicy] 未指定的字段从这里继承
75
+ */
76
+ export function normalizePolicy(raw, fallbackPolicy) {
77
+ const policy = raw && typeof raw === "object" ? raw : {};
78
+ const previous = fallbackPolicy && typeof fallbackPolicy === "object" ? fallbackPolicy : {};
79
+ const routingRaw = policy.routing ?? previous.routing ?? {};
80
+ const levels = ["L0", "L1", "L2", "L3"];
81
+ return {
82
+ autonomy: levels.includes(policy.autonomy)
83
+ ? policy.autonomy
84
+ : levels.includes(previous.autonomy)
85
+ ? previous.autonomy
86
+ : "L1",
87
+ preapprove: Array.isArray(policy.preapprove)
88
+ ? policy.preapprove
89
+ : Array.isArray(previous.preapprove)
90
+ ? previous.preapprove
91
+ : [],
92
+ danger: {
93
+ ...DEFAULT_DANGER,
94
+ ...(previous.danger && typeof previous.danger === "object" ? previous.danger : {}),
95
+ ...(policy.danger && typeof policy.danger === "object" ? policy.danger : {}),
96
+ },
97
+ routing: {
98
+ rules: Array.isArray(routingRaw?.rules) ? routingRaw.rules : [],
99
+ fallback: routingRaw?.fallback !== false,
100
+ },
101
+ persona:
102
+ typeof policy.persona === "string"
103
+ ? policy.persona
104
+ : typeof previous.persona === "string"
105
+ ? previous.persona
106
+ : "",
107
+ };
108
+ }
109
+
110
+ /** @param {number} [now] */
111
+ function iso(now = Date.now()) {
112
+ return new Date(now).toISOString();
113
+ }
114
+
115
+ /** @param {string} path @returns {any} */
116
+ function emptyState(path) {
117
+ return {
118
+ format: FORMAT_VERSION,
119
+ root: path,
120
+ projects: {},
121
+ threads: {},
122
+ audit: [],
123
+ approvals: [],
124
+ };
125
+ }
126
+
127
+ /**
128
+ * 把任意输入收敛成合法状态;不认识的字段保留(前向兼容),缺失的补齐。
129
+ * @param {any} raw
130
+ * @param {string} root
131
+ */
132
+ export function normalize(raw, root) {
133
+ const state = emptyState(root);
134
+ if (!raw || typeof raw !== "object") return state;
135
+ const format = Number.isInteger(raw.format) ? raw.format : 0;
136
+ if (format > FORMAT_VERSION) {
137
+ throw new Error(
138
+ `projects: metadata format ${format} is newer than supported ${FORMAT_VERSION}`,
139
+ );
140
+ }
141
+ state.format = Math.max(FORMAT_VERSION, format === 0 ? FORMAT_VERSION : format);
142
+ if (raw.projects && typeof raw.projects === "object") {
143
+ for (const [id, value] of Object.entries(raw.projects)) {
144
+ if (!value || typeof value !== "object") continue;
145
+ const project = /** @type {any} */ (value);
146
+ state.projects[id] = {
147
+ ...project,
148
+ id,
149
+ name: typeof project.name === "string" ? project.name : id,
150
+ goal: typeof project.goal === "string" ? project.goal : "",
151
+ state: ["active", "paused", "archived"].includes(project.state) ? project.state : "active",
152
+ dirs: Array.isArray(project.dirs)
153
+ ? project.dirs.filter((/** @type {unknown} */ d) => typeof d === "string")
154
+ : [],
155
+ coordinatorSessionId:
156
+ typeof project.coordinatorSessionId === "string" ? project.coordinatorSessionId : null,
157
+ policy: normalizePolicy(project.policy),
158
+ budget: {
159
+ dailyTokens:
160
+ typeof project.budget?.dailyTokens === "number" ? project.budget.dailyTokens : null,
161
+ maxThreadsPerDay:
162
+ typeof project.budget?.maxThreadsPerDay === "number"
163
+ ? project.budget.maxThreadsPerDay
164
+ : null,
165
+ maxStepsPerThread:
166
+ typeof project.budget?.maxStepsPerThread === "number"
167
+ ? project.budget.maxStepsPerThread
168
+ : null,
169
+ },
170
+ createdAt: typeof project.createdAt === "string" ? project.createdAt : iso(),
171
+ updatedAt: typeof project.updatedAt === "string" ? project.updatedAt : iso(),
172
+ };
173
+ }
174
+ }
175
+ if (raw.threads && typeof raw.threads === "object") {
176
+ for (const [sessionId, value] of Object.entries(raw.threads)) {
177
+ const thread = /** @type {any} */ (value);
178
+ if (!thread || typeof thread.projectId !== "string") continue;
179
+ state.threads[sessionId] = {
180
+ ...thread,
181
+ projectId: thread.projectId,
182
+ state: ["idle", "working", "waiting", "done", "failed"].includes(thread.state)
183
+ ? thread.state
184
+ : "idle",
185
+ branch: typeof thread.branch === "string" ? thread.branch : null,
186
+ worktree: typeof thread.worktree === "string" ? thread.worktree : null,
187
+ seq: Number.isInteger(thread.seq) ? thread.seq : 0,
188
+ createdAt: typeof thread.createdAt === "string" ? thread.createdAt : iso(),
189
+ lastWakeTurn: Number.isInteger(thread.lastWakeTurn) ? thread.lastWakeTurn : 0,
190
+ autoFixRound: Number.isInteger(thread.autoFixRound) ? thread.autoFixRound : 0,
191
+ autoFixSignature:
192
+ typeof thread.autoFixSignature === "string" ? thread.autoFixSignature : "",
193
+ autoFixChanged: Array.isArray(thread.autoFixChanged) ? thread.autoFixChanged : [],
194
+ };
195
+ }
196
+ }
197
+ if (Array.isArray(raw.audit)) state.audit = raw.audit.slice(-5000);
198
+ state.approvals = Array.isArray(raw.approvals) ? raw.approvals : [];
199
+ state.usage = raw.usage && typeof raw.usage === "object" ? raw.usage : {};
200
+ return state;
201
+ }
202
+
203
+ /** 稳定的短 id(不引入依赖:时间戳 + 随机段)。 */
204
+ export function newProjectId(/** @type {number} */ now = Date.now()) {
205
+ const random = Math.random().toString(36).slice(2, 10);
206
+ return `prj_${now.toString(36)}${random}`;
207
+ }
208
+
209
+ export class ProjectStore {
210
+ /** @type {any} */
211
+ state;
212
+
213
+ /**
214
+ * @param {{root: string, now?: () => number}} options
215
+ */
216
+ constructor(options) {
217
+ if (!options || typeof options.root !== "string" || options.root === "") {
218
+ throw new Error("projects: store requires an injectable data root");
219
+ }
220
+ this.root = options.root;
221
+ this.file = join(options.root, "projects.json");
222
+ this.now = options.now ?? (() => Date.now());
223
+ /** @type {any} */
224
+ this.state = emptyState(this.root);
225
+ }
226
+
227
+ load() {
228
+ if (!existsSync(this.file)) {
229
+ mkdirSync(dirname(this.file), { recursive: true });
230
+ this.state = emptyState(this.root);
231
+ return this;
232
+ }
233
+ const text = readFileSync(this.file, "utf8");
234
+ /** @type {any} */
235
+ let raw;
236
+ try {
237
+ raw = JSON.parse(text);
238
+ } catch (_error) {
239
+ // 不认识的/损坏的文件不删:改名隔离后从空状态起步(硬性约定 1:保留而非 rm -rf)
240
+ const quarantine = `${this.file}.corrupt-${this.now()}`;
241
+ try {
242
+ renameSync(this.file, quarantine);
243
+ } catch {
244
+ /* 隔离失败就保留原文件 */
245
+ }
246
+ throw new Error(`projects: metadata is not valid JSON, quarantined to ${quarantine}`);
247
+ }
248
+ this.state = normalize(raw, this.root);
249
+ return this;
250
+ }
251
+
252
+ save() {
253
+ mkdirSync(dirname(this.file), { recursive: true });
254
+ const tmp = `${this.file}.tmp-${this.now()}`;
255
+ writeFileSync(tmp, `${JSON.stringify(this.state, null, 2)}\n`, { mode: 0o600 });
256
+ renameSync(tmp, this.file);
257
+ return this;
258
+ }
259
+
260
+ /** @param {string} name @param {{goal?: string, dirs?: string[]}} [input] */
261
+ createProject(name, input = {}) {
262
+ const trimmed = String(name ?? "").trim();
263
+ if (trimmed === "") throw new Error("projects: project name is required");
264
+ const id = newProjectId(this.now());
265
+ const stamp = iso(this.now());
266
+ this.state.projects[id] = {
267
+ id,
268
+ name: trimmed,
269
+ goal: typeof input.goal === "string" ? input.goal : "",
270
+ state: "active",
271
+ dirs: Array.isArray(input.dirs) ? input.dirs.filter((d) => typeof d === "string") : [],
272
+ coordinatorSessionId: null,
273
+ policy: defaultPolicy(),
274
+ budget: {
275
+ dailyTokens: null,
276
+ maxThreadsPerDay: null,
277
+ maxStepsPerThread: null,
278
+ maxConcurrent: null,
279
+ },
280
+ createdAt: stamp,
281
+ updatedAt: stamp,
282
+ };
283
+ return { ...this.state.projects[id] };
284
+ }
285
+
286
+ /** @param {string} id */
287
+ getProject(id) {
288
+ const found = this.state.projects[id];
289
+ return found ? { ...found } : undefined;
290
+ }
291
+
292
+ listProjects() {
293
+ return Object.values(this.state.projects).map((/** @type {any} */ p) => ({ ...p }));
294
+ }
295
+
296
+ /**
297
+ * @param {string} id
298
+ * @param {Partial<{name: string, goal: string, state: string, dirs: string[], coordinatorSessionId: string|null, policy: any, persona: string, budget: any}>} patch
299
+ */
300
+ updateProject(id, patch) {
301
+ const current = this.state.projects[id];
302
+ if (!current) throw new Error(`projects: unknown project ${id}`);
303
+ const next = { ...current };
304
+ if (typeof patch.name === "string" && patch.name.trim() !== "") next.name = patch.name.trim();
305
+ if (typeof patch.goal === "string") next.goal = patch.goal;
306
+ if (["active", "paused", "archived"].includes(String(patch.state))) next.state = patch.state;
307
+ if (Array.isArray(patch.dirs))
308
+ next.dirs = patch.dirs.filter((/** @type {unknown} */ d) => typeof d === "string");
309
+ if (patch.coordinatorSessionId === null || typeof patch.coordinatorSessionId === "string") {
310
+ next.coordinatorSessionId = patch.coordinatorSessionId;
311
+ }
312
+ if (patch.policy && typeof patch.policy === "object") {
313
+ next.policy = normalizePolicy(patch.policy, current.policy);
314
+ }
315
+ if (typeof patch.persona === "string") {
316
+ next.policy = normalizePolicy(
317
+ { ...(next.policy ?? current.policy), persona: patch.persona },
318
+ current.policy,
319
+ );
320
+ }
321
+ if (patch.budget && typeof patch.budget === "object") {
322
+ next.budget = { ...(current.budget ?? {}), ...patch.budget };
323
+ }
324
+ next.updatedAt = iso(this.now());
325
+ this.state.projects[id] = next;
326
+ return { ...next };
327
+ }
328
+
329
+ /**
330
+ * 归档是唯一"默认开启"的自动化动作;它可逆,且不删数据。
331
+ * @param {string} id
332
+ */
333
+ archiveProject(id) {
334
+ return this.updateProject(id, { state: "archived" });
335
+ }
336
+
337
+ /** @param {string} sessionId @param {string} projectId */
338
+ attachThread(sessionId, projectId) {
339
+ if (!this.state.projects[projectId]) throw new Error(`projects: unknown project ${projectId}`);
340
+ const current = this.state.threads[sessionId];
341
+ this.state.threads[sessionId] = {
342
+ projectId,
343
+ state: current?.state ?? "idle",
344
+ branch: current?.branch ?? null,
345
+ worktree: current?.worktree ?? null,
346
+ seq: current?.seq ?? 0,
347
+ createdAt: current?.createdAt ?? iso(this.now()),
348
+ lastWakeTurn: current?.lastWakeTurn ?? 0,
349
+ autoFixRound: current?.autoFixRound ?? 0,
350
+ autoFixSignature: current?.autoFixSignature ?? "",
351
+ autoFixChanged: current?.autoFixChanged ?? [],
352
+ };
353
+ return { ...this.state.threads[sessionId] };
354
+ }
355
+
356
+ /**
357
+ * 删除一个项目记录,并摘掉它的线程归属(**不动会话日志**)。
358
+ * 返回被删内容,供调用方写进回收站清单。
359
+ * @param {string} id
360
+ */
361
+ removeProject(id) {
362
+ const project = this.state.projects[id];
363
+ if (!project) throw new Error(`projects: unknown project ${id}`);
364
+ const threads = Object.entries(this.state.threads)
365
+ .filter(([, thread]) => /** @type {any} */ (thread).projectId === id)
366
+ .map(([sessionId, thread]) => ({ sessionId, .../** @type {any} */ (thread) }));
367
+ delete this.state.projects[id];
368
+ for (const thread of threads) delete this.state.threads[thread.sessionId];
369
+ return { project: { ...project }, threads };
370
+ }
371
+
372
+ /**
373
+ * 记录线程的 worktree 归属(建 worktree 成功后调用)。
374
+ * @param {string} sessionId
375
+ * @param {{ branch?: string|null, worktree?: string|null, baseSha?: string|null, state?: string }} patch
376
+ */
377
+ setThreadWorktree(sessionId, patch) {
378
+ const current = this.state.threads[sessionId];
379
+ if (!current) throw new Error(`projects: unknown thread ${sessionId}`);
380
+ if (typeof patch.branch === "string" || patch.branch === null) current.branch = patch.branch;
381
+ if (typeof patch.worktree === "string" || patch.worktree === null)
382
+ current.worktree = patch.worktree;
383
+ if (typeof patch.baseSha === "string" || patch.baseSha === null)
384
+ current.baseSha = patch.baseSha;
385
+ if (typeof patch.state === "string") current.state = patch.state;
386
+ return { ...current };
387
+ }
388
+
389
+ /**
390
+ * 累加今天的 token 花费(按项目 + 本地日期分桶,跨重启保留)。
391
+ * @param {string} projectId
392
+ * @param {number} tokens
393
+ * @param {number} [now]
394
+ * @returns {{ date: string, tokens: number }}
395
+ */
396
+ addTokenUsage(projectId, tokens, now = this.now()) {
397
+ const amount = Number.isFinite(tokens) ? Math.max(0, Math.trunc(Number(tokens))) : 0;
398
+ const date = new Date(now).toISOString().slice(0, 10);
399
+ this.state.usage = this.state.usage ?? {};
400
+ const bucket = this.state.usage[projectId] ?? { date, tokens: 0 };
401
+ if (bucket.date !== date) {
402
+ bucket.date = date;
403
+ bucket.tokens = 0;
404
+ }
405
+ bucket.tokens += amount;
406
+ this.state.usage[projectId] = bucket;
407
+ return { ...bucket };
408
+ }
409
+
410
+ /**
411
+ * 读今天的 token 花费(日期不同就视为 0)。
412
+ * @param {string} projectId
413
+ * @param {number} [now]
414
+ */
415
+ tokenUsageToday(projectId, now = this.now()) {
416
+ const date = new Date(now).toISOString().slice(0, 10);
417
+ const bucket = this.state.usage?.[projectId];
418
+ if (!bucket || bucket.date !== date) return 0;
419
+ return Number.isFinite(bucket.tokens) ? bucket.tokens : 0;
420
+ }
421
+
422
+ /**
423
+ * 记录 auto-fix 进度(轮次 / 上次错误签名 / 上次改动文件)。
424
+ * @param {string} sessionId
425
+ * @param {{ round?: number, signature?: string, changedFiles?: string[] }} patch
426
+ */
427
+ setThreadAutoFix(sessionId, patch) {
428
+ const current = this.state.threads[sessionId];
429
+ if (!current) throw new Error(`projects: unknown thread ${sessionId}`);
430
+ if (Number.isInteger(patch.round)) current.autoFixRound = patch.round;
431
+ if (typeof patch.signature === "string") current.autoFixSignature = patch.signature;
432
+ if (Array.isArray(patch.changedFiles)) current.autoFixChanged = patch.changedFiles;
433
+ return { ...current };
434
+ }
435
+
436
+ /**
437
+ * 记录线程已经唤醒到第几轮(避免同一轮重复唤醒协调器)。
438
+ * @param {string} sessionId
439
+ * @param {number} turn
440
+ */
441
+ setThreadWakeState(sessionId, turn) {
442
+ const current = this.state.threads[sessionId];
443
+ if (!current) throw new Error(`projects: unknown thread ${sessionId}`);
444
+ current.lastWakeTurn = Number.isInteger(turn) ? turn : (current.lastWakeTurn ?? 0);
445
+ return { ...current };
446
+ }
447
+
448
+ /**
449
+ * 记录一条待审批的危险动作申请。
450
+ * @param {{ projectId: string, action: string, args?: any, reason: string }} request
451
+ * @returns {{ requestId: string }}
452
+ */
453
+ appendApproval(request) {
454
+ const requestId = `apr_${this.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`;
455
+ this.state.approvals.push({
456
+ requestId,
457
+ projectId: String(request.projectId),
458
+ action: String(request.action),
459
+ args: request.args ?? null,
460
+ reason: String(request.reason ?? ""),
461
+ status: "pending",
462
+ at: iso(this.now()),
463
+ resolvedAt: null,
464
+ });
465
+ return { requestId };
466
+ }
467
+
468
+ /**
469
+ * @param {string} [projectId] 省略则返回全部
470
+ * @returns {any[]}
471
+ */
472
+ listApprovals(projectId) {
473
+ return this.state.approvals.filter((/** @type {any} */ item) =>
474
+ projectId ? item.projectId === projectId : true,
475
+ );
476
+ }
477
+
478
+ /**
479
+ * 标记一条申请已执行(幂等保护:同一申请不能执行两次)。
480
+ * @param {string} requestId
481
+ * @param {any} [evidence]
482
+ */
483
+ markApprovalExecuted(requestId, evidence) {
484
+ const found = this.state.approvals.find(
485
+ (/** @type {any} */ item) => item.requestId === requestId,
486
+ );
487
+ if (!found) throw new Error(`projects: unknown approval ${requestId}`);
488
+ if (typeof found.executedAt === "string" && found.executedAt !== "") {
489
+ throw new Error(`projects: approval ${requestId} already executed`);
490
+ }
491
+ found.executedAt = iso(this.now());
492
+ found.evidence = evidence ?? null;
493
+ return { ...found };
494
+ }
495
+
496
+ /**
497
+ * 决议一条申请(approved / rejected)。只改状态,**不执行**动作。
498
+ * @param {string} requestId
499
+ * @param {"approved"|"rejected"} status
500
+ */
501
+ resolveApproval(requestId, status) {
502
+ const found = this.state.approvals.find(
503
+ (/** @type {any} */ item) => item.requestId === requestId,
504
+ );
505
+ if (!found) throw new Error(`projects: unknown approval ${requestId}`);
506
+ if (typeof found.executedAt === "string" && found.executedAt !== "") {
507
+ throw new Error(`projects: approval ${requestId} already executed`);
508
+ }
509
+ found.status = status;
510
+ found.resolvedAt = iso(this.now());
511
+ return { ...found };
512
+ }
513
+
514
+ /** @param {string} sessionId */
515
+ detachThread(sessionId) {
516
+ const existed = Boolean(this.state.threads[sessionId]);
517
+ delete this.state.threads[sessionId];
518
+ return existed;
519
+ }
520
+
521
+ /** @param {string} sessionId */
522
+ projectOfSession(sessionId) {
523
+ const thread = this.state.threads[sessionId];
524
+ if (!thread) return undefined;
525
+ return this.getProject(thread.projectId);
526
+ }
527
+
528
+ /** @param {string} projectId */
529
+ listThreads(projectId) {
530
+ /** @type {any} */ (this.state);
531
+ const entries = /** @type {Array<[string, any]>} */ (Object.entries(this.state.threads));
532
+ return entries
533
+ .filter(([, thread]) => thread.projectId === projectId)
534
+ .map(([sessionId, thread]) => ({ sessionId, ...thread }));
535
+ }
536
+
537
+ /** @param {any} entry */
538
+ appendAudit(entry) {
539
+ this.state.audit.push({ at: iso(this.now()), ...entry });
540
+ if (this.state.audit.length > 5000) this.state.audit.splice(0, this.state.audit.length - 5000);
541
+ }
542
+
543
+ /** 清空(仅测试与"删除数据"的显式动作使用)。 */
544
+ destroy() {
545
+ rmSync(this.root, { recursive: true, force: true });
546
+ }
547
+ }