@suifei/dsh-ai-team 0.3.54 → 0.3.60
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 +85 -0
- package/client.js +910 -384
- package/index.js +360 -45
- package/lib/diaglog.js +105 -0
- package/lib/domain/member-profile.js +4 -11
- package/lib/domain/policy.js +31 -0
- package/lib/host/member-tools.js +1 -1
- package/lib/host/people-view.js +104 -0
- package/lib/host/project-registry.js +6 -1
- package/lib/host/project-runtime.js +31 -3
- package/lib/host/risk-view.js +94 -0
- package/lib/host/service.js +195 -108
- package/lib/host/views.js +6 -16
- package/lib/host/waker.js +11 -1
- package/lib/host/weekly-view.js +83 -0
- package/lib/ledger/fold.js +36 -8
- package/lib/ledger/tools.js +118 -0
- package/lib/ledger/writer.js +115 -9
- package/lib/runtime/failure-policy.js +22 -8
- package/lib/runtime/member-runtime.js +6 -1
- package/lib/runtime/skill-provider.js +96 -33
- package/lib/vendor/skillopt/src/index.js +63 -3
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +6 -1
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 项目周报投影(R-11 / 视图组合纪律):同一份账本投影的窗口聚合,产出
|
|
3
|
+
* 正向/负向两种解读共用的数据结构——正向 = 完成了什么、一次通过多少;
|
|
4
|
+
* 负向 = 哪些返工了、Human 介入了几次、多少任务仍受阻。纯计数投影,
|
|
5
|
+
* 无新事件、无新数据结构。
|
|
6
|
+
*
|
|
7
|
+
* 口径(全部来自既有投影字段):
|
|
8
|
+
* - completed:status=done 且 updatedAt 在窗口内(done 的 updatedAt 即验收时间);
|
|
9
|
+
* - reworked:reviewRound ≥ 2(经历过 task/changes-requested)且窗口内有动静;
|
|
10
|
+
* - humanTouches:Thread 中 authorId === humanId 的条目数(窗口内 at)+
|
|
11
|
+
* 已答复决策数(requiresDecision 且 state==='done',ackedAt 窗口内);
|
|
12
|
+
* - humanTasks:ownerId === humanId 的活跃任务数("交给人"的负担面)。
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
export function weeklyView(state, { now = Date.now(), weeks = 1 } = {}) {
|
|
16
|
+
const windowStart = now - weeks * 7 * 24 * 60 * 60 * 1000;
|
|
17
|
+
const humanId = state.humanMemberId
|
|
18
|
+
?? Object.values(state.members ?? {}).find((member) => member.kind === 'human')?.id
|
|
19
|
+
?? null;
|
|
20
|
+
|
|
21
|
+
const completed = [];
|
|
22
|
+
const reworked = [];
|
|
23
|
+
let createdCount = 0;
|
|
24
|
+
for (const task of Object.values(state.tasks ?? {})) {
|
|
25
|
+
if (task.tombstone === true) continue;
|
|
26
|
+
const touchedAt = Math.max(task.updatedAt ?? 0, task.createdAt ?? 0);
|
|
27
|
+
if (task.createdAt >= windowStart) createdCount += 1;
|
|
28
|
+
if (task.status === 'done' && (task.updatedAt ?? 0) >= windowStart) {
|
|
29
|
+
completed.push({
|
|
30
|
+
taskId: task.id,
|
|
31
|
+
number: task.number ?? null,
|
|
32
|
+
title: task.title ?? '',
|
|
33
|
+
ownerName: state.members?.[task.ownerId]?.name ?? task.ownerId ?? null,
|
|
34
|
+
reviewRound: task.reviewRound ?? 1,
|
|
35
|
+
updatedAt: task.updatedAt ?? null,
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
if ((task.reviewRound ?? 0) >= 2 && touchedAt >= windowStart) {
|
|
39
|
+
reworked.push({
|
|
40
|
+
taskId: task.id,
|
|
41
|
+
number: task.number ?? null,
|
|
42
|
+
title: task.title ?? '',
|
|
43
|
+
reviewRound: task.reviewRound,
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
let humanThreadMessages = 0;
|
|
49
|
+
for (const thread of Object.values(state.threads ?? {})) {
|
|
50
|
+
for (const entry of thread.entries ?? []) {
|
|
51
|
+
if ((entry.at ?? 0) >= windowStart && entry.authorId === humanId) humanThreadMessages += 1;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
let decisionsAnswered = 0;
|
|
55
|
+
for (const item of Object.values(state.inbox ?? {})) {
|
|
56
|
+
if (item.type !== 'decision_required' || item.requiresDecision !== true) continue;
|
|
57
|
+
if (item.state !== 'done' && item.state !== 'resolved') continue;
|
|
58
|
+
if ((item.ackedAt ?? 0) >= windowStart) decisionsAnswered += 1;
|
|
59
|
+
}
|
|
60
|
+
const humanTasks = humanId === null ? 0
|
|
61
|
+
: Object.values(state.tasks ?? {}).filter((task) =>
|
|
62
|
+
task.tombstone !== true && ['pending', 'in_progress', 'pending_acceptance'].includes(task.status)
|
|
63
|
+
&& (task.ownerId === humanId || task.assigneeId === humanId)).length;
|
|
64
|
+
|
|
65
|
+
const completedTitles = completed.map((row) => '#' + (row.number ?? row.taskId) + ' ' + row.title);
|
|
66
|
+
return {
|
|
67
|
+
windowStart,
|
|
68
|
+
generatedAt: now,
|
|
69
|
+
weeks,
|
|
70
|
+
completedCount: completed.length,
|
|
71
|
+
createdCount,
|
|
72
|
+
reworkedCount: reworked.length,
|
|
73
|
+
humanThreadMessages,
|
|
74
|
+
decisionsAnswered,
|
|
75
|
+
humanTasks,
|
|
76
|
+
completed,
|
|
77
|
+
reworked,
|
|
78
|
+
// 正向解读的数据面:完成的清单与「零 Human 发言」的直通任务。
|
|
79
|
+
positive: { completedTitles, humanThreadMessages, decisionsAnswered },
|
|
80
|
+
// 负向解读的数据面:返工清单(reviewRound>=2)与仍然阻塞/待人的任务。
|
|
81
|
+
negative: { reworkedTitles: reworked.map((row) => '#' + (row.number ?? row.taskId) + ' ' + row.title), humanTasks },
|
|
82
|
+
};
|
|
83
|
+
}
|
package/lib/ledger/fold.js
CHANGED
|
@@ -31,9 +31,18 @@
|
|
|
31
31
|
*/
|
|
32
32
|
|
|
33
33
|
import { GENESIS_HASH, isPlainObject } from './events.js';
|
|
34
|
+
import { isReviewCandidate } from '../domain/policy.js';
|
|
34
35
|
|
|
35
36
|
/** 投影状态版本;改动折叠语义时必须递增(03 §6.4)。 */
|
|
36
|
-
export const FOLD_STATE_VERSION =
|
|
37
|
+
export const FOLD_STATE_VERSION = 2;
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* 投影封顶:大规模/长迭代账本下,stream 与每个 Thread 的 entries 不随事件数
|
|
41
|
+
* 无界增长(它们只是展示投影,完整历史在账本事件里,可按需重放)。
|
|
42
|
+
* headSeq/seq 单调计数不受影响,回复基线与去重仍然成立。
|
|
43
|
+
*/
|
|
44
|
+
export const STREAM_TAIL_LIMIT = 500;
|
|
45
|
+
export const THREAD_ENTRIES_LIMIT = 500;
|
|
37
46
|
|
|
38
47
|
export const TASK_STATUS = Object.freeze({
|
|
39
48
|
PENDING: 'pending',
|
|
@@ -84,6 +93,7 @@ function emptyState() {
|
|
|
84
93
|
threads: {},
|
|
85
94
|
inbox: {},
|
|
86
95
|
stream: [],
|
|
96
|
+
streamTotal: 0,
|
|
87
97
|
followers: {},
|
|
88
98
|
humanMemberId: null,
|
|
89
99
|
};
|
|
@@ -527,7 +537,13 @@ function applyThreadPosted(state, event, payload) {
|
|
|
527
537
|
eventId: event.id,
|
|
528
538
|
};
|
|
529
539
|
|
|
530
|
-
|
|
540
|
+
// Thread 条目 seq 单调递增(dedupe 已挡同 seq),直接追加;仅手工乱序回放
|
|
541
|
+
// 才回退到插入排序。entries 按 THREAD_ENTRIES_LIMIT 封顶,headSeq 仍单调。
|
|
542
|
+
const lastEntry = previous.entries[previous.entries.length - 1];
|
|
543
|
+
let entries = lastEntry !== undefined && lastEntry.seq > entrySeq
|
|
544
|
+
? [...previous.entries, entry].sort((left, right) => left.seq - right.seq)
|
|
545
|
+
: [...previous.entries, entry];
|
|
546
|
+
if (entries.length > THREAD_ENTRIES_LIMIT) entries = entries.slice(entries.length - THREAD_ENTRIES_LIMIT);
|
|
531
547
|
const headEntry = entries[entries.length - 1];
|
|
532
548
|
const headSeq = Math.max(previous.headSeq, entrySeq, headEntry.seq);
|
|
533
549
|
const thread = {
|
|
@@ -604,8 +620,16 @@ function applyStreamPosted(state, event, payload) {
|
|
|
604
620
|
parentEventId: stringOrNull(payload.parentEventId),
|
|
605
621
|
at: event.at,
|
|
606
622
|
};
|
|
607
|
-
|
|
608
|
-
|
|
623
|
+
// 事件按 seq 递增到达(applyEvent 已挡住 seq <= lastSeq),直接追加即可;
|
|
624
|
+
// 只有手工构造的乱序回放才需要插入排序,用末尾比较识别。投影按
|
|
625
|
+
// STREAM_TAIL_LIMIT 封顶:完整历史在账本里,可重放。
|
|
626
|
+
const last = state.stream[state.stream.length - 1];
|
|
627
|
+
let stream = last !== undefined && last.seq > event.seq
|
|
628
|
+
? [...state.stream, entry].sort((left, right) => left.seq - right.seq)
|
|
629
|
+
: [...state.stream, entry];
|
|
630
|
+
const streamTotal = (state.streamTotal ?? 0) + 1;
|
|
631
|
+
if (stream.length > STREAM_TAIL_LIMIT) stream = stream.slice(stream.length - STREAM_TAIL_LIMIT);
|
|
632
|
+
return advance(state, event, { stream, streamTotal });
|
|
609
633
|
}
|
|
610
634
|
|
|
611
635
|
function applyFollow(state, event, payload, following) {
|
|
@@ -698,6 +722,8 @@ export function applyEvent(state, event) {
|
|
|
698
722
|
const sessionId = textOr(payload.sessionId, null);
|
|
699
723
|
const member = memberId === null ? undefined : state.members[memberId];
|
|
700
724
|
if (member === undefined || sessionId === null) return advance(state, event);
|
|
725
|
+
// 投影防御:retired 成员不得被绑定事件复活,必须走 member.rejoin。
|
|
726
|
+
if (member.status === MEMBER_STATUS.RETIRED) return advance(state, event);
|
|
701
727
|
return advance(state, event, {
|
|
702
728
|
members: {
|
|
703
729
|
...state.members,
|
|
@@ -802,6 +828,8 @@ export function applyEvent(state, event) {
|
|
|
802
828
|
const memberId = textOr(payload.memberId, null);
|
|
803
829
|
const member = memberId === null ? undefined : state.members[memberId];
|
|
804
830
|
if (member === undefined) return advance(state, event);
|
|
831
|
+
// 投影防御:retired 成员的旧会话回报 completed 不算恢复。
|
|
832
|
+
if (member.status === MEMBER_STATUS.RETIRED) return advance(state, event);
|
|
805
833
|
return advance(state, event, {
|
|
806
834
|
members: {
|
|
807
835
|
...state.members,
|
|
@@ -820,6 +848,8 @@ export function applyEvent(state, event) {
|
|
|
820
848
|
const memberId = textOr(payload.memberId, null);
|
|
821
849
|
const member = memberId === null ? undefined : state.members[memberId];
|
|
822
850
|
if (member === undefined) return advance(state, event);
|
|
851
|
+
// 投影防御:重试退役成员必须走 member.rejoin(顺带清 talentPool)。
|
|
852
|
+
if (member.status === MEMBER_STATUS.RETIRED) return advance(state, event);
|
|
823
853
|
return advance(state, event, {
|
|
824
854
|
members: {
|
|
825
855
|
...state.members,
|
|
@@ -998,17 +1028,15 @@ export function isTaskBlocked(state, taskOrId) {
|
|
|
998
1028
|
|
|
999
1029
|
/**
|
|
1000
1030
|
* 验收资格纯函数(02 INV-04 / Q-05):
|
|
1001
|
-
* - Agent 必须未退役、不是当前 assignee、且从未 claim 过(历史谓词)。
|
|
1002
1031
|
* - Human 是唯一例外,可验收自己执行的 Task;二次确认由命令层负责。
|
|
1032
|
+
* - Agent 的资格判定统一走 policy.isReviewCandidate(与 views/Waker 同一实现)。
|
|
1003
1033
|
*/
|
|
1004
1034
|
export function isEligibleReviewer(state, taskId, memberId) {
|
|
1005
1035
|
const task = state.tasks[taskId];
|
|
1006
1036
|
const member = state.members[memberId];
|
|
1007
1037
|
if (!task || task.tombstone || !member) return false;
|
|
1008
1038
|
if (member.kind === 'human') return true;
|
|
1009
|
-
|
|
1010
|
-
if (task.assigneeId === memberId) return false;
|
|
1011
|
-
return !hasClaimed(task, memberId);
|
|
1039
|
+
return isReviewCandidate(member, task);
|
|
1012
1040
|
}
|
|
1013
1041
|
|
|
1014
1042
|
/** 状态里的 Task 是否处于已知状态值(供测试/诊断使用)。 */
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 账本工具面(R-15 / "plumbing 的 porcelain"):把 writer 已有的读取与
|
|
3
|
+
* 校验能力包装成不依赖宿主进程的人读操作——"一切有记录"的承诺必须可以
|
|
4
|
+
* **独立兑现**才成立。
|
|
5
|
+
*
|
|
6
|
+
* 纪律:全部只读;**不做 gc/压缩/删除**(D1 裁定:append-only 即历史不可变)。
|
|
7
|
+
*
|
|
8
|
+
* exportLedger(dir, outDir) 自包含导出包:段文件副本 + manifest.json +
|
|
9
|
+
* verify-report.md(人读校验结论)
|
|
10
|
+
* auditLedger(dir) 独立校验 hash 链,返回结构化结论(人读报告
|
|
11
|
+
* 由 CLI 层渲染)
|
|
12
|
+
* statsLedger(dir) 段/事件/字节计数与首尾时间
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import fsDefault from 'node:fs';
|
|
16
|
+
import pathDefault from 'node:path';
|
|
17
|
+
import { verifyChain } from './events.js';
|
|
18
|
+
|
|
19
|
+
function listSegments(dir, fs = fsDefault) {
|
|
20
|
+
return fs.readdirSync(dir)
|
|
21
|
+
.filter((name) => /^ledger-\d+\.jsonl$/.test(name))
|
|
22
|
+
.sort();
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function readEvents(dir, fs = fsDefault) {
|
|
26
|
+
const segments = listSegments(dir, fs);
|
|
27
|
+
const events = [];
|
|
28
|
+
for (const name of segments) {
|
|
29
|
+
const text = fs.readFileSync(pathDefault.join(dir, name), 'utf8');
|
|
30
|
+
for (const line of text.split('\n')) {
|
|
31
|
+
if (line.trim() === '') continue;
|
|
32
|
+
events.push(JSON.parse(line));
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
return { segments, events };
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function bytesOf(dir, segments, fs = fsDefault) {
|
|
39
|
+
let total = 0;
|
|
40
|
+
for (const name of segments) {
|
|
41
|
+
total += fs.statSync(pathDefault.join(dir, name)).size;
|
|
42
|
+
}
|
|
43
|
+
return total;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** 独立校验:读全部事件 → verifyChain(不加锁、不写盘、不 require 宿主)。 */
|
|
47
|
+
export function auditLedger(dir, options = {}) {
|
|
48
|
+
const fs = options.fs ?? fsDefault;
|
|
49
|
+
const { segments, events } = readEvents(dir, fs);
|
|
50
|
+
const projectId = events[0]?.projectId ?? null;
|
|
51
|
+
const chain = verifyChain(events, { projectId });
|
|
52
|
+
return {
|
|
53
|
+
ok: chain.ok,
|
|
54
|
+
dir,
|
|
55
|
+
projectId,
|
|
56
|
+
segments,
|
|
57
|
+
eventCount: events.length,
|
|
58
|
+
head: events.length > 0 ? { seq: events.at(-1).seq, hash: events.at(-1).hash, at: events.at(-1).at } : null,
|
|
59
|
+
error: chain.ok ? null : { code: chain.code, message: chain.message, details: chain.details ?? {}, index: chain.index ?? null },
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** 段/事件/字节/首尾时间统计。 */
|
|
64
|
+
export function statsLedger(dir, options = {}) {
|
|
65
|
+
const fs = options.fs ?? fsDefault;
|
|
66
|
+
const { segments, events } = readEvents(dir, fs);
|
|
67
|
+
const first = events[0] ?? null;
|
|
68
|
+
const last = events.at(-1) ?? null;
|
|
69
|
+
return {
|
|
70
|
+
dir,
|
|
71
|
+
segments: segments.length,
|
|
72
|
+
segmentBytes: segments.length > 0 ? bytesOf(dir, segments, fs) : 0,
|
|
73
|
+
eventCount: events.length,
|
|
74
|
+
firstAt: first?.at ?? null,
|
|
75
|
+
lastAt: last?.at ?? null,
|
|
76
|
+
headSeq: last?.seq ?? 0,
|
|
77
|
+
types: [...new Set(events.map((event) => event.type))].sort(),
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* 自包含导出:段文件副本(字节级复制,不重排不重写)+ manifest.json(head/
|
|
83
|
+
* 事件计数/文件清单/导出时间)+ verify-report.md(人读校验结论)。导出包
|
|
84
|
+
* 拷到任何机器都可以用 audit 独立复检。
|
|
85
|
+
*/
|
|
86
|
+
export function exportLedger(dir, outDir, options = {}) {
|
|
87
|
+
const fs = options.fs ?? fsDefault;
|
|
88
|
+
const path = options.path ?? pathDefault;
|
|
89
|
+
const audit = auditLedger(dir, { fs });
|
|
90
|
+
fs.mkdirSync(outDir, { recursive: true });
|
|
91
|
+
const copied = [];
|
|
92
|
+
for (const name of audit.segments) {
|
|
93
|
+
fs.copyFileSync(path.join(dir, name), path.join(outDir, name));
|
|
94
|
+
copied.push({ name, bytes: fs.statSync(path.join(outDir, name)).size });
|
|
95
|
+
}
|
|
96
|
+
const manifest = {
|
|
97
|
+
exportedAt: new Date().toISOString(),
|
|
98
|
+
sourceDir: dir,
|
|
99
|
+
projectId: audit.projectId,
|
|
100
|
+
head: audit.head,
|
|
101
|
+
eventCount: audit.eventCount,
|
|
102
|
+
files: copied,
|
|
103
|
+
verify: { ok: audit.ok, error: audit.error },
|
|
104
|
+
};
|
|
105
|
+
fs.writeFileSync(path.join(outDir, 'manifest.json'), JSON.stringify(manifest, null, 2) + '\n', 'utf8');
|
|
106
|
+
const lines = [
|
|
107
|
+
'# Ledger export verify report', '',
|
|
108
|
+
'- source: `' + dir + '`',
|
|
109
|
+
'- projectId: `' + String(audit.projectId) + '`',
|
|
110
|
+
'- events: ' + String(audit.eventCount),
|
|
111
|
+
'- head: seq ' + String(audit.head?.seq ?? 0),
|
|
112
|
+
'- hash chain: ' + (audit.ok ? '**OK**' : '**BROKEN**'),
|
|
113
|
+
audit.error ? '- error: ' + audit.error.code + ' ' + audit.error.message : '- error: none',
|
|
114
|
+
'- exportedAt: ' + manifest.exportedAt,
|
|
115
|
+
];
|
|
116
|
+
fs.writeFileSync(path.join(outDir, 'verify-report.md'), lines.join('\n') + '\n', 'utf8');
|
|
117
|
+
return { ok: audit.ok, outDir, files: copied.map((file) => file.name).concat(['manifest.json', 'verify-report.md']) };
|
|
118
|
+
}
|
package/lib/ledger/writer.js
CHANGED
|
@@ -29,7 +29,8 @@ import {
|
|
|
29
29
|
verifyChain,
|
|
30
30
|
verifyEvent,
|
|
31
31
|
} from './events.js';
|
|
32
|
-
import { applyEvent, fold, initialState } from './fold.js';
|
|
32
|
+
import { applyEvent, FOLD_STATE_VERSION, fold, initialState } from './fold.js';
|
|
33
|
+
import { loadCheckpoint, saveCheckpoint } from './checkpoint.js';
|
|
33
34
|
|
|
34
35
|
export { LedgerError };
|
|
35
36
|
|
|
@@ -403,7 +404,10 @@ export class LedgerWriter {
|
|
|
403
404
|
if (this._closed) throw new LedgerError('E_LEDGER_CLOSED', 'ledger is closed');
|
|
404
405
|
|
|
405
406
|
const plans = [];
|
|
406
|
-
|
|
407
|
+
// 批内查重只用临时小集合;全局查重直接查 _ids(O(1)),避免每次
|
|
408
|
+
// append 全量拷贝已存事件集合带来的平方级开销。
|
|
409
|
+
const seenIds = new Set();
|
|
410
|
+
const hasId = (id) => seenIds.has(id) || this._ids.has(id);
|
|
407
411
|
let seq = this._head.seq;
|
|
408
412
|
let prevHash = this._head.hash;
|
|
409
413
|
|
|
@@ -431,7 +435,7 @@ export class LedgerWriter {
|
|
|
431
435
|
|
|
432
436
|
const at = draft.at ?? this._clock();
|
|
433
437
|
const id = draft.id ?? newEventId(at);
|
|
434
|
-
if (
|
|
438
|
+
if (hasId(id)) {
|
|
435
439
|
throw new LedgerError('E_DUPLICATE_ID', 'event id already exists in this ledger', { id });
|
|
436
440
|
}
|
|
437
441
|
seenIds.add(id);
|
|
@@ -488,7 +492,13 @@ export class LedgerWriter {
|
|
|
488
492
|
(segCount > 0 &&
|
|
489
493
|
(segCount >= this.segmentEvents || segSize + plan.line.length > this.segmentBytes));
|
|
490
494
|
if (needRoll) {
|
|
491
|
-
if (segFd !== null)
|
|
495
|
+
if (segFd !== null) {
|
|
496
|
+
// 落盘后再关闭旧段:closeSync 不保证刷盘,若旧段尾部整行
|
|
497
|
+
// 只留在 OS 缓冲而崩溃丢失,新段首行的 prevHash/seq 将与
|
|
498
|
+
// 截断后的旧段尾对不上,哈希链断裂且无法修复。
|
|
499
|
+
if (this.fsync) this._fs.fsyncSync(segFd);
|
|
500
|
+
this._fs.closeSync(segFd);
|
|
501
|
+
}
|
|
492
502
|
// 段号 = 上一个已存在段的编号 + 1;全新账本的第一段仍是 000001。
|
|
493
503
|
const lastIndex =
|
|
494
504
|
created.length > 0
|
|
@@ -884,15 +894,91 @@ export class LedgerWriter {
|
|
|
884
894
|
export function openLedger(options = {}) {
|
|
885
895
|
const writer = new LedgerWriter(options);
|
|
886
896
|
const opened = writer.open();
|
|
887
|
-
|
|
888
|
-
|
|
897
|
+
// checkpoint 命中且账本与检查点齐平时,跳过全量 readAll(boot 的大头):
|
|
898
|
+
// state 直接取自检查点,events 惰性化(首次访问才读盘,append 只增新事件)。
|
|
899
|
+
// 尾部存在时才需要一次 readAll 来续放投影。
|
|
900
|
+
const checkpointOptions = options.checkpoint ?? null;
|
|
901
|
+
const checkpointDir = checkpointOptions?.dir ?? writer.dir;
|
|
902
|
+
const stateVersion = checkpointOptions?.stateVersion ?? FOLD_STATE_VERSION;
|
|
903
|
+
let state;
|
|
904
|
+
let recovery = null;
|
|
905
|
+
let events = null;
|
|
906
|
+
const ensureEvents = () => {
|
|
907
|
+
if (events === null) events = writer.readAll({ repairTail: false });
|
|
908
|
+
return events;
|
|
909
|
+
};
|
|
910
|
+
if (checkpointOptions) {
|
|
911
|
+
const loaded = loadCheckpoint(checkpointDir, {
|
|
912
|
+
stateVersion,
|
|
913
|
+
hashAt: (seq) => writer.hashAt(seq),
|
|
914
|
+
});
|
|
915
|
+
if (loaded.checkpoint && loaded.checkpoint.lastSeq === writer.head.seq) {
|
|
916
|
+
// 齐平:零尾放,账本事件列表不进内存。
|
|
917
|
+
state = loaded.checkpoint.state;
|
|
918
|
+
recovery = {
|
|
919
|
+
source: loaded.source,
|
|
920
|
+
fromSeq: loaded.checkpoint.lastSeq + 1,
|
|
921
|
+
tailReplayed: 0,
|
|
922
|
+
errors: loaded.errors,
|
|
923
|
+
};
|
|
924
|
+
} else {
|
|
925
|
+
const fromSeq = loaded.checkpoint ? loaded.checkpoint.lastSeq + 1 : 1;
|
|
926
|
+
state = loaded.checkpoint ? loaded.checkpoint.state : initialState();
|
|
927
|
+
const all = ensureEvents();
|
|
928
|
+
for (const event of all) {
|
|
929
|
+
if (event.seq >= fromSeq) Object.assign(state, applyEvent(state, event));
|
|
930
|
+
}
|
|
931
|
+
recovery = {
|
|
932
|
+
source: loaded.source ?? 'replay',
|
|
933
|
+
fromSeq,
|
|
934
|
+
tailReplayed: Math.max(0, writer.head.seq - fromSeq + 1),
|
|
935
|
+
errors: loaded.errors,
|
|
936
|
+
};
|
|
937
|
+
}
|
|
938
|
+
} else {
|
|
939
|
+
events = writer.readAll({ repairTail: false });
|
|
940
|
+
state = fold(events);
|
|
941
|
+
}
|
|
889
942
|
|
|
890
943
|
let onEvent = typeof options.onEvent === 'function' ? options.onEvent : null;
|
|
944
|
+
// 检查点节奏:boot 后落一次地板,之后每 saveEvery 次追加落一次,close
|
|
945
|
+
// 前必落——崩溃窗口最多丢 saveEvery 个事件的投影进度(账本本体无损)。
|
|
946
|
+
const saveEvery = Number.isSafeInteger(checkpointOptions?.saveEvery)
|
|
947
|
+
? Math.max(50, checkpointOptions.saveEvery)
|
|
948
|
+
: 500;
|
|
949
|
+
let eventsSinceCheckpoint = 0;
|
|
950
|
+
const saveCheckpointNow = () => {
|
|
951
|
+
if (!checkpointOptions) return null;
|
|
952
|
+
try {
|
|
953
|
+
// 水位取"fold 已应用前缀"而非 writer.head:跨调用交错下(B 批次可在
|
|
954
|
+
// A 的 facade 续体推进 state 之前提交),head 可能领先 state——按
|
|
955
|
+
// head 落盘会持久化一个 state 落后于 lastSeq 的检查点,崩溃重开时
|
|
956
|
+
// 零尾放静默吞掉投影。state.lastSeq/lastHash 由 advance() 逐事件
|
|
957
|
+
// 维护,永远 ≤ head,尾放从其 +1 重放天然自洽。
|
|
958
|
+
return saveCheckpoint(
|
|
959
|
+
checkpointDir,
|
|
960
|
+
{ stateVersion, lastSeq: state.lastSeq, lastHash: state.lastHash, state },
|
|
961
|
+
{ hashAt: (seq) => writer.hashAt(seq) },
|
|
962
|
+
);
|
|
963
|
+
} catch (error) {
|
|
964
|
+
// 检查点保存失败绝不影响追加,但必须可见:静默失败会让检查点
|
|
965
|
+
// 名存实亡(boot 退化为全量重放而无人知晓)。
|
|
966
|
+
console.warn(`[ai-team] ledger ${writer.projectId} checkpoint save failed:`, error?.message ?? error);
|
|
967
|
+
return { error: error.message ?? String(error) };
|
|
968
|
+
}
|
|
969
|
+
};
|
|
970
|
+
if (checkpointOptions) {
|
|
971
|
+
const saved = saveCheckpointNow();
|
|
972
|
+
recovery.saved = saved && !saved.error ? saved.path : (saved?.error ?? null);
|
|
973
|
+
}
|
|
891
974
|
const ledger = {
|
|
892
975
|
projectId: writer.projectId,
|
|
893
976
|
writer,
|
|
894
977
|
state,
|
|
895
|
-
|
|
978
|
+
/** 账本事件全列表(checkpoint 模式下惰性读盘,append 持续追加)。 */
|
|
979
|
+
get events() {
|
|
980
|
+
return ensureEvents();
|
|
981
|
+
},
|
|
896
982
|
opened,
|
|
897
983
|
get onEvent() {
|
|
898
984
|
return onEvent;
|
|
@@ -910,20 +996,28 @@ export function openLedger(options = {}) {
|
|
|
910
996
|
const event = await writer.append(draft);
|
|
911
997
|
// 只有 append 成功(含 fsync)后才推进内存状态。
|
|
912
998
|
Object.assign(state, applyEvent(state, event));
|
|
913
|
-
|
|
999
|
+
ensureEvents().push(event);
|
|
914
1000
|
try {
|
|
915
1001
|
onEvent?.(event);
|
|
916
1002
|
} catch {
|
|
917
1003
|
/* a projection listener must never break the append */
|
|
918
1004
|
}
|
|
1005
|
+
if (checkpointOptions) {
|
|
1006
|
+
eventsSinceCheckpoint += 1;
|
|
1007
|
+
if (eventsSinceCheckpoint >= saveEvery) {
|
|
1008
|
+
eventsSinceCheckpoint = 0;
|
|
1009
|
+
saveCheckpointNow();
|
|
1010
|
+
}
|
|
1011
|
+
}
|
|
919
1012
|
return event;
|
|
920
1013
|
},
|
|
921
1014
|
async appendMany(drafts) {
|
|
922
1015
|
const appended = await writer.appendMany(drafts);
|
|
923
1016
|
let next = state;
|
|
1017
|
+
const list = ensureEvents();
|
|
924
1018
|
for (const event of appended) {
|
|
925
1019
|
next = applyEvent(next, event);
|
|
926
|
-
|
|
1020
|
+
list.push(event);
|
|
927
1021
|
}
|
|
928
1022
|
Object.assign(state, next);
|
|
929
1023
|
for (const event of appended) {
|
|
@@ -933,8 +1027,19 @@ export function openLedger(options = {}) {
|
|
|
933
1027
|
/* a projection listener must never break the append */
|
|
934
1028
|
}
|
|
935
1029
|
}
|
|
1030
|
+
if (checkpointOptions) {
|
|
1031
|
+
eventsSinceCheckpoint += appended.length;
|
|
1032
|
+
if (eventsSinceCheckpoint >= saveEvery) {
|
|
1033
|
+
eventsSinceCheckpoint = 0;
|
|
1034
|
+
saveCheckpointNow();
|
|
1035
|
+
}
|
|
1036
|
+
}
|
|
936
1037
|
return appended;
|
|
937
1038
|
},
|
|
1039
|
+
/** boot 时检查点恢复方式:'primary'/'backup'/'replay' 与尾放区间。 */
|
|
1040
|
+
get recovery() {
|
|
1041
|
+
return recovery;
|
|
1042
|
+
},
|
|
938
1043
|
readAll(readOptions = {}) {
|
|
939
1044
|
return writer.readAll(readOptions);
|
|
940
1045
|
},
|
|
@@ -975,6 +1080,7 @@ export function openLedger(options = {}) {
|
|
|
975
1080
|
return writer.repair();
|
|
976
1081
|
},
|
|
977
1082
|
close() {
|
|
1083
|
+
if (checkpointOptions) saveCheckpointNow();
|
|
978
1084
|
writer.close();
|
|
979
1085
|
},
|
|
980
1086
|
};
|
|
@@ -1,10 +1,14 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* LLM failure classification and the deterministic retry/fallback decision.
|
|
3
3
|
*
|
|
4
|
-
* The
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
* a
|
|
4
|
+
* The listener on `agent/request-error` owns the retry for transient
|
|
5
|
+
* server/network failures and re-dispatches the same request immediately
|
|
6
|
+
* (DSH's agent loop supports that via `{ kind: 'retry' }`). There are no
|
|
7
|
+
* timers: a fallback patch only rewrites the member's persisted config, so it
|
|
8
|
+
* takes effect on the next wake — the current turn ends (`fail`). Rate limits
|
|
9
|
+
* also end the turn: hammering the same route at once burns the retry budget
|
|
10
|
+
* without a backoff clock. Auth/billing/policy failures are fail-closed and
|
|
11
|
+
* require a Human or the Project owner to change the environment.
|
|
8
12
|
*/
|
|
9
13
|
|
|
10
14
|
export const FAILURE_CATEGORY = Object.freeze({
|
|
@@ -80,18 +84,21 @@ function fallbackAt(config, index) {
|
|
|
80
84
|
}
|
|
81
85
|
|
|
82
86
|
/**
|
|
83
|
-
* Decide what the
|
|
84
|
-
*
|
|
87
|
+
* Decide what the request-error listener does next. `retry` re-dispatches the
|
|
88
|
+
* same request immediately; `fallback` writes the config patch and ends the
|
|
89
|
+
* turn (it can only take effect on the next wake, because a step's route is
|
|
90
|
+
* captured before dispatch); `fail` ends the turn unchanged.
|
|
85
91
|
*/
|
|
86
92
|
export function retryDecision(failure, config = {}, attempt = 1) {
|
|
87
93
|
const maxAttempts = Number.isSafeInteger(config.retry?.maxAttempts)
|
|
88
94
|
? Math.max(1, Math.min(config.retry.maxAttempts, 5))
|
|
89
95
|
: 3;
|
|
90
96
|
if (!failure?.retryable) return { action: 'fail', attempt, reason: `${failure?.category ?? 'unknown'} is not retryable` };
|
|
91
|
-
if (attempt >= maxAttempts) return { action: 'fail', attempt, reason: `retry budget exhausted (${maxAttempts})` };
|
|
92
97
|
const nextFallbackIndex = attempt - 1;
|
|
93
98
|
const fallback = fallbackAt(config, nextFallbackIndex);
|
|
94
99
|
if (fallback !== null) {
|
|
100
|
+
// 换路优先于预算:fallback 不是同路由重试,预算钳制它会让 maxAttempts=1
|
|
101
|
+
// 的配置永远走不到备用路由。
|
|
95
102
|
return {
|
|
96
103
|
action: 'fallback',
|
|
97
104
|
attempt,
|
|
@@ -105,7 +112,14 @@ export function retryDecision(failure, config = {}, attempt = 1) {
|
|
|
105
112
|
reason: `fallback to ${fallback.provider ?? config.provider}/${fallback.model ?? config.model}`,
|
|
106
113
|
};
|
|
107
114
|
}
|
|
108
|
-
return { action: '
|
|
115
|
+
if (attempt >= maxAttempts) return { action: 'fail', attempt, reason: `retry budget exhausted (${maxAttempts})` };
|
|
116
|
+
// No fallback route configured: a rate limit would hit again at once
|
|
117
|
+
// without a backoff clock — end the turn and let the next event/startup
|
|
118
|
+
// try fresh instead of burning the budget on a throttled route.
|
|
119
|
+
if (failure.category === FAILURE_CATEGORY.RATE_LIMIT) {
|
|
120
|
+
return { action: 'fail', attempt, reason: 'rate limited; left to the next wake' };
|
|
121
|
+
}
|
|
122
|
+
return { action: 'retry', attempt, reason: 'same route, immediate retry' };
|
|
109
123
|
}
|
|
110
124
|
|
|
111
125
|
export function describeFailure(failure) {
|
|
@@ -98,6 +98,9 @@ export class MemberRuntime {
|
|
|
98
98
|
this.preset = options.preset ?? null;
|
|
99
99
|
this.agentPresets = options.agentPresets ?? null;
|
|
100
100
|
this.direct = options.direct === true;
|
|
101
|
+
// Cold resumes produce AgentHandles the caller does not store; the owner
|
|
102
|
+
// tracks them here so teardown can dispose every member activation.
|
|
103
|
+
this.trackHandle = typeof options.trackHandle === 'function' ? options.trackHandle : null;
|
|
101
104
|
this.clock = options.clock ?? (() => Date.now());
|
|
102
105
|
}
|
|
103
106
|
|
|
@@ -241,6 +244,7 @@ export class MemberRuntime {
|
|
|
241
244
|
setup: async (agentCtx) => { await this.agentPresets.mount(agentCtx, preset); },
|
|
242
245
|
} : {}),
|
|
243
246
|
});
|
|
247
|
+
this.trackHandle?.(member.sessionId, handle);
|
|
244
248
|
agent = handle.agent;
|
|
245
249
|
} catch (error) {
|
|
246
250
|
fail('E_SESSION_MISSING', `member ${member.id} cannot be resumed: ${error?.message ?? error}`);
|
|
@@ -259,7 +263,8 @@ export class MemberRuntime {
|
|
|
259
263
|
// for a spawned subagent. Then the normal permission check applies.
|
|
260
264
|
if ((session === undefined || session === null) && this.agents?.resume !== undefined) {
|
|
261
265
|
try {
|
|
262
|
-
await this.agents.resume({ resumeSessionId: member.sessionId, parentAgent: this.parent });
|
|
266
|
+
const handle = await this.agents.resume({ resumeSessionId: member.sessionId, parentAgent: this.parent });
|
|
267
|
+
this.trackHandle?.(member.sessionId, handle);
|
|
263
268
|
session = this.sessions?.get?.(member.sessionId);
|
|
264
269
|
} catch { /* fall through to sendMessage cold path */ }
|
|
265
270
|
}
|