@sleep2agi/commhub-server 0.9.0-preview.219 → 0.9.0-preview.220
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/package.json +1 -1
- package/src/agent-acl-slice3-http.test.ts +388 -1
- package/src/config-apply-validate.test.ts +68 -0
- package/src/config-apply-validate.ts +69 -0
- package/src/cors-origins.test.ts +40 -0
- package/src/create-node-network-id.test.ts +12 -0
- package/src/department-heads-http.test.ts +20 -0
- package/src/departments-agent-count.test.ts +3 -0
- package/src/etag-of.test.ts +57 -0
- package/src/event-loop-lag.ts +20 -0
- package/src/health-anon-readers.ts +59 -0
- package/src/health-host-disk-2756.test.ts +23 -1
- package/src/health-redaction.test.ts +1063 -0
- package/src/hub-catalog-read-http.test.ts +79 -0
- package/src/hub-provider-config.test.ts +17 -0
- package/src/hub-provider-config.ts +19 -0
- package/src/license-state.test.ts +56 -0
- package/src/license-state.ts +48 -0
- package/src/list-host-supervisors.test.ts +10 -0
- package/src/mcp-projects-events-http.test.ts +3 -0
- package/src/mcp-write-network-resolution.test.ts +3 -0
- package/src/node-caller-identity-http.test.ts +9 -1
- package/src/node-health-dispatch-http.test.ts +58 -2
- package/src/node-health-guard.ts +16 -0
- package/src/node-skills-transport.test.ts +3 -0
- package/src/opencode-v2-catalog.ts +4 -0
- package/src/redact-tokens.test.ts +22 -1
- package/src/redact-tokens.ts +4 -1
- package/src/rejection-counters.test.ts +72 -0
- package/src/rejection-counters.ts +173 -0
- package/src/requirement-events-http.test.ts +27 -0
- package/src/route-callers-http.test.ts +1 -1
- package/src/serve-error.test.ts +35 -0
- package/src/serve-error.ts +33 -4
- package/src/server.ts +913 -17
- package/src/shared/probe-host-allowlist-drift.test.ts +45 -0
- package/src/skillhub-http.test.ts +35 -1
- package/src/status-read-cache.ts +8 -1
- package/src/task-late-reply-http.test.ts +7 -0
- package/src/task-rejection-log.ts +10 -1
- package/src/tmux-allowlist.test.ts +48 -0
- package/src/tool-audience.ts +10 -3
- package/src/tools.ts +99 -15
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
// 2026-10-31 —— 拒绝原因不止要有日志,还要有**计数**。
|
|
2
|
+
//
|
|
3
|
+
// 背景:同一条路由的失败可以有很多原因(TM 侧那条是 401/400/403 三种「1 键」出口),
|
|
4
|
+
// 而日志只回答「有没有发生过」:要回答「今天拒了多少次、分别为什么」,
|
|
5
|
+
// 得去翻文件、还要考虑轮转与压缩 —— 而轮转后的 .gz 用 grep 读是**静默 0**。
|
|
6
|
+
//
|
|
7
|
+
// ⇒ **日志是事后取证,计数器是随时可读。**
|
|
8
|
+
//
|
|
9
|
+
// 🔴 三条设计约束(每条都对应一个我们已经踩过的坑):
|
|
10
|
+
// ① **按 reason 分桶,不是只有一个总数。**
|
|
11
|
+
// 一个总数会数出频率、看不出原因 —— 而「为什么」才是排查要的东西。
|
|
12
|
+
// ② **窗口必须显式给出。** 计数器随进程重启归零,
|
|
13
|
+
// 而「归零」与「没有发生」在读数上同值 ⇒ 必须与 startedAt 一起读。
|
|
14
|
+
// (历史教训:拿累计值除以 uptime 当速率 ⇒ 分母与分子不独立 ⇒ 刚重启必假阳性。)
|
|
15
|
+
// ③ **键必须有限且可枚举。** reason 由 (status, code) 组成,两者都来自
|
|
16
|
+
// 我们自己的出口 ⇒ 不会随请求内容膨胀(不做「按 URL 分桶」那种事)。
|
|
17
|
+
//
|
|
18
|
+
// 🔴 这一类的第四问(2026-10-31 补):**它在正常运行时会不会动?**
|
|
19
|
+
// 本模块的计数器属于「只有异常路径能让它 +1」那一类 ⇒ 正常运行时恒为 0,
|
|
20
|
+
// 而「0」读起来像「从没出过错」。它与「死计数器」在读数上完全一样,
|
|
21
|
+
// 但处置相反:死计数器该删,这一种**必须配一个 must-fire**(注入一次真实拒绝,看它跳不跳)。
|
|
22
|
+
// ⇒ 光有 by_reason 的形状断言不够:形状对、接线错,读数照样是 0。
|
|
23
|
+
// ⇒ 已有一处 must-fire:health-redaction.test.ts 里真实 POST /api/task 触发非 2xx 后读 /health。
|
|
24
|
+
//
|
|
25
|
+
// 🔴 已知缺口 —— 写成**可数清单**,而不是一句“可能不全”(2026-10-31 实测)。
|
|
26
|
+
//
|
|
27
|
+
// 🔑 行键是 **位置**(谁在那里拒绝),不是「失败种类」。
|
|
28
|
+
// 理由:同一类失败会随实现搬家 —— `express.json()` 把 parser 放在中间件里 ⇒ 不计;
|
|
29
|
+
// 我们把 `await req.json()` 放在 handler 里 ⇒ 计。
|
|
30
|
+
// **失败种类会漂,位置不会。** 分类键要选「不因重构而改变」的那个维度。
|
|
31
|
+
//
|
|
32
|
+
// 位置 是否计数 失败种类(只作说明)
|
|
33
|
+
// ────────────────────────────────────────────────────────────────────────────
|
|
34
|
+
// 鉴权中间件之前 ✗ 401 在到达 /api/task 之前返回
|
|
35
|
+
// 路由表之前 ✗ 全局/路由 404(未匹配)
|
|
36
|
+
// fetch() 之前(运行时层) ✗ Bun maxRequestBodySize(请求体超限)
|
|
37
|
+
// handler 内 · 解析 ✓ await req.json() 失败(本仓如此;Express 恰好相反)
|
|
38
|
+
// handler 内 · 校验/权限 ✓ schema / 网络归属 等非 2xx
|
|
39
|
+
// 错误 hook(500 兜底) ✗ buildServeErrorResponse
|
|
40
|
+
//
|
|
41
|
+
// ⇒ **位置仪器化 2/6;但链路覆盖 = 0/6。**
|
|
42
|
+
//
|
|
43
|
+
// 🔴 「2/6」这个写法本身是错的(2026-10-31 修正):
|
|
44
|
+
// 从上表可知被仪器化的是第 4、5 个位置 —— **不是前缀**。
|
|
45
|
+
// 而「要到达第 k 个位置,必须先经过前 k-1 个」⇒
|
|
46
|
+
// 一条能被判读的「链路覆盖」只能是 prefix(k);
|
|
47
|
+
// 非前缀的覆盖数会**暗示测试绕过链路**,而不是测了链路。
|
|
48
|
+
// ⇒ 所以按「首个未被观测的位置」算:**#1(鉴权中间件之前)就是那个洞 ⇒ 链覆盖 0/6**。
|
|
49
|
+
// ⇒ 2/6 只能念成「有 2 个点装了表」,不能念成「链路有三分之一被覆盖」。
|
|
50
|
+
// ⇒ 判据:**覆盖数必须是前缀**;非前缀时,报告要写「首个空洞在哪」,否则它是个自相矛盾的读数。
|
|
51
|
+
// ⇒ 清单要能被一次坏输入打出来,而不是靠回想中间件有哪些:
|
|
52
|
+
// `curl -X POST /api/task -H 'content-type: application/json' -d '{bad'` ⇒ 400,
|
|
53
|
+
// 看计数器动不动 ⇒ 动 ⇒ 这个位置被覆盖(本仓就是动的,见 health-redaction.test.ts)。
|
|
54
|
+
// ⇒ 为什么必须写分母:一个有分母的缺口是可排期的;一个没有分母的缺口只会被当成注释。
|
|
55
|
+
// ⇒ 补齐路径:把 +1 上移到中间件(401/404)或统一错误兜底(500),本次不做。
|
|
56
|
+
//
|
|
57
|
+
// 🔴 而下面的流程顺序也来自同一个教训:
|
|
58
|
+
// ① 先写「怎么让它 +1」的具体注入(命令或测试)
|
|
59
|
+
// ② 写不出 ⇒ **停下来先补出口** —— 此时暴露的往往是产品缺陷,不是测试缺陷
|
|
60
|
+
// ③ 写得出 ⇒ 再写断言
|
|
61
|
+
// ⇒ 形状断言写得再漂亮,也不要求「它能响」;而「能不能响」才是判据的入场券。
|
|
62
|
+
//
|
|
63
|
+
// 🔴 2026-10-31 补:窗口不能只给时长,要给**两个时刻**。
|
|
64
|
+
// 读者拿 counters.since(起点)与 /health.served_at(终点)相减才是窗口;
|
|
65
|
+
// 「我打算等 60 秒」是意图,不是读数 —— 而意图与读数在字段里同形。
|
|
66
|
+
// ⇒ 判据:速率/窗口类字段,分子分母各要自己的时刻戳;**被声明的那个永远不算**。
|
|
67
|
+
//
|
|
68
|
+
// 字段注释的三行格式(本模块的对外承诺):
|
|
69
|
+
// 由拒绝日志同一位置 +1;不由读它的人 +1;**只有非 2xx 的 /api/task 才会让它 >0**。
|
|
70
|
+
//
|
|
71
|
+
// 为什么不做成 Prometheus 指标:本仓没有指标管道,而 /health 已经是
|
|
72
|
+
// 「随手可读」的那个面。放这里能被 agent-node、dashboard、人都读到。
|
|
73
|
+
|
|
74
|
+
const REJECTION_COUNTS = new Map<string, number>();
|
|
75
|
+
|
|
76
|
+
/** 桶键:`<status>:<code>`。code 缺失时用 `unknown`,绝不省略 —— 省略会让两种原因并桶。 */
|
|
77
|
+
function bucketKey(status: number, code: unknown): string {
|
|
78
|
+
const raw = typeof code === "string" && code ? code : "unknown";
|
|
79
|
+
// 只保留可打印的短标识,防客户端塞长串把键空间撑爆。
|
|
80
|
+
const safe = raw.replace(/[^\w.:-]+/g, "_").slice(0, 48) || "unknown";
|
|
81
|
+
return `${status}:${safe}`;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** 记一次拒绝。调用点:logTaskRejection —— 与那一行日志同一个位置,不会漏记。 */
|
|
85
|
+
export function recordTaskRejection(status: number, code: unknown): void {
|
|
86
|
+
const key = bucketKey(status, code);
|
|
87
|
+
REJECTION_COUNTS.set(key, (REJECTION_COUNTS.get(key) ?? 0) + 1);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* 快照。**只读、已排序、键有限**:
|
|
92
|
+
* - 排序是为了让两次读数可比(无序 Map 会让「同一个计数器」看起来在变)
|
|
93
|
+
* - 上限 64 个桶,超出的合并进 `other` —— 计数器的价值在「为什么」,不在「穷举」
|
|
94
|
+
*/
|
|
95
|
+
/**
|
|
96
|
+
* 2026-10-31 —— 加一个 `scope` 字段:让「这个数是进程生命期内的」无法被误读。
|
|
97
|
+
*
|
|
98
|
+
* null 有三个成因,而只有前两个被写进过文档:
|
|
99
|
+
* ① 真的没发生
|
|
100
|
+
* ② 记录随进程没了(进程内计数器)
|
|
101
|
+
* ③ **记录还在日志里,只是不在这个窗口里**
|
|
102
|
+
* ⇒ 第三种最常见,而它与「没发生」在读数上同值。
|
|
103
|
+
* ⇒ 与其在注释里提醒,不如让数据自己说明:`scope: "process_lifetime"`。
|
|
104
|
+
*/
|
|
105
|
+
export function taskRejectionCounters(): {
|
|
106
|
+
scope: "process_lifetime";
|
|
107
|
+
total: number;
|
|
108
|
+
by_reason: Record<string, number>;
|
|
109
|
+
} {
|
|
110
|
+
let total = 0;
|
|
111
|
+
const entries = [...REJECTION_COUNTS.entries()].sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0));
|
|
112
|
+
const byReason: Record<string, number> = {};
|
|
113
|
+
let other = 0;
|
|
114
|
+
for (const [key, count] of entries) {
|
|
115
|
+
total += count;
|
|
116
|
+
if (Object.keys(byReason).length < 64) byReason[key] = count;
|
|
117
|
+
else other += count;
|
|
118
|
+
}
|
|
119
|
+
if (other > 0) byReason.other = other;
|
|
120
|
+
// ⚠️ `scope` 说的是**这个计数的生命期**,不是证据的生命期:
|
|
121
|
+
// 进程没了 ⇒ 这里归零;但对应日志行仍在磁盘上 ⇒
|
|
122
|
+
// 「计数器为 0 且日志里有拒绝」是正常的,不是矛盾。
|
|
123
|
+
return { scope: "process_lifetime", total, by_reason: byReason };
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** 测试用:清空。生产路径不调用。 */
|
|
127
|
+
export function resetTaskRejectionCounters(): void {
|
|
128
|
+
REJECTION_COUNTS.clear();
|
|
129
|
+
}/**
|
|
130
|
+
* 2026-10-31 —— 出口清单**导出成数据**(外部复核 ②:「那张表的分母本身需要一个来源」)。
|
|
131
|
+
*
|
|
132
|
+
* 以前这六行只活在注释里:加一个中间件时,注释不会自己变,而「覆盖 2/6」这个比例
|
|
133
|
+
* 也没人知道分母从哪来。⇒ 现在它是数据,测试会断言:
|
|
134
|
+
* · 行数恰好 6(有变化就必须改测试,而不是让注释漂)
|
|
135
|
+
* · 每个 `counted: true` 的位置都有 must-fire 用例覆盖
|
|
136
|
+
* · 每个 `counted: false` 的位置都有「已知缺口」用例钉住(防止它悄悄被修好而报告仍写 0/6)
|
|
137
|
+
*/
|
|
138
|
+
export const TASK_REJECTION_EXITS: ReadonlyArray<{
|
|
139
|
+
/** 位置(谁在那里拒绝)——分类键选位置,不选失败种类(种类会漂,位置不会) */
|
|
140
|
+
position: string;
|
|
141
|
+
/** 这个位置拒绝时,task_rejections 计数器会不会 +1 */
|
|
142
|
+
counted: boolean;
|
|
143
|
+
/** 钉住这一行的测试名(空串 = 还没有测试,属于缺口) */
|
|
144
|
+
pinned_by: string;
|
|
145
|
+
/**
|
|
146
|
+
* 当 `pinned_by` 是空串时,**必须**说明为什么钉不住、以及什么能让它被钉住。
|
|
147
|
+
*
|
|
148
|
+
* 2026-10-31 —— 外部复核 (b) 那条的直接应用:
|
|
149
|
+
* 「兜底值必须说出自己是兜底」(`failure_reason_source: none` / `artifact_errors_source: empty`)。
|
|
150
|
+
* 本表同款:空的 `pinned_by` 与「忘了填」在数据里长得一样 ——
|
|
151
|
+
* 而填一个 gap_reason 之后,「我们知道这是洞」与「我们没看见这个洞」就分开了。
|
|
152
|
+
*
|
|
153
|
+
* 反例守卫:`pinned_by` 与 `gap_reason` **恰好填一个**(两个都填 = 自相矛盾;都不填 = 又回到静默缺口)。
|
|
154
|
+
*/
|
|
155
|
+
gap_reason?: string;
|
|
156
|
+
}> = [
|
|
157
|
+
{ position: "before_auth_middleware", counted: false, pinned_by: "KNOWN GAP: unauthenticated /api/task rejection is NOT counted" },
|
|
158
|
+
{ position: "before_route_table", counted: false, pinned_by: "KNOWN GAP: unmatched /api/* route 404 is NOT counted" },
|
|
159
|
+
{ position: "before_fetch_runtime_body_limit", counted: false, pinned_by: "KNOWN GAP: body over runtime maxRequestBodySize is NOT counted" },
|
|
160
|
+
{ position: "handler_parse", counted: true, pinned_by: "malformed JSON on /api/task IS counted" },
|
|
161
|
+
{ position: "handler_validate_or_permission", counted: true, pinned_by: "a real rejected /api/task actually bumps the counter" },
|
|
162
|
+
{
|
|
163
|
+
position: "error_hook_500",
|
|
164
|
+
counted: false,
|
|
165
|
+
pinned_by: "",
|
|
166
|
+
gap_reason:
|
|
167
|
+
"未捕获异常 → 500 的出口目前没有夹具:要钉它必须能**按需诱发**一次未捕获异常," +
|
|
168
|
+
"而本仓没有测试专用路由(也不打算为测试在路由表里开洞)。" +
|
|
169
|
+
"解锁条件:出现一个可被合法输入诱发、且不依赖测试钩子的异常路径,或在测试里单独起一个只注册 error hook 的最小 server。",
|
|
170
|
+
},
|
|
171
|
+
];
|
|
172
|
+
|
|
173
|
+
|
|
@@ -146,6 +146,33 @@ describe("requirement events", () => {
|
|
|
146
146
|
expect(JSON.stringify(later[2])).not.toContain("一段描述");
|
|
147
147
|
});
|
|
148
148
|
|
|
149
|
+
// 2026-10-31 —— **变化字段集合 == 实际被写库的字段集合**(外部复核那条的对账形态)。
|
|
150
|
+
// 上一节断言的是「事件字段集合」;这里把它与「读回来的行真的变了哪些字段」逐项比对 ——
|
|
151
|
+
// 只有两边相等,才能说「流水没有漏记,也没有凭空多记」。
|
|
152
|
+
test("changed-field set equals the set of columns that actually changed in the stored row", async () => {
|
|
153
|
+
const card = await create(admin.token, { name: "对账示例", priority: "normal" });
|
|
154
|
+
const read = async () => (await send(admin.token, "GET", `/api/requirements/${card.id}?network_id=${NET}`)).body.requirement;
|
|
155
|
+
const before = await read();
|
|
156
|
+
// 2026-10-31 —— **同一个 PATCH 里混一个「赋相同值」的字段**(外部复核 (a) 的原话:
|
|
157
|
+
// 「同一次 update 里加一个赋相同值的字段,断言它不在 changes 里」)。
|
|
158
|
+
// 这是「变化集 vs 赋值集」两种实现唯一分叉的输入形态:
|
|
159
|
+
// 只测「整单都是空操作」时,两种实现都绿;混一个不变字段,只有按值比较的那种才绿。
|
|
160
|
+
const r = await patch(member.token, card.id, { column: "doing", priority: "high", due: "2026-10-09", assignee: "" });
|
|
161
|
+
expect(r.status).toBe(200);
|
|
162
|
+
const after = await read();
|
|
163
|
+
// 只看这次 PATCH 涉及的四个字段(三个改了、一个赋的是原值):读回来的行里**真的不同**的那些
|
|
164
|
+
const keys = ["column", "priority", "due", "assignee"] as const;
|
|
165
|
+
const actuallyChanged = keys.filter((k) => JSON.stringify(before[k] ?? null) !== JSON.stringify(after[k] ?? null)).sort();
|
|
166
|
+
const eventFields = of((await events(admin.token)).body.events, card.id)
|
|
167
|
+
.filter((e: any) => e.kind === "changed")
|
|
168
|
+
.map((e: any) => e.field).sort();
|
|
169
|
+
expect(eventFields).toEqual(actuallyChanged);
|
|
170
|
+
expect(actuallyChanged).toEqual(["column", "due", "priority"]);
|
|
171
|
+
// 赋相同值的那个字段:既不在实际变化里,也不在流水里(否则「赋值集」实现会多记一条)
|
|
172
|
+
expect(actuallyChanged).not.toContain("assignee");
|
|
173
|
+
expect(eventFields).not.toContain("assignee");
|
|
174
|
+
});
|
|
175
|
+
|
|
149
176
|
test("checklist: ticking an item is `checklist_item` (repeat is a no-op); adding items is `checklist`", async () => {
|
|
150
177
|
const card = await create(admin.token, { name: "动态示例三", checklist: [{ id: "a", text: "第一项" }, { id: "b", text: "第二项" }] });
|
|
151
178
|
const tick = (done: boolean) => send(member.token, "PATCH", `/api/requirements/${card.id}/checklist/a?network_id=${NET}`, { done });
|
|
@@ -71,7 +71,7 @@ describe("GET /api/stats/routes?by=caller", () => {
|
|
|
71
71
|
const res = await get("/api/stats/routes?minutes=5", auth(admin));
|
|
72
72
|
expect(await res.text()).toBe(expected);
|
|
73
73
|
const body = JSON.parse(expected);
|
|
74
|
-
expect(Object.keys(body)).toEqual(["ok", "
|
|
74
|
+
expect(Object.keys(body).sort()).toEqual(["ok", "oldest_at", "routes", "samples", "window_ms"]);
|
|
75
75
|
for (const r of body.routes) expect(Object.keys(r)).toEqual(["route", "count", "total_ms", "avg_ms", "p95_ms", "max_ms", "bytes", "errors"]);
|
|
76
76
|
});
|
|
77
77
|
|
package/src/serve-error.test.ts
CHANGED
|
@@ -35,4 +35,39 @@ describe("#695 fetch exceptions become JSON with the exception's own message", (
|
|
|
35
35
|
}
|
|
36
36
|
});
|
|
37
37
|
|
|
38
|
+
// 2026-10-31 —— join 的**前提**:一个错误要能被念回来,且念回的那个 id 必须真的进日志。
|
|
39
|
+
// 只说「加了 id」不算:三者(body / header / log)不一致时,念回 id 反而更糟 ——
|
|
40
|
+
// 它会让人以为服务端有记录。
|
|
41
|
+
// 我自己刚加了 error_id ⇒ 按本仓的「键集纪律」,这次加字段也必须是一次**有意识的**改动。
|
|
42
|
+
// 不加这条的话,下次再有人往这个 body 里加东西,没有任何测试会因此变红。
|
|
43
|
+
test("the error body's key set is pinned (adding a field here is a contract change)", () => {
|
|
44
|
+
expect(Object.keys(serveErrorBody(new Error("x"))).sort()).toEqual(
|
|
45
|
+
["error", "error_id", "id", "jsonrpc", "message", "ok"],
|
|
46
|
+
);
|
|
47
|
+
expect(Object.keys(serveErrorBody(new Error("x")).error).sort()).toEqual(["code", "message"]);
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
describe("error_id: the join key must exist in all three places, identically", () => {
|
|
51
|
+
test("body.error_id === x-error-id === the logged id", async () => {
|
|
52
|
+
const logged: string[] = [];
|
|
53
|
+
const res = buildServeErrorResponse(new Error("boom-join"), (l) => logged.push(l));
|
|
54
|
+
const body = await res.json() as any;
|
|
55
|
+
expect(typeof body.error_id).toBe("string");
|
|
56
|
+
// ⚠️ 2026-10-31 —— 这条 `header === body.error_id` 的判别力有限:
|
|
57
|
+
// header 与 body 由**同一个变量**序列化 ⇒ 它结构上恒真(改成任何实现都成立)。
|
|
58
|
+
// 真正的独立证据在下面两条:日志行里的 id 与之相同(另一个生产者),
|
|
59
|
+
// 以及「每次失败 id 不同」(常量会失败)。
|
|
60
|
+
expect(body.error_id).toMatch(/^[0-9a-f]{8}$/);
|
|
61
|
+
expect(res.headers.get("x-error-id")).toBe(body.error_id);
|
|
62
|
+
// 分母:日志必须真的有一条,且里面就是那个 id
|
|
63
|
+
expect(logged.length).toBe(1);
|
|
64
|
+
expect(logged[0]).toContain(`id=${body.error_id}`);
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
test("ids differ per failure (a constant id would join every incident to one line)", () => {
|
|
68
|
+
const a = serveErrorBody(new Error("a"));
|
|
69
|
+
const b = serveErrorBody(new Error("b"));
|
|
70
|
+
expect(a.error_id).not.toBe(b.error_id);
|
|
71
|
+
});
|
|
72
|
+
});
|
|
38
73
|
});
|
package/src/serve-error.ts
CHANGED
|
@@ -10,18 +10,47 @@ export interface ServeErrorBody {
|
|
|
10
10
|
error: { code: -32603; message: string };
|
|
11
11
|
ok: false;
|
|
12
12
|
message: string;
|
|
13
|
+
/**
|
|
14
|
+
* 2026-10-31 —— **join 的前提是这条日志真的写下来了。**
|
|
15
|
+
*
|
|
16
|
+
* 生产者(我们)给一个短 id,写进 body + 响应头 + 服务端日志;
|
|
17
|
+
* 消费者(用户/另一个 agent)只需要把它念回来。
|
|
18
|
+
*
|
|
19
|
+
* 没有它的时候,「用户报了一个 500」与「日志里那一行」之间只能靠
|
|
20
|
+
* 时间 ± 猜测去 join —— 而时间戳在跨时区/日志滚动后不可用。
|
|
21
|
+
* (反面教材:某系统的 400 出口既不写 sink 也不发 diagnostic id,
|
|
22
|
+
* 于是那个失败在结构上就是**无法 join** 的,只能靠客户端自采集。)
|
|
23
|
+
*
|
|
24
|
+
* ⇒ 判据:**一个错误如果要求人去排查,它必须自带一个能被念回来的 id,
|
|
25
|
+
* 且这个 id 必须真的出现在日志里**(两件事缺一,join 就不成立)。
|
|
26
|
+
*/
|
|
27
|
+
error_id: string;
|
|
13
28
|
}
|
|
14
29
|
|
|
15
|
-
|
|
30
|
+
/** 短、可念、低碰撞:8 个十六进制字符(32 bit)。它**不是**安全边界,只是关联键。 */
|
|
31
|
+
function newErrorId(): string {
|
|
32
|
+
return Math.floor(Math.random() * 0xffffffff).toString(16).padStart(8, "0");
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function serveErrorBody(err: unknown, errorId: string = newErrorId()): ServeErrorBody {
|
|
16
36
|
const raw = err instanceof Error ? err.message : String(err);
|
|
17
37
|
const message = (raw && raw.trim()) ? raw.trim().slice(0, 500) : "internal error";
|
|
18
|
-
return { jsonrpc: "2.0", id: null, error: { code: -32603, message }, ok: false, message };
|
|
38
|
+
return { jsonrpc: "2.0", id: null, error: { code: -32603, message }, ok: false, message, error_id: errorId };
|
|
19
39
|
}
|
|
20
40
|
|
|
21
|
-
|
|
41
|
+
/**
|
|
42
|
+
* 日志一行、body 一份、响应头一份 —— **同一个 id**。
|
|
43
|
+
* 三者不一致时,「念回 id」就 join 不上,而那比没有 id 更糟(它会让人以为有记录)。
|
|
44
|
+
*/
|
|
45
|
+
export function buildServeErrorResponse(err: unknown, log: (line: string) => void = console.error): Response {
|
|
22
46
|
const body = serveErrorBody(err);
|
|
47
|
+
log(`[serve-error] id=${body.error_id} ${body.message}`);
|
|
23
48
|
return new Response(JSON.stringify(body), {
|
|
24
49
|
status: 500,
|
|
25
|
-
headers: {
|
|
50
|
+
headers: {
|
|
51
|
+
"content-type": "application/json; charset=utf-8",
|
|
52
|
+
"cache-control": "no-store",
|
|
53
|
+
"x-error-id": body.error_id,
|
|
54
|
+
},
|
|
26
55
|
});
|
|
27
56
|
}
|