@sleep2agi/commhub-server 0.9.0-preview.281 → 0.9.0-preview.282
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/build-info.json +2 -2
- package/package.json +1 -1
- package/src/api-host-supervisors-source-capabilities.test.ts +107 -0
- package/src/auth_login_guard.test.ts +15 -0
- package/src/auth_login_guard.ts +20 -1
- package/src/board-grants.test.ts +134 -0
- package/src/broadcast-attribution.test.ts +93 -0
- package/src/build-commit-report-http.test.ts +10 -0
- package/src/clone-node-adopted-db.test.ts +78 -0
- package/src/clone-node.ts +5 -1
- package/src/create-node.ts +17 -0
- package/src/department-heads.ts +3 -0
- package/src/expiry-counters.test.ts +50 -1
- package/src/expiry-counters.ts +31 -9
- package/src/mcp-write-network-resolution.test.ts +36 -0
- package/src/node-config-last-update.test.ts +103 -1
- package/src/node-config-last-update.ts +70 -5
- package/src/node-daemon-bindings.ts +9 -0
- package/src/node-grants-http.test.ts +239 -0
- package/src/node-grants.ts +234 -0
- package/src/node-inbox-allowlist-http.test.ts +35 -0
- package/src/node-permissions.ts +37 -2
- package/src/opencode-v2-catalog.test.ts +22 -1
- package/src/opencode-v2-catalog.ts +36 -3
- package/src/peer-allowlist.test.ts +29 -0
- package/src/registration-switch-http.test.ts +60 -0
- package/src/reply-bare-infer-4315.test.ts +86 -0
- package/src/requirements.ts +29 -4
- package/src/schedule-agent.ts +45 -10
- package/src/scheduled-tasks-http.test.ts +25 -0
- package/src/scheduled-tasks.ts +46 -2
- package/src/server.ts +111 -6
- package/src/steer-send-message.test.ts +121 -0
- package/src/task-access.ts +21 -1
- package/src/tools.ts +76 -18
package/src/expiry-counters.ts
CHANGED
|
@@ -182,7 +182,15 @@ export function neverConsumeGate(input: {
|
|
|
182
182
|
persistent?: PersistentExpiryEvidence;
|
|
183
183
|
}): NeverConsumeGate {
|
|
184
184
|
const limit = input.limit ?? NEVER_CONSUME_LIMIT;
|
|
185
|
-
|
|
185
|
+
// 2026-11-13 —— **内存计数也要以「最后一次回复」为界**(与 DB 证据同一条判据)。
|
|
186
|
+
// 现场:TMA客户端欧 卡住期间攒了 ≥3 次内存过期,之后它恢复并正常回复了,DB 证据随即归零,
|
|
187
|
+
// 但内存桶只有 count + lastAt,没有回复边界 ⇒ 闸继续拒发直到 2 小时 TTL 或 Hub 重启。
|
|
188
|
+
// 有人为此重启了 Hub。回复本身就是「它活着」的证据:最后一次回复晚于内存里最近一次过期
|
|
189
|
+
// ⇒ 那些内存计数全部发生在恢复之前,不再算数。
|
|
190
|
+
const memLastAt = parseHubTime(input.counters.last_at?.[input.alias]);
|
|
191
|
+
const lastReplyAt = parseHubTime(input.persistent?.last_reply_at ?? undefined);
|
|
192
|
+
const memorySupersededByReply = memLastAt !== null && lastReplyAt !== null && lastReplyAt >= memLastAt;
|
|
193
|
+
const fromMemory = memorySupersededByReply ? 0 : (input.counters.by_node[input.alias] ?? 0);
|
|
186
194
|
const fromDb = input.persistent?.expiries ?? 0;
|
|
187
195
|
const expiries = Math.max(fromMemory, fromDb);
|
|
188
196
|
if (expiries < limit) return { ok: true };
|
|
@@ -199,19 +207,22 @@ export function neverConsumeGate(input: {
|
|
|
199
207
|
message:
|
|
200
208
|
`this target has ${fromDb} expired task(s) with no reply since its last reply`
|
|
201
209
|
+ `${input.persistent?.last_reply_at ? ` (${input.persistent.last_reply_at})` : " (it has never replied)"}; `
|
|
202
|
-
+ `nothing will queue correctly here until it replies again — pass force:true (user tokens) if you know it recovered
|
|
210
|
+
+ `nothing will queue correctly here until it replies again — pass force:true (user tokens) if you know it recovered, `
|
|
211
|
+
+ `or as a user token cancel the expired rows (cancel_task accepts expired for user tokens) to clear this gate`,
|
|
203
212
|
};
|
|
204
213
|
}
|
|
205
214
|
// 2026-10-31 —— **只数不衰减会把恢复了的节点永久拉黑**。
|
|
206
215
|
// 实测的教训来自另一台机(TM中转运维):连「抑制了多少」这个数本身都在被环缓冲淘汰,
|
|
207
216
|
// 所以任何「累计」都只在它的窗口内可引用;这里把窗口写进判据:最近一次过期超过 TTL ⇒ 放行。
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
.
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
217
|
+
// 两个来源的时间格式不同(内存是 ISO,tasks 表是 SQLite 的 "YYYY-MM-DD HH:MM:SS" UTC),
|
|
218
|
+
// 原来按字符串排序再 Date.parse —— 后者会把 SQLite 时间当成**本地时间**解析(Hub 机是 UTC+8)。
|
|
219
|
+
const lastAtMs = [input.counters.last_at?.[input.alias], input.persistent?.last_at ?? undefined]
|
|
220
|
+
.map(parseHubTime)
|
|
221
|
+
.filter((x): x is number => x !== null)
|
|
222
|
+
.reduce<number | null>((a, b) => (a === null || b > a ? b : a), null);
|
|
223
|
+
if (lastAtMs !== null) {
|
|
224
|
+
const age = (input.now ?? Date.now()) - lastAtMs;
|
|
225
|
+
if (age > (input.staleAfterMs ?? NEVER_CONSUME_STALE_MS)) return { ok: true };
|
|
215
226
|
}
|
|
216
227
|
if (input.force && input.forceAllowed) return { ok: true };
|
|
217
228
|
return {
|
|
@@ -225,3 +236,14 @@ export function neverConsumeGate(input: {
|
|
|
225
236
|
+ `nothing will queue correctly here until it consumes again — pass force:true (user tokens) if you know it recovered`,
|
|
226
237
|
};
|
|
227
238
|
}
|
|
239
|
+
|
|
240
|
+
/**
|
|
241
|
+
* 解析 Hub 里出现的两种时间:ISO(带 Z / 偏移)和 SQLite `datetime('now')` 的
|
|
242
|
+
* "YYYY-MM-DD HH:MM:SS"(UTC、无时区标记)。后者必须按 UTC 解析,不能交给 Date.parse 当本地时间。
|
|
243
|
+
*/
|
|
244
|
+
export function parseHubTime(v: string | null | undefined): number | null {
|
|
245
|
+
if (typeof v !== "string" || !v) return null;
|
|
246
|
+
const sqlite = /^(\d{4}-\d{2}-\d{2})[ T](\d{2}:\d{2}:\d{2}(?:\.\d+)?)$/.exec(v);
|
|
247
|
+
const ms = Date.parse(sqlite ? `${sqlite[1]}T${sqlite[2]}Z` : v);
|
|
248
|
+
return Number.isFinite(ms) ? ms : null;
|
|
249
|
+
}
|
|
@@ -448,3 +448,39 @@ describe("legacy global-token mode pinned", () => {
|
|
|
448
448
|
expect(inboxRow("x517 g5 legacy")?.network_id).toBeNull();
|
|
449
449
|
});
|
|
450
450
|
});
|
|
451
|
+
|
|
452
|
+
// ─────────────────────────────────────────────────────────────────────
|
|
453
|
+
// Group 9 — #4307: `expired` 行的清理权限
|
|
454
|
+
// target_never_consumes 的判据是「最后一次回复之后仍 status='expired' 且 result 为空」。
|
|
455
|
+
// 节点令牌不得改写终态(那是别人的历史);但**用户令牌必须能清**,否则那个节点
|
|
456
|
+
// 永远收不到新消息(实测 4 个节点各 14–46 条,只能人工改库)。
|
|
457
|
+
// ─────────────────────────────────────────────────────────────────────
|
|
458
|
+
describe("#4307 cancel_task 对 expired:用户令牌可清、节点令牌不可", () => {
|
|
459
|
+
test("用户令牌:可以取消 expired,且 result 被写上(从而不再被 409 计数)", async () => {
|
|
460
|
+
const { tools } = buildHandlers({ userId: U_SINGLE });
|
|
461
|
+
const t = makeTask(A1, "expired", "x517 g9 expired by user");
|
|
462
|
+
const r = await call(tools["cancel_task"], { task_id: t, reason: "clear backlog" });
|
|
463
|
+
expect(r.ok).toBe(true);
|
|
464
|
+
expect(r.cancelled).toBe(true);
|
|
465
|
+
expect(taskById(t)?.status).toBe("cancelled");
|
|
466
|
+
const row = db.get<{ result: string | null }>("SELECT result FROM tasks WHERE task_id = ?1", t);
|
|
467
|
+
expect(row?.result).toBe("clear backlog");
|
|
468
|
+
});
|
|
469
|
+
|
|
470
|
+
test("节点令牌:expired 仍不可取消(不重写终态历史)", async () => {
|
|
471
|
+
const { tools } = buildHandlers({ netId: NET_A, alias: A1, isNetwork: true });
|
|
472
|
+
const t = makeTask(A1, "expired", "x517 g9 expired by node");
|
|
473
|
+
const r = await call(tools["cancel_task"], { task_id: t });
|
|
474
|
+
expect(r.ok).toBe(false);
|
|
475
|
+
expect(r.cancelled).toBe(false);
|
|
476
|
+
expect(taskById(t)?.status).toBe("expired");
|
|
477
|
+
});
|
|
478
|
+
|
|
479
|
+
test("节点令牌:非终态仍可取消(既有行为不变)", async () => {
|
|
480
|
+
const { tools } = buildHandlers({ netId: NET_A, alias: A1, isNetwork: true });
|
|
481
|
+
const t = makeTask(A1, "delivered", "x517 g9 delivered by node");
|
|
482
|
+
const r = await call(tools["cancel_task"], { task_id: t });
|
|
483
|
+
expect(r.cancelled).toBe(true);
|
|
484
|
+
expect(taskById(t)?.status).toBe("cancelled");
|
|
485
|
+
});
|
|
486
|
+
});
|
|
@@ -71,7 +71,8 @@ describe("#3146 上一次配置下发的投影", () => {
|
|
|
71
71
|
test("不投影 created_by_token(凭据标识不是界面信息)", () => {
|
|
72
72
|
const v: any = projectLastConfigUpdate(row() as any);
|
|
73
73
|
expect(Object.keys(v).sort()).toEqual([
|
|
74
|
-
"acked_at", "created_at", "error", "observed_status", "requested_model", "
|
|
74
|
+
"acked_at", "created_at", "error", "observed_status", "requested_model", "requested_variant",
|
|
75
|
+
"resolved_after_queue", "status", "terminal", "update_id",
|
|
75
76
|
]);
|
|
76
77
|
expect(JSON.stringify(v)).not.toContain("created_by_token");
|
|
77
78
|
});
|
|
@@ -124,3 +125,104 @@ describe("#3146 GET /api/nodes/:id/config 的接线", () => {
|
|
|
124
125
|
expect(configGetHandler()).not.toContain("created_by_token");
|
|
125
126
|
});
|
|
126
127
|
});
|
|
128
|
+
|
|
129
|
+
// ── #4499 ────────────────────────────────────────────────────────────────────
|
|
130
|
+
// 现象(2026-11-10 生产实测,通信欧):档位被拒(busy)→ 节点排队 → 29s 后真的应用上了
|
|
131
|
+
// → 顶层 modelVariant 已变 → 但 last_update 永远停在 rejected/variant_busy,
|
|
132
|
+
// 客户端于是一直显示「被拒绝」,而它其实已经生效。
|
|
133
|
+
//
|
|
134
|
+
// 判据(三条同时成立才算已生效,缺一条都保持 rejected):
|
|
135
|
+
// ① ack 原因是 variant_busy;② patch 里确实要了档位;③ 节点当前回读的档位 == 请求值。
|
|
136
|
+
// 另加 15 分钟时间窗;`applied` 仍然只代表「写入并回读一致」,不用「已排队」冒充。
|
|
137
|
+
describe("#4499 被拒后排队已生效的下发", () => {
|
|
138
|
+
const busyRow = (over: Record<string, unknown> = {}) => ({
|
|
139
|
+
update_id: "cu_busy",
|
|
140
|
+
status: "rejected",
|
|
141
|
+
patch_json: JSON.stringify({ modelVariant: "high" }),
|
|
142
|
+
error: "variant_busy (in_flight=1, turn_age_ms=31421)",
|
|
143
|
+
created_at: "1793519656437",
|
|
144
|
+
acked_at: "1793519656466",
|
|
145
|
+
...over,
|
|
146
|
+
});
|
|
147
|
+
const now = 1793519656437 + 29_000; // 29 秒后:正是生产里实际应用的时刻
|
|
148
|
+
|
|
149
|
+
test("回读档位 == 请求值 ⇒ 投影成 applied,但保留原始 rejected 与标记", () => {
|
|
150
|
+
const v = projectLastConfigUpdate(busyRow(), { currentVariant: "high", nowMs: now });
|
|
151
|
+
expect(v.status).toBe("applied");
|
|
152
|
+
expect(v.terminal).toBe(true);
|
|
153
|
+
expect(v.error).toBeNull();
|
|
154
|
+
expect(v.resolved_after_queue).toBe(true);
|
|
155
|
+
expect(v.observed_status).toBe("rejected"); // 原始事实不丢
|
|
156
|
+
expect(v.requested_variant).toBe("high");
|
|
157
|
+
});
|
|
158
|
+
|
|
159
|
+
test("回读档位对不上 ⇒ 保持 rejected(不许猜)", () => {
|
|
160
|
+
const v = projectLastConfigUpdate(busyRow(), { currentVariant: "low", nowMs: now });
|
|
161
|
+
expect(v.status).toBe("rejected");
|
|
162
|
+
expect(v.resolved_after_queue).toBe(false);
|
|
163
|
+
expect(v.error).toContain("variant_busy");
|
|
164
|
+
});
|
|
165
|
+
|
|
166
|
+
test("没有回读上下文 ⇒ 保持 rejected(不可能凭 patch 猜)", () => {
|
|
167
|
+
const v = projectLastConfigUpdate(busyRow(), { nowMs: now });
|
|
168
|
+
expect(v.status).toBe("rejected");
|
|
169
|
+
expect(v.resolved_after_queue).toBe(false);
|
|
170
|
+
});
|
|
171
|
+
|
|
172
|
+
test("超过 15 分钟窗口 ⇒ 不假设已生效", () => {
|
|
173
|
+
const late = 1793519656437 + 16 * 60 * 1000;
|
|
174
|
+
const v = projectLastConfigUpdate(busyRow(), { currentVariant: "high", nowMs: late });
|
|
175
|
+
expect(v.status).toBe("rejected");
|
|
176
|
+
expect(v.resolved_after_queue).toBe(false);
|
|
177
|
+
});
|
|
178
|
+
|
|
179
|
+
test("原因不是 variant_busy ⇒ 不参与这个推断(例如 session 没起)", () => {
|
|
180
|
+
const v = projectLastConfigUpdate(
|
|
181
|
+
busyRow({ error: "OpenCode V2 session is not running; model was not changed" }),
|
|
182
|
+
{ currentVariant: "high", nowMs: now },
|
|
183
|
+
);
|
|
184
|
+
expect(v.status).toBe("rejected");
|
|
185
|
+
expect(v.resolved_after_queue).toBe(false);
|
|
186
|
+
});
|
|
187
|
+
|
|
188
|
+
test("patch 里没有 modelVariant ⇒ 与档位无关,不推断", () => {
|
|
189
|
+
const v = projectLastConfigUpdate(busyRow({ patch_json: JSON.stringify({ model: "a/b" }) }), {
|
|
190
|
+
currentVariant: "high",
|
|
191
|
+
nowMs: now,
|
|
192
|
+
});
|
|
193
|
+
expect(v.status).toBe("rejected");
|
|
194
|
+
expect(v.resolved_after_queue).toBe(false);
|
|
195
|
+
expect(v.requested_variant).toBeNull();
|
|
196
|
+
});
|
|
197
|
+
|
|
198
|
+
test("要求清空(modelVariant:null / \"default\")⇒ 与回读的 null 相等才算生效", () => {
|
|
199
|
+
for (const patch of [{ modelVariant: null }, { modelVariant: "default" }]) {
|
|
200
|
+
const applied = projectLastConfigUpdate(busyRow({ patch_json: JSON.stringify(patch) }), {
|
|
201
|
+
currentVariant: null,
|
|
202
|
+
nowMs: now,
|
|
203
|
+
});
|
|
204
|
+
expect(applied.status).toBe("applied");
|
|
205
|
+
const notApplied = projectLastConfigUpdate(busyRow({ patch_json: JSON.stringify(patch) }), {
|
|
206
|
+
currentVariant: "high",
|
|
207
|
+
nowMs: now,
|
|
208
|
+
});
|
|
209
|
+
expect(notApplied.status).toBe("rejected");
|
|
210
|
+
}
|
|
211
|
+
});
|
|
212
|
+
|
|
213
|
+
test("真的 applied 行不受影响:resolved_after_queue=false 且 requested_variant 仍然带出", () => {
|
|
214
|
+
const v = projectLastConfigUpdate(busyRow({ status: "applied", error: null }), {
|
|
215
|
+
currentVariant: "high",
|
|
216
|
+
nowMs: now,
|
|
217
|
+
});
|
|
218
|
+
expect(v.status).toBe("applied");
|
|
219
|
+
expect(v.resolved_after_queue).toBe(false);
|
|
220
|
+
expect(v.requested_variant).toBe("high");
|
|
221
|
+
});
|
|
222
|
+
|
|
223
|
+
test("接线:GET /api/nodes/:id/config 把当前档位传给投影", () => {
|
|
224
|
+
const block = configGetHandler();
|
|
225
|
+
expect(block).toContain("currentVariant:");
|
|
226
|
+
expect(block).toContain("modelVariant");
|
|
227
|
+
});
|
|
228
|
+
});
|
|
@@ -41,6 +41,15 @@ export interface LastConfigUpdate {
|
|
|
41
41
|
terminal: boolean;
|
|
42
42
|
/** 这次下发要的模型(来自 patch_json.model);patch 里没有就是 null。 */
|
|
43
43
|
requested_model: string | null;
|
|
44
|
+
/** 这次下发要的思考档位(来自 patch_json.modelVariant);patch 里没有就是 null。 */
|
|
45
|
+
requested_variant: string | null;
|
|
46
|
+
/**
|
|
47
|
+
* #4499 —— 「排队后被应用」是**推断**出来的,不是节点回报的:
|
|
48
|
+
* 原来 ack 是 rejected/variant_busy,之后节点把排队的档位应用上了,回读档位 == 请求值。
|
|
49
|
+
* 这种情况下 status 投影成 applied(因为它确实生效且回读一致),但这里留 true 便于排查;
|
|
50
|
+
* observed_status 仍然保留原始的 rejected。应用窗口外的、或回读对不上的,一律 false。
|
|
51
|
+
*/
|
|
52
|
+
resolved_after_queue: boolean;
|
|
44
53
|
/** 节点自报的失败原因(rejected/timeout 才有;applied 是 null)。 */
|
|
45
54
|
error: string | null;
|
|
46
55
|
/** ISO;TEXT 存的是 ms epoch,转不出来就是 null。 */
|
|
@@ -76,17 +85,72 @@ function requestedModel(patchJson: string | null): string | null {
|
|
|
76
85
|
}
|
|
77
86
|
}
|
|
78
87
|
|
|
88
|
+
/**
|
|
89
|
+
* patch_json 里的思考档位(`modelVariant`)。
|
|
90
|
+
*
|
|
91
|
+
* 三种「没要档位」必须分开,不能都折叠成 null:
|
|
92
|
+
* · patch 里**没有** modelVariant 这个键 ⇒ undefined(这次下发与档位无关)
|
|
93
|
+
* · patch 里是 `null` / `"default"` ⇒ null(**明确要求清空**回默认)
|
|
94
|
+
* · patch 里是字符串 ⇒ 原样
|
|
95
|
+
*/
|
|
96
|
+
function requestedVariant(patchJson: string | null): string | null | undefined {
|
|
97
|
+
if (!patchJson) return undefined;
|
|
98
|
+
try {
|
|
99
|
+
const parsed = JSON.parse(patchJson) as { modelVariant?: unknown };
|
|
100
|
+
if (!Object.prototype.hasOwnProperty.call(parsed, "modelVariant")) return undefined;
|
|
101
|
+
const v = (parsed as { modelVariant?: unknown }).modelVariant;
|
|
102
|
+
if (v === null || v === undefined) return null;
|
|
103
|
+
if (typeof v === "string") return v === "default" ? null : v;
|
|
104
|
+
return undefined;
|
|
105
|
+
} catch {
|
|
106
|
+
return undefined;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** #4499 —— 排队应用的时间窗。超过这个窗口就不再假设「它后来生效了」。 */
|
|
111
|
+
export const QUEUED_VARIANT_WINDOW_MS = 15 * 60 * 1000;
|
|
112
|
+
|
|
113
|
+
/** ack 的原因是「档位忙」吗?只认节点自己写的 `variant_busy`(后面可能带细节)。 */
|
|
114
|
+
function isVariantBusy(error: string | null): boolean {
|
|
115
|
+
return typeof error === "string" && /^variant_busy\b/.test(error);
|
|
116
|
+
}
|
|
117
|
+
|
|
79
118
|
/** 纯函数:一行 → 对外形状。抽出来是为了能单独钉住「闭集外不折叠」那条。 */
|
|
80
|
-
export function projectLastConfigUpdate(
|
|
119
|
+
export function projectLastConfigUpdate(
|
|
120
|
+
row: Row,
|
|
121
|
+
ctx: { currentVariant?: string | null; nowMs?: number } = {},
|
|
122
|
+
): LastConfigUpdate {
|
|
81
123
|
const observed = typeof row.status === "string" ? row.status : "";
|
|
82
124
|
const known = (CONFIG_UPDATE_STATUSES as readonly string[]).includes(observed);
|
|
125
|
+
const reqVariant = requestedVariant(row.patch_json);
|
|
126
|
+
|
|
127
|
+
// #4499:rejected/variant_busy 之后,节点把排队的档位应用上了。
|
|
128
|
+
// 判据三条同时成立才算(缺一条都保持 rejected,绝不把「排队中」冒充 applied):
|
|
129
|
+
// ① ack 原因是 variant_busy;② patch 里确实要了档位;③ 节点当前回读的档位 == 请求值。
|
|
130
|
+
// 另外加一条时间窗:太久以前的下发即使值巧合相等也不算(那是另一件事)。
|
|
131
|
+
let resolvedAfterQueue = false;
|
|
132
|
+
if (known && observed === "rejected" && isVariantBusy(row.error) && reqVariant !== undefined) {
|
|
133
|
+
const nowMs = ctx.nowMs ?? Date.now();
|
|
134
|
+
const createdMs = Number(row.created_at);
|
|
135
|
+
const inWindow =
|
|
136
|
+
Number.isFinite(createdMs) && createdMs > 0 &&
|
|
137
|
+
nowMs >= createdMs && nowMs - createdMs <= QUEUED_VARIANT_WINDOW_MS;
|
|
138
|
+
const current = ctx.currentVariant === undefined ? undefined : ctx.currentVariant === "default" ? null : ctx.currentVariant;
|
|
139
|
+
const requested = reqVariant === null ? null : reqVariant;
|
|
140
|
+
if (inWindow && current !== undefined && current === requested) resolvedAfterQueue = true;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
const effectiveStatus = resolvedAfterQueue ? "applied" : known ? (observed as ConfigUpdateStatus) : "unknown";
|
|
144
|
+
|
|
83
145
|
return {
|
|
84
146
|
update_id: row.update_id,
|
|
85
|
-
status:
|
|
147
|
+
status: effectiveStatus,
|
|
86
148
|
observed_status: observed,
|
|
87
|
-
terminal: known ? TERMINAL[observed as ConfigUpdateStatus] : false,
|
|
149
|
+
terminal: resolvedAfterQueue ? true : known ? TERMINAL[observed as ConfigUpdateStatus] : false,
|
|
88
150
|
requested_model: requestedModel(row.patch_json),
|
|
89
|
-
|
|
151
|
+
requested_variant: reqVariant === undefined ? null : reqVariant,
|
|
152
|
+
resolved_after_queue: resolvedAfterQueue,
|
|
153
|
+
error: resolvedAfterQueue ? null : typeof row.error === "string" && row.error ? row.error : null,
|
|
90
154
|
created_at: msToIso(row.created_at),
|
|
91
155
|
acked_at: msToIso(row.acked_at),
|
|
92
156
|
};
|
|
@@ -101,7 +165,8 @@ export const LAST_CONFIG_UPDATE_SQL =
|
|
|
101
165
|
export function readLastConfigUpdate(
|
|
102
166
|
get: (sql: string, ...params: any[]) => Row | null,
|
|
103
167
|
nodeId: string,
|
|
168
|
+
ctx: { currentVariant?: string | null; nowMs?: number } = {},
|
|
104
169
|
): LastConfigUpdate | null {
|
|
105
170
|
const row = get(LAST_CONFIG_UPDATE_SQL, nodeId);
|
|
106
|
-
return row ? projectLastConfigUpdate(row) : null;
|
|
171
|
+
return row ? projectLastConfigUpdate(row, ctx) : null;
|
|
107
172
|
}
|
|
@@ -22,6 +22,15 @@ export function createdDaemon(nodeId: string): string | null {
|
|
|
22
22
|
export function activeBinding(nodeId: string): Binding | null {
|
|
23
23
|
return db.get<Binding>("SELECT * FROM node_daemon_bindings WHERE node_id=?1 AND status='active'", nodeId);
|
|
24
24
|
}
|
|
25
|
+
/** clone_node source facts for an ADOPTED node (no succeeded create row).
|
|
26
|
+
* Same shape as the create row clone_node reads; flags stay empty (the
|
|
27
|
+
* daemon reads the real config from disk), runtime/model come from the node row. */
|
|
28
|
+
export function adoptedCloneSourceRow(nodeId: string, networkId: string, runtime: string | null, alias: string):
|
|
29
|
+
{ daemon_node_id: string; runtime: string; model: string | null; flags_json: string; child_name: string } | undefined {
|
|
30
|
+
const b = db.get<Binding>("SELECT * FROM node_daemon_bindings WHERE node_id=?1 AND network_id=?2 AND status='active'", nodeId, networkId);
|
|
31
|
+
if (!b) return undefined;
|
|
32
|
+
return { daemon_node_id: b.daemon_node_id, runtime: runtime || "", model: null, flags_json: "{}", child_name: alias };
|
|
33
|
+
}
|
|
25
34
|
export function resolveManagedDaemon(nodeId: string): string | null {
|
|
26
35
|
return createdDaemon(nodeId) ?? activeBinding(nodeId)?.daemon_node_id ?? null;
|
|
27
36
|
}
|
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
// 节点管理授权(node-grants.ts)—— 全部经真实 HTTP 入口(bootServer + REST / /mcp)。
|
|
2
|
+
//
|
|
3
|
+
// 钉住:
|
|
4
|
+
// 1. PUT /api/nodes/:id/grants:网络 owner 可授全网;节点主人(普通成员)不行;部门负责人只能授自己子树里的部门范围,
|
|
5
|
+
// 授 network 403;未知能力 / 计划中的 board 能力 400;GET 读回;/health 带 node_grants。
|
|
6
|
+
// 2. 定时任务:没授权时节点看不到别人的计划;schedules·network·read ⇒ 看得到、改不了(not_schedule_creator);
|
|
7
|
+
// edit ⇒ 能改、能取消,审计一行 schedule_changed_via_node_grant;department 范围只覆盖目标节点在子树里的计划;
|
|
8
|
+
// 只读模式的节点 edit 降为 read;撤销([])当场生效。
|
|
9
|
+
//
|
|
10
|
+
// 跑法:COMMHUB_DB=/tmp/x.db bun test server/src/node-grants-http.test.ts
|
|
11
|
+
import { afterAll, beforeAll, describe, expect, test } from "bun:test";
|
|
12
|
+
import { addNetworkMember, createNetworkTokenForNode, register } from "./auth.js";
|
|
13
|
+
import { db } from "./db.js";
|
|
14
|
+
|
|
15
|
+
const activeDbPath = process.env.COMMHUB_DB ?? (process.env.COMMHUB_TEST_PG_URL ? "postgres" : undefined);
|
|
16
|
+
if (!activeDbPath) throw new Error("node-grants requires COMMHUB_DB (or COMMHUB_TEST_PG_URL) before module import");
|
|
17
|
+
|
|
18
|
+
const stamp = Date.now();
|
|
19
|
+
const PW = "NodeGrants123!";
|
|
20
|
+
let server: any, base = "", net = "";
|
|
21
|
+
const user: Record<string, { id: string; name: string; token: string }> = {};
|
|
22
|
+
const node: Record<string, { id: string; alias: string; token: string }> = {};
|
|
23
|
+
const deptA = `dept_ga_${stamp}`, deptB = `dept_gb_${stamp}`;
|
|
24
|
+
|
|
25
|
+
async function call(token: string, method: string, path: string, body?: unknown) {
|
|
26
|
+
const r = await fetch(`${base}${path}`, {
|
|
27
|
+
method, headers: { Authorization: `Bearer ${token}`, ...(body === undefined ? {} : { "Content-Type": "application/json" }) },
|
|
28
|
+
body: body === undefined ? undefined : JSON.stringify(body),
|
|
29
|
+
});
|
|
30
|
+
const text = await r.text();
|
|
31
|
+
let json: any = null; try { json = JSON.parse(text); } catch {}
|
|
32
|
+
return { status: r.status, body: json };
|
|
33
|
+
}
|
|
34
|
+
async function mcp(token: string, name: string, args: Record<string, unknown>): Promise<any> {
|
|
35
|
+
const r = await fetch(`${base}/mcp`, {
|
|
36
|
+
method: "POST",
|
|
37
|
+
headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json", Accept: "application/json, text/event-stream" },
|
|
38
|
+
body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name, arguments: args } }),
|
|
39
|
+
});
|
|
40
|
+
const text = await r.text();
|
|
41
|
+
const data = text.split("\n").find((l) => l.startsWith("data: "));
|
|
42
|
+
const msg = JSON.parse(data ? data.slice(6) : text);
|
|
43
|
+
const inner = msg.result?.content?.[0]?.text;
|
|
44
|
+
try { return JSON.parse(inner); } catch { return { raw: inner ?? msg }; }
|
|
45
|
+
}
|
|
46
|
+
const putGrants = (token: string, nodeId: string, grants: unknown) => call(token, "PUT", `/api/nodes/${nodeId}/grants`, { grants });
|
|
47
|
+
async function scheduleFor(target: string, name: string): Promise<string> {
|
|
48
|
+
const r = await call(user.boss.token, "POST", "/api/scheduled-tasks", {
|
|
49
|
+
network_id: net, name, target_node_id: target, task: `${name} task`, timezone: "UTC", schedule: { type: "interval", every_seconds: 86400 },
|
|
50
|
+
});
|
|
51
|
+
expect(r.status).toBe(201);
|
|
52
|
+
return r.body.schedule.schedule_id;
|
|
53
|
+
}
|
|
54
|
+
const listIds = async (token: string) => ((await mcp(token, "schedule_list", {})).schedules ?? []).map((s: any) => s.schedule_id);
|
|
55
|
+
|
|
56
|
+
let schedA = "", schedB = "";
|
|
57
|
+
|
|
58
|
+
beforeAll(async () => {
|
|
59
|
+
const boss = register(`ng_boss_${stamp}`, PW);
|
|
60
|
+
net = boss.network_id!;
|
|
61
|
+
user.boss = { id: boss.user!.user_id, name: `ng_boss_${stamp}`, token: boss.token! };
|
|
62
|
+
for (const k of ["own", "lead"] as const) {
|
|
63
|
+
const name = `ng_${k}_${stamp}`;
|
|
64
|
+
const u = register(name, PW);
|
|
65
|
+
user[k] = { id: u.user!.user_id, name, token: u.token! };
|
|
66
|
+
expect(addNetworkMember(net, user[k].id, "member", user.boss.id, { agentAccess: "all" }).ok).toBe(true);
|
|
67
|
+
}
|
|
68
|
+
// mgr 是被授权的节点(主人 own);a 在部门 A,b 在部门 B。
|
|
69
|
+
for (const [key, owner] of [["mgr", "own"], ["a", "boss"], ["b", "boss"]] as const) {
|
|
70
|
+
const alias = `ng-${key}-${stamp}`, id = `n_ng_${key}_${stamp}`;
|
|
71
|
+
const t = createNetworkTokenForNode(user[owner].id, net, alias, id);
|
|
72
|
+
expect(t.ok).toBe(true);
|
|
73
|
+
node[key] = { id, alias, token: t.token! };
|
|
74
|
+
db.run("INSERT INTO sessions (resume_id, alias, status, node_id, network_id) VALUES (?1, ?2, 'idle', ?3, ?4)", [`r_${id}`, alias, id, net]);
|
|
75
|
+
}
|
|
76
|
+
db.run("INSERT INTO network_departments (network_id, department_id, name, parent_id, sort, created_by, leader_user_id) VALUES (?1, ?2, 'A', NULL, 0, ?3, ?4)", [net, deptA, user.boss.id, user.lead.id]);
|
|
77
|
+
db.run("INSERT INTO network_departments (network_id, department_id, name, parent_id, sort, created_by) VALUES (?1, ?2, 'B', NULL, 1, ?3)", [net, deptB, user.boss.id]);
|
|
78
|
+
// board 判「卡的负责人所在部门」⇒ 成员要先有部门。
|
|
79
|
+
db.run("UPDATE network_members SET department_id = ?1 WHERE network_id = ?2 AND user_id IN (?3, ?4)", [deptA, net, user.own.id, user.lead.id]);
|
|
80
|
+
db.run("UPDATE network_members SET department_id = ?1 WHERE network_id = ?2 AND user_id = ?3", [deptB, net, user.boss.id]);
|
|
81
|
+
db.run("UPDATE nodes SET department_id = ?1 WHERE node_id = ?2", [deptA, node.a.id]);
|
|
82
|
+
db.run("UPDATE nodes SET department_id = ?1 WHERE node_id = ?2", [deptB, node.b.id]);
|
|
83
|
+
const mod: any = await import("./server.js");
|
|
84
|
+
server = mod.bootServer({ port: 0, hostname: "127.0.0.1" });
|
|
85
|
+
base = `http://127.0.0.1:${server.port}`;
|
|
86
|
+
schedA = await scheduleFor(node.a.id, "for-a");
|
|
87
|
+
schedB = await scheduleFor(node.b.id, "for-b");
|
|
88
|
+
}, 60_000);
|
|
89
|
+
afterAll(() => { server?.stop?.(true); });
|
|
90
|
+
|
|
91
|
+
describe("PUT /api/nodes/:id/grants —— 谁能授", () => {
|
|
92
|
+
test("/health 报 node_grants", async () => {
|
|
93
|
+
const h = await (await fetch(`${base}/health`)).json() as any;
|
|
94
|
+
expect(h.capabilities).toContain("node_grants");
|
|
95
|
+
});
|
|
96
|
+
test("网络 owner 可授全网;GET 读回;[] 清空", async () => {
|
|
97
|
+
const r = await putGrants(user.boss.token, node.mgr.id, [{ capability: "schedules", scope_kind: "network", level: "read" }]);
|
|
98
|
+
expect(r.status).toBe(200);
|
|
99
|
+
expect(r.body.grants).toEqual([expect.objectContaining({ capability: "schedules", scope_kind: "network", scope_id: "", level: "read" })]);
|
|
100
|
+
expect((await call(user.own.token, "GET", `/api/nodes/${node.mgr.id}/grants`)).body.grants.length).toBe(1);
|
|
101
|
+
expect((await putGrants(user.boss.token, node.mgr.id, [])).body.grants).toEqual([]);
|
|
102
|
+
});
|
|
103
|
+
test("节点主人(普通成员)不能给自己的节点授权", async () => {
|
|
104
|
+
const r = await putGrants(user.own.token, node.mgr.id, [{ capability: "schedules", scope_kind: "network", level: "edit" }]);
|
|
105
|
+
expect(r.status).toBe(403);
|
|
106
|
+
});
|
|
107
|
+
test("部门负责人:授自己部门 OK,授全网 / 别的部门 403", async () => {
|
|
108
|
+
expect((await putGrants(user.lead.token, node.mgr.id, [{ capability: "schedules", scope_kind: "department", scope_id: deptA, level: "edit" }])).status).toBe(200);
|
|
109
|
+
expect((await putGrants(user.lead.token, node.mgr.id, [{ capability: "schedules", scope_kind: "network", level: "edit" }])).status).toBe(403);
|
|
110
|
+
expect((await putGrants(user.lead.token, node.mgr.id, [{ capability: "schedules", scope_kind: "department", scope_id: deptB, level: "edit" }])).status).toBe(403);
|
|
111
|
+
await putGrants(user.boss.token, node.mgr.id, []);
|
|
112
|
+
});
|
|
113
|
+
test("未知能力 400;board(第二期已开闸)200 且可读回;不存在的部门 404", async () => {
|
|
114
|
+
expect((await putGrants(user.boss.token, node.mgr.id, [{ capability: "nope", scope_kind: "network" }])).body.error).toBe("invalid_capability");
|
|
115
|
+
// 第二期:board 与 requirements 读写判定同批上线 ⇒ 写入不再被拒。
|
|
116
|
+
expect((await putGrants(user.boss.token, node.mgr.id, [{ capability: "board", scope_kind: "network", level: "read" }])).status).toBe(200);
|
|
117
|
+
const readBack = await call(user.boss.token, "GET", `/api/nodes/${node.mgr.id}/grants?network_id=${net}`);
|
|
118
|
+
expect((readBack.body.grants || []).some((g: any) => g.capability === "board" && g.level === "read")).toBe(true);
|
|
119
|
+
await putGrants(user.boss.token, node.mgr.id, []);
|
|
120
|
+
expect((await putGrants(user.boss.token, node.mgr.id, [{ capability: "schedules", scope_kind: "department", scope_id: "dept_missing" }])).status).toBe(404);
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
test("部门负责人只能授本部门的 board(跨部门 403)", async () => {
|
|
124
|
+
expect((await putGrants(user.lead.token, node.mgr.id, [{ capability: "board", scope_kind: "department", scope_id: deptA, level: "read" }])).status).toBe(200);
|
|
125
|
+
expect((await putGrants(user.lead.token, node.mgr.id, [{ capability: "board", scope_kind: "department", scope_id: deptB, level: "read" }])).status).toBe(403);
|
|
126
|
+
await putGrants(user.boss.token, node.mgr.id, []);
|
|
127
|
+
});
|
|
128
|
+
});
|
|
129
|
+
|
|
130
|
+
describe("定时任务 —— 授权让节点看得到 / 改得了", () => {
|
|
131
|
+
test("没授权:看不到别人的计划", async () => {
|
|
132
|
+
await putGrants(user.boss.token, node.mgr.id, []);
|
|
133
|
+
const ids = await listIds(node.mgr.token);
|
|
134
|
+
expect(ids).not.toContain(schedA);
|
|
135
|
+
expect((await mcp(node.mgr.token, "schedule_get", { schedule_id: schedA })).error).toBe("schedule_not_found");
|
|
136
|
+
});
|
|
137
|
+
test("network·read:看得到、改不了", async () => {
|
|
138
|
+
await putGrants(user.boss.token, node.mgr.id, [{ capability: "schedules", scope_kind: "network", level: "read" }]);
|
|
139
|
+
const ids = await listIds(node.mgr.token);
|
|
140
|
+
expect(ids).toContain(schedA); expect(ids).toContain(schedB);
|
|
141
|
+
expect((await mcp(node.mgr.token, "schedule_update", { schedule_id: schedA, name: "x" })).error).toBe("not_schedule_creator");
|
|
142
|
+
});
|
|
143
|
+
test("department(A)·edit:只覆盖目标在 A 的;能改能取消;审计一行", async () => {
|
|
144
|
+
await putGrants(user.boss.token, node.mgr.id, [{ capability: "schedules", scope_kind: "department", scope_id: deptA, level: "edit" }]);
|
|
145
|
+
const ids = await listIds(node.mgr.token);
|
|
146
|
+
expect(ids).toContain(schedA); expect(ids).not.toContain(schedB);
|
|
147
|
+
const upd = await mcp(node.mgr.token, "schedule_update", { schedule_id: schedA, name: "renamed by grant" });
|
|
148
|
+
expect(upd.ok).toBe(true);
|
|
149
|
+
expect(upd.schedule.name).toBe("renamed by grant");
|
|
150
|
+
expect((await mcp(node.mgr.token, "schedule_update", { schedule_id: schedB, name: "nope" })).error).toBe("schedule_not_found");
|
|
151
|
+
const audit = db.get<{ n: number | string }>("SELECT COUNT(*) AS n FROM audit_log WHERE action = 'schedule_changed_via_node_grant' AND target_id = ?1", schedA);
|
|
152
|
+
expect(Number(audit!.n)).toBeGreaterThanOrEqual(1);
|
|
153
|
+
});
|
|
154
|
+
test("只读模式的节点:edit 降为 read", async () => {
|
|
155
|
+
db.run("UPDATE nodes SET permission_mode = 'readonly' WHERE node_id = ?1", [node.mgr.id]);
|
|
156
|
+
try {
|
|
157
|
+
const r = await mcp(node.mgr.token, "schedule_update", { schedule_id: schedA, name: "should fail" });
|
|
158
|
+
expect(r.ok).toBe(false);
|
|
159
|
+
} finally {
|
|
160
|
+
db.run("UPDATE nodes SET permission_mode = 'normal' WHERE node_id = ?1", [node.mgr.id]);
|
|
161
|
+
}
|
|
162
|
+
});
|
|
163
|
+
test("撤销([])当场生效", async () => {
|
|
164
|
+
await putGrants(user.boss.token, node.mgr.id, []);
|
|
165
|
+
expect(await listIds(node.mgr.token)).not.toContain(schedA);
|
|
166
|
+
});
|
|
167
|
+
});
|
|
168
|
+
|
|
169
|
+
// ── 第二期:任务看板(board)───────────────────────────────────────────────
|
|
170
|
+
// 判「卡的负责人所在部门」,与定时任务按「目标节点所在部门」不是一回事。
|
|
171
|
+
// 卡:A 的负责人在 deptA(部门负责人 lead 本人),B 的负责人在 deptB(网络 owner boss)。
|
|
172
|
+
// 被授权的节点 mgr 的主人是 own(deptA),但它看不到别人的卡 —— 所以下面看到 A 一定是授权带来的。
|
|
173
|
+
describe("任务看板 —— 授权让节点看得到 / 改得了", () => {
|
|
174
|
+
let cardA = "", cardB = "";
|
|
175
|
+
const cardIds = async (token: string) => ((await mcp(token, "requirements_list", { network_id: net })).requirements ?? []).map((r: any) => r.id);
|
|
176
|
+
|
|
177
|
+
beforeAll(async () => {
|
|
178
|
+
// 🔴 必须在 enforce 下测:默认 "log" 时节点根本不做范围收窄(nodeTaskCaller 返回 null),
|
|
179
|
+
// 那样「授权后才看得到」和「撤销后看不到」都测不出来(无论有没有授权都看得见)。
|
|
180
|
+
process.env.COMMHUB_NODE_PERMISSIONS = "enforce";
|
|
181
|
+
const mk = async (name: string, ownerId: string) => {
|
|
182
|
+
const r = await mcp(user.boss.token, "requirements_create", { network_id: net, name, owner: { kind: "user", id: ownerId } });
|
|
183
|
+
const id = r.requirement?.id;
|
|
184
|
+
expect(typeof id).toBe("string");
|
|
185
|
+
return id as string;
|
|
186
|
+
};
|
|
187
|
+
cardA = await mk(`board A ${stamp}`, user.lead.id);
|
|
188
|
+
cardB = await mk(`board B ${stamp}`, user.boss.id);
|
|
189
|
+
});
|
|
190
|
+
afterAll(() => { delete process.env.COMMHUB_NODE_PERMISSIONS; });
|
|
191
|
+
|
|
192
|
+
test("没授权:别人的卡看不到,也改不了", async () => {
|
|
193
|
+
await putGrants(user.boss.token, node.mgr.id, []);
|
|
194
|
+
const ids = await cardIds(node.mgr.token);
|
|
195
|
+
expect(ids).not.toContain(cardA); expect(ids).not.toContain(cardB);
|
|
196
|
+
const upd = await mcp(node.mgr.token, "requirements_update", { network_id: net, id: cardA, description: "nope" });
|
|
197
|
+
expect(upd.ok).not.toBe(true);
|
|
198
|
+
});
|
|
199
|
+
|
|
200
|
+
test("department(A)·read:看得到 A、看不到 B;B 是 not_found;改不了", async () => {
|
|
201
|
+
await putGrants(user.boss.token, node.mgr.id, [{ capability: "board", scope_kind: "department", scope_id: deptA, level: "read" }]);
|
|
202
|
+
const ids = await cardIds(node.mgr.token);
|
|
203
|
+
expect(ids).toContain(cardA); expect(ids).not.toContain(cardB);
|
|
204
|
+
expect((await mcp(node.mgr.token, "requirements_get", { network_id: net, id: cardB })).error).toBe("requirement_not_found");
|
|
205
|
+
expect((await mcp(node.mgr.token, "requirements_update", { network_id: net, id: cardA, description: "read only" })).ok).not.toBe(true);
|
|
206
|
+
});
|
|
207
|
+
|
|
208
|
+
test("department(A)·edit:能改 A,审计 requirement_changed_via_node_grant;B 仍 not_found", async () => {
|
|
209
|
+
await putGrants(user.boss.token, node.mgr.id, [{ capability: "board", scope_kind: "department", scope_id: deptA, level: "edit" }]);
|
|
210
|
+
const upd = await mcp(node.mgr.token, "requirements_update", { network_id: net, id: cardA, description: "changed by grant" });
|
|
211
|
+
expect(upd.ok).toBe(true);
|
|
212
|
+
const audit = db.get<{ n: number | string }>("SELECT COUNT(*) AS n FROM audit_log WHERE action = 'requirement_changed_via_node_grant' AND target_id = ?1", cardA);
|
|
213
|
+
expect(Number(audit!.n)).toBeGreaterThanOrEqual(1);
|
|
214
|
+
expect((await mcp(node.mgr.token, "requirements_update", { network_id: net, id: cardB, description: "nope" })).error).toBe("requirement_not_found");
|
|
215
|
+
});
|
|
216
|
+
|
|
217
|
+
test("network·read:两张卡都能看到(不拼巨大 IN 列表)", async () => {
|
|
218
|
+
await putGrants(user.boss.token, node.mgr.id, [{ capability: "board", scope_kind: "network", level: "read" }]);
|
|
219
|
+
const ids = await cardIds(node.mgr.token);
|
|
220
|
+
expect(ids).toContain(cardA); expect(ids).toContain(cardB);
|
|
221
|
+
});
|
|
222
|
+
|
|
223
|
+
test("只读模式的节点:edit 降为 read,改不动", async () => {
|
|
224
|
+
await putGrants(user.boss.token, node.mgr.id, [{ capability: "board", scope_kind: "department", scope_id: deptA, level: "edit" }]);
|
|
225
|
+
db.run("UPDATE nodes SET permission_mode = 'readonly' WHERE node_id = ?1", [node.mgr.id]);
|
|
226
|
+
try {
|
|
227
|
+
expect((await mcp(node.mgr.token, "requirements_update", { network_id: net, id: cardA, description: "should fail" })).ok).not.toBe(true);
|
|
228
|
+
// 但看还是能看
|
|
229
|
+
expect(await cardIds(node.mgr.token)).toContain(cardA);
|
|
230
|
+
} finally {
|
|
231
|
+
db.run("UPDATE nodes SET permission_mode = 'normal' WHERE node_id = ?1", [node.mgr.id]);
|
|
232
|
+
}
|
|
233
|
+
});
|
|
234
|
+
|
|
235
|
+
test("撤销([])当场生效", async () => {
|
|
236
|
+
await putGrants(user.boss.token, node.mgr.id, []);
|
|
237
|
+
expect(await cardIds(node.mgr.token)).not.toContain(cardA);
|
|
238
|
+
});
|
|
239
|
+
});
|