@sleep2agi/commhub-server 0.9.0-preview.280 → 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/anet-variant-real-daemon-http.test.ts +3 -2
- 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 +13 -2
- 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/health-redaction.test.ts +8 -4
- package/src/launched-by-cli-report-http.test.ts +155 -0
- 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 +355 -0
- package/src/node-lifecycle-read.ts +1 -1
- package/src/node-permissions.ts +168 -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-comment-http.test.ts +1 -1
- package/src/requirements-status-participants-http.test.ts +3 -3
- 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 +65 -5
- package/src/server.ts +186 -11
- package/src/session-project-attach-migration.test.ts +2 -1
- package/src/session-project-attach-native.test.ts +3 -1
- package/src/session-project-create-http.test.ts +3 -2
- package/src/session-project-create-native.test.ts +3 -1
- package/src/session-source-delivery.ts +5 -0
- package/src/session-source-directory-http.test.ts +5 -1
- package/src/session-source-evidence.test.ts +11 -4
- package/src/session-source-transport.ts +7 -1
- package/src/steer-send-message.test.ts +121 -0
- package/src/task-access.ts +21 -1
- package/src/test-work-root.ts +18 -0
- package/src/tools.ts +117 -33
|
@@ -191,6 +191,26 @@ function evictExpired(now = Date.now()): void {
|
|
|
191
191
|
}
|
|
192
192
|
}
|
|
193
193
|
|
|
194
|
+
const OPENCODE_RUNTIME_LABELS = new Set(["opencode-cli", "opencode-sdk", "opencode"]);
|
|
195
|
+
/** An actively adopted child of this daemon that reports OpenCode V2 (projection only). */
|
|
196
|
+
function adoptedOpenCodeV2Child(nodeId: string, networkId: string, daemonNodeId: string):
|
|
197
|
+
{ child_name: string; workdir: string | null } | "not_v2" | null {
|
|
198
|
+
let b: { workdir: string } | null = null;
|
|
199
|
+
try {
|
|
200
|
+
b = db.get<{ workdir: string }>(
|
|
201
|
+
"SELECT workdir FROM node_daemon_bindings WHERE node_id=?1 AND network_id=?2 AND daemon_node_id=?3 AND status='active'",
|
|
202
|
+
nodeId, networkId, daemonNodeId);
|
|
203
|
+
} catch { return null; }
|
|
204
|
+
if (!b) return null;
|
|
205
|
+
const n = db.get<{ alias: string | null; runtime: string | null; config_snapshot: string | null }>(
|
|
206
|
+
"SELECT alias, runtime, config_snapshot FROM nodes WHERE node_id=?1 AND network_id=?2", nodeId, networkId);
|
|
207
|
+
if (!n?.alias) return null;
|
|
208
|
+
let generation: unknown;
|
|
209
|
+
try { generation = JSON.parse(n.config_snapshot || "{}")?.flags?.opencodeGeneration; } catch { generation = undefined; }
|
|
210
|
+
if (!OPENCODE_RUNTIME_LABELS.has(n.runtime ?? "") || generation !== "v2") return "not_v2";
|
|
211
|
+
return { child_name: n.alias, workdir: b.workdir || null };
|
|
212
|
+
}
|
|
213
|
+
|
|
194
214
|
export function queueOpenCodeCatalogRead(input: QueueCatalogInput):
|
|
195
215
|
| { ok: true; request_id: string; status: "pending"; daemon_alias: string; network_id: string }
|
|
196
216
|
| { ok: false; error: string } {
|
|
@@ -225,9 +245,22 @@ export function queueOpenCodeCatalogRead(input: QueueCatalogInput):
|
|
|
225
245
|
input.networkId, input.daemonNodeId,
|
|
226
246
|
);
|
|
227
247
|
const owned = creates.filter(row => childNodeId(row.request_id) === input.nodeId && row.daemon_node_id === input.daemonNodeId);
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
248
|
+
let row: { child_name: string; workdir: string | null };
|
|
249
|
+
if (owned.length === 1) {
|
|
250
|
+
const created = owned[0]!;
|
|
251
|
+
if (created.runtime !== "opencode-cli" || !v2Flags(created.flags_json)) return { ok: false, error: "not_opencode_v2" };
|
|
252
|
+
row = created;
|
|
253
|
+
} else if (owned.length === 0) {
|
|
254
|
+
// admin 2026-11-11:被这个 daemon **收编**的节点没有创建记录,此前一律 node_not_found,
|
|
255
|
+
// 客户端模型面板只剩一行错误码。active 绑定 + 节点自报 OpenCode V2 就允许代读;
|
|
256
|
+
// 目录用绑定登记的 workdir(daemon 侧照样用它核对 endpoint 的目录)。
|
|
257
|
+
const adopted = adoptedOpenCodeV2Child(input.nodeId, input.networkId, input.daemonNodeId);
|
|
258
|
+
if (adopted === "not_v2") return { ok: false, error: "not_opencode_v2" };
|
|
259
|
+
if (!adopted) return { ok: false, error: "node_not_found" };
|
|
260
|
+
row = adopted;
|
|
261
|
+
} else {
|
|
262
|
+
return { ok: false, error: "node_not_found" };
|
|
263
|
+
}
|
|
231
264
|
|
|
232
265
|
const requestId = `cat_${uuidv4()}`;
|
|
233
266
|
const directory = typeof row.workdir === "string" && row.workdir.length > 0 ? row.workdir : null;
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
// 2026-11-11 安全排查:COMMHUB_ALLOWED_PEER_IPS —— Hub 端口只接名单里的对端 + 本机回环。
|
|
2
|
+
import { describe, expect, test } from "bun:test";
|
|
3
|
+
import { mkdtempSync } from "fs";
|
|
4
|
+
import { join } from "path";
|
|
5
|
+
import { tmpdir } from "os";
|
|
6
|
+
|
|
7
|
+
process.env.COMMHUB_DB ||= join(mkdtempSync(join(tmpdir(), "anet-peer-")), "hub.db");
|
|
8
|
+
const { peerAllowed } = await import("./server.js");
|
|
9
|
+
|
|
10
|
+
describe("peerAllowed", () => {
|
|
11
|
+
const list = new Set(["47.0.0.1"]);
|
|
12
|
+
test("unset = no restriction (old behaviour)", () => {
|
|
13
|
+
expect(peerAllowed("203.0.113.9", null)).toBe(true);
|
|
14
|
+
});
|
|
15
|
+
test("loopback always allowed (frp, local nodes)", () => {
|
|
16
|
+
for (const ip of ["127.0.0.1", "::1", "::ffff:127.0.0.1", "127.0.1.1"]) expect(peerAllowed(ip, list)).toBe(true);
|
|
17
|
+
});
|
|
18
|
+
test("listed proxy allowed, IPv4-mapped too", () => {
|
|
19
|
+
expect(peerAllowed("47.0.0.1", list)).toBe(true);
|
|
20
|
+
expect(peerAllowed("::ffff:47.0.0.1", list)).toBe(true);
|
|
21
|
+
});
|
|
22
|
+
test("anyone else refused", () => {
|
|
23
|
+
expect(peerAllowed("203.0.113.9", list)).toBe(false);
|
|
24
|
+
expect(peerAllowed("::ffff:203.0.113.9", list)).toBe(false);
|
|
25
|
+
});
|
|
26
|
+
test("unknown peer is not refused (never lock everyone out on a missing address)", () => {
|
|
27
|
+
expect(peerAllowed(null, list)).toBe(true);
|
|
28
|
+
});
|
|
29
|
+
});
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
// 2026-11-11 安全排查:生产 Hub 的公开注册没有开关(任何人都能注册、领令牌、按令牌限额上传)。
|
|
2
|
+
// COMMHUB_REGISTRATION=closed 关掉注册;不设 = 旧行为。库里还没有用户时(装机第一个 admin)照常放行。
|
|
3
|
+
import { describe, expect, test, beforeAll, afterAll } from "bun:test";
|
|
4
|
+
import { mkdtempSync, rmSync } from "fs";
|
|
5
|
+
import { join } from "path";
|
|
6
|
+
import { tmpdir } from "os";
|
|
7
|
+
import { register } from "./auth.js";
|
|
8
|
+
|
|
9
|
+
const DIR = mkdtempSync(join(tmpdir(), "anet-regswitch-"));
|
|
10
|
+
let BASE = "";
|
|
11
|
+
let hub: any = null;
|
|
12
|
+
|
|
13
|
+
const reg = (username: string) => fetch(`${BASE}/api/auth/register`, {
|
|
14
|
+
method: "POST",
|
|
15
|
+
headers: { "Content-Type": "application/json" },
|
|
16
|
+
body: JSON.stringify({ username, password: "RegSwitchPassw0rd!" }),
|
|
17
|
+
}).then(async r => ({ status: r.status, body: await r.json() as any }));
|
|
18
|
+
|
|
19
|
+
beforeAll(async () => {
|
|
20
|
+
process.env.COMMHUB_DB ||= join(DIR, "hub.db");
|
|
21
|
+
process.env.COMMHUB_UPLOADS_DIR = join(DIR, "uploads");
|
|
22
|
+
process.env.HOST = "127.0.0.1";
|
|
23
|
+
delete process.env.COMMHUB_REGISTRATION;
|
|
24
|
+
const mod: any = await import("./server.js");
|
|
25
|
+
hub = mod.bootServer({ port: 0, hostname: "127.0.0.1" });
|
|
26
|
+
BASE = `http://127.0.0.1:${hub.port}`;
|
|
27
|
+
}, 30_000);
|
|
28
|
+
|
|
29
|
+
afterAll(() => {
|
|
30
|
+
delete process.env.COMMHUB_REGISTRATION;
|
|
31
|
+
try { hub?.stop?.(true); } catch {}
|
|
32
|
+
try { rmSync(DIR, { recursive: true, force: true }); } catch {}
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
describe("COMMHUB_REGISTRATION", () => {
|
|
36
|
+
test("unset: registration stays open (unchanged)", async () => {
|
|
37
|
+
register(`seed_${Date.now()}`, "RegSwitchPassw0rd!");
|
|
38
|
+
const r = await reg(`open_${Date.now()}`);
|
|
39
|
+
expect(r.status).toBe(200);
|
|
40
|
+
expect(r.body.ok).toBe(true);
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
test("closed: new sign-ups get 403 registration_closed; login still works", async () => {
|
|
44
|
+
const name = `before_${Date.now()}`;
|
|
45
|
+
expect((await reg(name)).status).toBe(200);
|
|
46
|
+
process.env.COMMHUB_REGISTRATION = "closed";
|
|
47
|
+
try {
|
|
48
|
+
const r = await reg(`late_${Date.now()}`);
|
|
49
|
+
expect(r.status).toBe(403);
|
|
50
|
+
expect(r.body.error).toBe("registration_closed");
|
|
51
|
+
const login = await fetch(`${BASE}/api/auth/login`, {
|
|
52
|
+
method: "POST", headers: { "Content-Type": "application/json" },
|
|
53
|
+
body: JSON.stringify({ username: name, password: "RegSwitchPassw0rd!" }),
|
|
54
|
+
});
|
|
55
|
+
expect(login.status).toBe(200);
|
|
56
|
+
} finally {
|
|
57
|
+
delete process.env.COMMHUB_REGISTRATION;
|
|
58
|
+
}
|
|
59
|
+
});
|
|
60
|
+
});
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
// #4315 —— 裸回执(既无 alias 也无 in_reply_to)会把那笔任务留成 expired,
|
|
2
|
+
// 攒够 3 条就把节点挡成 target_never_consumes。
|
|
3
|
+
// 判据:**这台节点手上恰好一条非终态任务**时才推断 in_reply_to;多条并存保持原拒绝。
|
|
4
|
+
import { afterAll, beforeEach, describe, expect, test } from "bun:test";
|
|
5
|
+
import { db, uuidv4 } from "./db.js";
|
|
6
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
7
|
+
import { registerTools } from "./tools.js";
|
|
8
|
+
|
|
9
|
+
const NET = "net_4315";
|
|
10
|
+
const SENDER = "sender-4315";
|
|
11
|
+
const NODE_ALIAS = "node-4315";
|
|
12
|
+
const NODE_ID = "node_4315_x";
|
|
13
|
+
const TOKEN_ID = "tok_4315_x";
|
|
14
|
+
const USER = "u4315";
|
|
15
|
+
|
|
16
|
+
function reset() {
|
|
17
|
+
for (const t of ["tasks", "inbox", "task_events"]) {
|
|
18
|
+
try { db.run(`DELETE FROM ${t} WHERE network_id = ?1`, [NET]); } catch {}
|
|
19
|
+
}
|
|
20
|
+
try { db.run("DELETE FROM sessions WHERE network_id = ?1", [NET]); } catch {}
|
|
21
|
+
try { db.run("DELETE FROM nodes WHERE network_id = ?1", [NET]); } catch {}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function seed() {
|
|
25
|
+
reset();
|
|
26
|
+
db.run(
|
|
27
|
+
`INSERT INTO nodes (node_id, node_name, alias, network_id, created_at) VALUES (?1, ?2, ?2, ?3, datetime('now'))`,
|
|
28
|
+
[NODE_ID, NODE_ALIAS, NET],
|
|
29
|
+
);
|
|
30
|
+
try { db.run("DELETE FROM users WHERE user_id = ?1", [USER]); } catch {}
|
|
31
|
+
db.run(`INSERT INTO users (user_id, username, password_hash, role, created_at) VALUES (?1, ?1, 'x', 'user', datetime('now'))`, [USER]);
|
|
32
|
+
try { db.run("DELETE FROM api_tokens WHERE token_id = ?1", [TOKEN_ID]); } catch {}
|
|
33
|
+
db.run(
|
|
34
|
+
`INSERT INTO api_tokens (token_id, token_hash, user_id, network_id, name, scope, bound_node_id, node_identity_epoch)
|
|
35
|
+
VALUES (?1, 'h4315', ?2, ?3, ?4, 'network', ?5, 2)`,
|
|
36
|
+
[TOKEN_ID, USER, NET, `node:${NODE_ALIAS}`, NODE_ID],
|
|
37
|
+
);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function makeTask(status: string, content: string): string {
|
|
41
|
+
const id = uuidv4();
|
|
42
|
+
db.run(
|
|
43
|
+
`INSERT INTO tasks (task_id, from_name, to_name, priority, status, content, requires_response, created_at, network_id)
|
|
44
|
+
VALUES (?1, ?2, ?3, 'normal', ?4, ?5, 'reply', datetime('now'), ?6)`,
|
|
45
|
+
[id, SENDER, NODE_ALIAS, status, content, NET],
|
|
46
|
+
);
|
|
47
|
+
return id;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function buildNodeTokenTools() {
|
|
51
|
+
const server = new McpServer({ name: "t", version: "0" }) as any;
|
|
52
|
+
const tools: Record<string, any> = {};
|
|
53
|
+
const orig = server.tool.bind(server);
|
|
54
|
+
server.tool = (name: string, desc: string, schema: any, handler: any) => {
|
|
55
|
+
tools[name] = handler;
|
|
56
|
+
return orig(name, desc, schema, handler);
|
|
57
|
+
};
|
|
58
|
+
// bound_node_id 就是「这台节点」——推断靠它定位手上的任务
|
|
59
|
+
registerTools(server, undefined, NET, null, NODE_ALIAS, true, TOKEN_ID);
|
|
60
|
+
return tools;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const call = async (h: any, args: any) =>
|
|
64
|
+
JSON.parse((await h(args)).content[0].text);
|
|
65
|
+
|
|
66
|
+
describe("#4315 裸回执的单候选推断", () => {
|
|
67
|
+
beforeEach(seed);
|
|
68
|
+
|
|
69
|
+
test("恰好一条在手任务 ⇒ 推断 in_reply_to,任务被正常结束(不再留 expired)", async () => {
|
|
70
|
+
const tools = buildNodeTokenTools();
|
|
71
|
+
const t = makeTask("delivered", "x4315 single open task");
|
|
72
|
+
const r = await call(tools["send_reply"], { text: "done, single open task" });
|
|
73
|
+
expect(r.ok).toBe(true);
|
|
74
|
+
const row = db.get<{ status: string }>("SELECT status FROM tasks WHERE task_id = ?1", t);
|
|
75
|
+
expect(row?.status).toBe("replied");
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
test("两条在手任务 ⇒ 不推断,仍按原样拒绝(宁可拒绝也不赌对象)", async () => {
|
|
79
|
+
const tools = buildNodeTokenTools();
|
|
80
|
+
makeTask("delivered", "x4315 open A");
|
|
81
|
+
makeTask("delivered", "x4315 open B");
|
|
82
|
+
const r = await call(tools["send_reply"], { text: "ambiguous" });
|
|
83
|
+
expect(r.ok).toBe(false);
|
|
84
|
+
expect(r.error).toBe("reply_target_required");
|
|
85
|
+
});
|
|
86
|
+
});
|
|
@@ -168,7 +168,7 @@ describe("requirements_comment", () => {
|
|
|
168
168
|
const lines = raw.split("\n").filter(x => x.startsWith("data:"));
|
|
169
169
|
const tools = (lines.length ? JSON.parse(lines.at(-1)!.slice(5).trim()) : JSON.parse(raw)).result.tools as any[];
|
|
170
170
|
const byName = new Map(tools.map(t => [t.name, t]));
|
|
171
|
-
expect(String(byName.get("requirements_comment")?.description)).
|
|
171
|
+
expect(String(byName.get("requirements_comment")?.description)).toMatch(/append-only/i);
|
|
172
172
|
expect(String(byName.get("requirements_events")?.description)).toContain("kind=comment");
|
|
173
173
|
});
|
|
174
174
|
});
|
|
@@ -207,14 +207,14 @@ describe("tool descriptions", () => {
|
|
|
207
207
|
const tools = (await rpc(U.nodeA.token, "tools/list", {})).result.tools as any[];
|
|
208
208
|
const byName = new Map(tools.map(t => [t.name, t]));
|
|
209
209
|
const update = byName.get("requirements_update");
|
|
210
|
-
expect(update.description).
|
|
210
|
+
expect(update.description).toMatch(/participants REPLACES the (whole )?list/);
|
|
211
211
|
expect(update.inputSchema.properties.participants.description).toContain("REPLACES");
|
|
212
212
|
expect(Object.keys(update.inputSchema.properties)).toEqual(expect.arrayContaining(["status", "participants_add", "participants_remove"]));
|
|
213
213
|
// #478:节点令牌的 tools/list 里本来就没有 projects_create / projects_update(调了也是 403),那两条的说明从人的列表里读。
|
|
214
214
|
expect(byName.has("projects_create")).toBe(false);
|
|
215
215
|
const human = new Map(((await rpc(U.member.token, "tools/list", {})).result.tools as any[]).map(t => [t.name, t]));
|
|
216
|
-
expect(byName.get("projects_list").description).toMatch(/node (?:\(Agent\) )?tokens can only read projects/i);
|
|
217
|
-
for (const name of ["projects_create", "projects_update"]) expect(human.get(name).description).toMatch(/node (?:\(Agent\) )?tokens can only read projects/i);
|
|
216
|
+
expect(byName.get("projects_list").description).toMatch(/node (?:\(Agent\) )?tokens (?:can only read projects|read only)/i);
|
|
217
|
+
for (const name of ["projects_create", "projects_update"]) expect(human.get(name).description).toMatch(/node (?:\(Agent\) )?tokens (?:can only read projects|read only)/i);
|
|
218
218
|
const denied = await mcp(U.nodeA.token, "projects_create", { name: "示例项目" });
|
|
219
219
|
expect(denied.status).toBe(403);
|
|
220
220
|
expect(denied.error).toBe("user_token_required");
|
package/src/requirements.ts
CHANGED
|
@@ -14,6 +14,7 @@ import { aggregateStats, parseStatsQuery, type StatsRow } from "./requirements-s
|
|
|
14
14
|
import { addHumanNetworkScope, canRestWriteNetwork, canRestWriteNetworkAsHuman, resolveRestWriteNetworkId, type RestNetworkScope } from "./network-scope.js";
|
|
15
15
|
import { isAgentRestricted, restrictedNetworkIds, visibleAgents } from "./agent-access.js";
|
|
16
16
|
import { nodeDecide, nodeIdentity, nodePermissionDeniedBody, nodePermissionsFlag, type NodeIdentity, type Verdict } from "./node-permissions.js";
|
|
17
|
+
import { boardGrantForCard, boardScopeForNode } from "./node-grants.js";
|
|
17
18
|
import {
|
|
18
19
|
addProjectVisibilityScope, addTaskVisibilityScope, canDeleteTask, canEditTask, deletesAsHeadOnly, headOnlyEditScope, canParticipantEditTask, canSeeTask, canUseProject, deleteTaskGrantsForProject, projectUseResolver,
|
|
19
20
|
cardAssignedToNode, isTaskScoped, PARTICIPANT_EDIT_FIELDS, shouldAuditDenied, taskPermissionsResolver, type TaskCaller,
|
|
@@ -149,8 +150,13 @@ function nodeIdent(ctx: RequirementsRequestContext): NodeIdentity | null {
|
|
|
149
150
|
function nodeTaskCaller(ctx: RequirementsRequestContext): TaskCaller {
|
|
150
151
|
const id = nodeIdent(ctx);
|
|
151
152
|
if (!id?.ownerUserId) return null;
|
|
152
|
-
|
|
153
|
-
|
|
153
|
+
// 第二期 board:只有「这个节点**确实有** board 授权」时才带上额外范围。
|
|
154
|
+
// 没授权的节点返回 null / 原样对象 ⇒ 可见性 SQL 逐字节不变。
|
|
155
|
+
const board = id.networkId ? boardScopeForNode(id.networkId, id.logKey) : null;
|
|
156
|
+
if (id.mode === "restricted") return { userId: id.ownerUserId, node: { id: id.logKey, only: true }, ...(board ? { board } : {}) };
|
|
157
|
+
if (nodePermissionsFlag() === "enforce") return { userId: id.ownerUserId, node: { id: id.logKey, only: false }, ...(board ? { board } : {}) };
|
|
158
|
+
// 影子模式(默认 log / 未开 enforce):本来就不收窄可见性,节点看到的就是全部卡 ——
|
|
159
|
+
// 这时再挂 board 只会把范围**收窄**到「主人 + 授权」,违反「授权只加不减」。所以这里保持原来的 null。
|
|
154
160
|
return null;
|
|
155
161
|
}
|
|
156
162
|
|
|
@@ -162,6 +168,18 @@ function nodeTaskGate(ctx: RequirementsRequestContext, route: string, row: Row |
|
|
|
162
168
|
const id = nodeIdent(ctx);
|
|
163
169
|
if (!id) return null;
|
|
164
170
|
const sample = row ? `#${row.seq ?? "?"} ${row.requirement_id}` : create?.projectId ?? undefined;
|
|
171
|
+
// 第二期 board:这一刀只管「改已有卡」。boardGrantForCard 已把 readonly 模式的 edit 降成 read,
|
|
172
|
+
// 所以这里拿到 "edit" 就说明真的可写;read 不放行(只读不能改)。
|
|
173
|
+
if (row && id.networkId) {
|
|
174
|
+
const level = boardGrantForCard(id.networkId, id.logKey, row, id.mode);
|
|
175
|
+
if (level === "edit") {
|
|
176
|
+
try {
|
|
177
|
+
logAudit(id.ownerUserId, id.aliases[0] ?? id.nodeId, "requirement_changed_via_node_grant", "requirement",
|
|
178
|
+
row.requirement_id, JSON.stringify({ route, node_id: id.nodeId }), undefined, id.networkId);
|
|
179
|
+
} catch { /* 审计失败不挡写入 */ }
|
|
180
|
+
return null;
|
|
181
|
+
}
|
|
182
|
+
}
|
|
165
183
|
let verdict: Verdict = null;
|
|
166
184
|
if (id.mode === "readonly") verdict = { reason: "mode_readonly", sample };
|
|
167
185
|
else if (id.mode === "restricted") {
|
|
@@ -178,6 +196,13 @@ function nodeTaskGate(ctx: RequirementsRequestContext, route: string, row: Row |
|
|
|
178
196
|
return nodeDecide(id, route, verdict) ? Response.json(nodePermissionDeniedBody(verdict!.reason, route), { status: 403 }) : null;
|
|
179
197
|
}
|
|
180
198
|
|
|
199
|
+
/** 第二期 board:这个节点经授权可写这张卡(edit 级;readonly 模式在 boardGrantForCard 里已降成 read)。 */
|
|
200
|
+
function nodeBoardEdit(ctx: RequirementsRequestContext, row: Row): boolean {
|
|
201
|
+
const id = nodeIdent(ctx);
|
|
202
|
+
if (!id?.networkId) return false;
|
|
203
|
+
return boardGrantForCard(id.networkId, id.logKey, row, id.mode) === "edit";
|
|
204
|
+
}
|
|
205
|
+
|
|
181
206
|
/** 正常模式的节点读到了主人看不见的卡:只记录(执行时 taskCaller 已按主人收窄,读不到)。主人不受任务范围限制时什么都不做。 */
|
|
182
207
|
function nodeReadNote(ctx: RequirementsRequestContext, route: string, row: Row | null): void {
|
|
183
208
|
const id = nodeIdent(ctx);
|
|
@@ -1239,7 +1264,7 @@ function patchRequirement(ctx: RequirementsRequestContext, row: Row, body: Recor
|
|
|
1239
1264
|
const nodeDenied = nodeTaskGate(ctx, "PATCH /api/requirements/:id", row);
|
|
1240
1265
|
if (nodeDenied) return nodeDenied;
|
|
1241
1266
|
const caller = taskCaller(ctx);
|
|
1242
|
-
if (!canEditTask(caller, row)) {
|
|
1267
|
+
if (!canEditTask(caller, row) && !nodeBoardEdit(ctx, row)) {
|
|
1243
1268
|
// 参与人:只放状态和检查项;别的字段点名拒绝。不是参与人 → 与今天一样。
|
|
1244
1269
|
if (!canParticipantEditTask(caller, row)) return taskDenied(ctx, row, "task_read_only");
|
|
1245
1270
|
const other = PATCH_FIELDS.find(k => has(k) && !PARTICIPANT_EDIT_FIELDS.includes(k));
|
|
@@ -2142,7 +2167,7 @@ async function handleRequirementsRequestInner(ctx: RequirementsRequestContext):
|
|
|
2142
2167
|
if (!canWrite(ctx, row.network_id)) return jsonError("permission_denied", 403);
|
|
2143
2168
|
const nodeDenied = nodeTaskGate(ctx, "PATCH /api/requirements/:id/checklist/:id", row);
|
|
2144
2169
|
if (nodeDenied) return nodeDenied;
|
|
2145
|
-
if (!canEditTask(taskCaller(ctx), row) && !canParticipantEditTask(taskCaller(ctx), row)) return taskDenied(ctx, row, "task_read_only");
|
|
2170
|
+
if (!canEditTask(taskCaller(ctx), row) && !canParticipantEditTask(taskCaller(ctx), row) && !nodeBoardEdit(ctx, row)) return taskDenied(ctx, row, "task_read_only");
|
|
2146
2171
|
// 读-改-写在同一个同步段里完成(中间没有 await),同一进程里的两次勾选不会交错。
|
|
2147
2172
|
const items = storedChecklist(row.checklist_json);
|
|
2148
2173
|
const itemId = decodeURIComponent(itemMatch[2]);
|
package/src/schedule-agent.ts
CHANGED
|
@@ -27,6 +27,8 @@ import {
|
|
|
27
27
|
} from "./scheduled-tasks.js";
|
|
28
28
|
import { SCHEDULED_TASK_STORAGE_SELECT } from "./rest-projections.js";
|
|
29
29
|
import { dispatchVerdict, nodePermissionDeniedBody, recordNodePermission, type NodeIdentity } from "./node-permissions.js";
|
|
30
|
+
import { grantLevelForTarget, hasAnyGrant } from "./node-grants.js";
|
|
31
|
+
import { logAudit } from "./db.js";
|
|
30
32
|
|
|
31
33
|
export type AgentScheduleResult = Record<string, unknown> & { ok: boolean };
|
|
32
34
|
|
|
@@ -40,7 +42,9 @@ const fail = (error: string, extra: Record<string, unknown> = {}): AgentSchedule
|
|
|
40
42
|
/** The scope rule. Exported so the mutation tests can pin it. */
|
|
41
43
|
export function nodeMaySeeSchedule(id: NodeIdentity, row: ScheduledRow): boolean {
|
|
42
44
|
if (!id.nodeId || row.network_id !== id.networkId) return false;
|
|
43
|
-
|
|
45
|
+
if (row.target_node_id === id.nodeId || row.created_by_node_id === id.nodeId) return true;
|
|
46
|
+
// 节点管理授权(node-grants.ts):能力 schedules,按目标节点判范围;read / edit 都能看。
|
|
47
|
+
return grantLevelForTarget(id.networkId, id.nodeId, "schedules", row.target_node_id, id.mode) !== null;
|
|
44
48
|
}
|
|
45
49
|
|
|
46
50
|
function visibleRow(id: NodeIdentity, scheduleId: string): ScheduledRow | null {
|
|
@@ -50,12 +54,23 @@ function visibleRow(id: NodeIdentity, scheduleId: string): ScheduledRow | null {
|
|
|
50
54
|
|
|
51
55
|
/** Visible AND created by this node; else the error to return. Exported for the mutation tests. */
|
|
52
56
|
export function nodeMayMutateSchedule(id: NodeIdentity, row: ScheduledRow): boolean {
|
|
53
|
-
|
|
57
|
+
if (!id.nodeId) return false;
|
|
58
|
+
if (row.created_by_node_id === id.nodeId) return true;
|
|
59
|
+
return grantLevelForTarget(id.networkId, id.nodeId, "schedules", row.target_node_id, id.mode) === "edit";
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** 经授权(不是自己建的)改了一条计划:记一行审计,主人在报表里看得到是哪个节点改的。 */
|
|
63
|
+
function auditGrantMutation(id: NodeIdentity, row: ScheduledRow, action: string): void {
|
|
64
|
+
if (!id.nodeId || row.created_by_node_id === id.nodeId) return;
|
|
65
|
+
try {
|
|
66
|
+
logAudit(id.ownerUserId, id.aliases[0] ?? id.nodeId, "schedule_changed_via_node_grant", "scheduled_task", row.schedule_id,
|
|
67
|
+
JSON.stringify({ action, node_id: id.nodeId, target_node_id: row.target_node_id }), undefined, id.networkId);
|
|
68
|
+
} catch { /* 审计失败不挡写入 */ }
|
|
54
69
|
}
|
|
55
70
|
function ownRow(id: NodeIdentity, scheduleId: string): ScheduledRow | AgentScheduleResult {
|
|
56
71
|
const row = visibleRow(id, scheduleId);
|
|
57
72
|
if (!row) return fail("schedule_not_found");
|
|
58
|
-
if (!nodeMayMutateSchedule(id, row)) return fail("not_schedule_creator", { message: "only schedules this node created can be changed" });
|
|
73
|
+
if (!nodeMayMutateSchedule(id, row)) return fail("not_schedule_creator", { message: "only schedules this node created (or that an edit grant covers) can be changed" });
|
|
59
74
|
return row;
|
|
60
75
|
}
|
|
61
76
|
const isRow = (r: ScheduledRow | AgentScheduleResult): r is ScheduledRow => typeof (r as ScheduledRow).schedule_id === "string";
|
|
@@ -83,10 +98,20 @@ function inputError(e: any): AgentScheduleResult {
|
|
|
83
98
|
export function agentListSchedules(id: NodeIdentity, status?: string): AgentScheduleResult {
|
|
84
99
|
if (!id.nodeId) return fail("node_identity_unbound");
|
|
85
100
|
const params: unknown[] = [id.networkId, id.nodeId];
|
|
86
|
-
|
|
101
|
+
// 有 schedules 授权时扫全网(上限 500)再按授权逐条判;没有授权走原来的窄查询。
|
|
102
|
+
const granted = hasAnyGrant(id.networkId, id.nodeId, "schedules");
|
|
103
|
+
let sql = granted
|
|
104
|
+
? `SELECT ${SCHEDULED_TASK_STORAGE_SELECT} FROM scheduled_tasks WHERE network_id = ?1 AND ?2 = ?2`
|
|
105
|
+
: `SELECT ${SCHEDULED_TASK_STORAGE_SELECT} FROM scheduled_tasks WHERE network_id = ?1 AND (target_node_id = ?2 OR created_by_node_id = ?2)`;
|
|
87
106
|
if (status) { sql += " AND status = ?3"; params.push(status); }
|
|
88
|
-
sql += " ORDER BY updated_at DESC LIMIT 200";
|
|
89
|
-
const
|
|
107
|
+
sql += granted ? " ORDER BY updated_at DESC LIMIT 500" : " ORDER BY updated_at DESC LIMIT 200";
|
|
108
|
+
const rawRows = db.all<ScheduledRow>(sql, ...params);
|
|
109
|
+
const rows = (granted ? rawRows.filter(r => nodeMaySeeSchedule(id, r)) : rawRows).map(decodeRowForAgent);
|
|
110
|
+
if (granted) for (const r of rows) {
|
|
111
|
+
const raw = rawRows.find(x => x.schedule_id === (r as Record<string, unknown>).schedule_id);
|
|
112
|
+
if (raw) (r as Record<string, unknown>).access = raw.created_by_node_id === id.nodeId || raw.target_node_id === id.nodeId
|
|
113
|
+
? "own" : nodeMayMutateSchedule(id, raw) ? "grant_edit" : "grant_read";
|
|
114
|
+
}
|
|
90
115
|
// #2935 —— 「周期比单轮工作耗时短」的排程会**永久 skip**:退避只会让它更稀疏,追不上。
|
|
91
116
|
// 数据是现成的(scheduled_task_runs 的 completed_at - created_at),只是以前没人给出来。
|
|
92
117
|
// 这里只**报数**,不改任何调度行为。
|
|
@@ -197,10 +222,16 @@ export function agentUpdateSchedule(id: NodeIdentity, canWrite: boolean, schedul
|
|
|
197
222
|
if (!node?.alias) return fail("target_node_not_found");
|
|
198
223
|
target = { node_id: node.node_id, alias: node.alias };
|
|
199
224
|
}
|
|
200
|
-
|
|
201
|
-
|
|
225
|
+
// 经授权改别人建的计划、且不改目标:不再要求本节点能给目标 send_task(每次执行仍按建计划者复查)。
|
|
226
|
+
// 改目标 / 改自己建的:照旧走 send_task 的判定。
|
|
227
|
+
const viaGrant = row.created_by_node_id !== id.nodeId;
|
|
228
|
+
if (!viaGrant || retarget) {
|
|
229
|
+
const denied = targetDenied(id, route, target);
|
|
230
|
+
if (denied) return denied;
|
|
231
|
+
}
|
|
202
232
|
try {
|
|
203
233
|
const patched = patchSchedule(row, { ...body, revision: body.revision ?? row.revision }, id.ownerUserId);
|
|
234
|
+
auditGrantMutation(id, row, retarget ? "update_retarget" : "update");
|
|
204
235
|
return { ok: true, schedule: decodeRowForAgent(patched) };
|
|
205
236
|
} catch (e) { return inputError(e); }
|
|
206
237
|
}
|
|
@@ -230,6 +261,7 @@ export function agentCancelSchedule(id: NodeIdentity, canWrite: boolean, schedul
|
|
|
230
261
|
const row = ownRow(id, scheduleId);
|
|
231
262
|
if (!isRow(row)) return row;
|
|
232
263
|
cancelSchedule(row);
|
|
264
|
+
auditGrantMutation(id, row, "cancel");
|
|
233
265
|
return { ok: true, status: "cancelled" };
|
|
234
266
|
}
|
|
235
267
|
|
|
@@ -240,10 +272,13 @@ export function agentRunScheduleNow(id: NodeIdentity, canWrite: boolean, schedul
|
|
|
240
272
|
const row = ownRow(id, scheduleId);
|
|
241
273
|
if (!isRow(row)) return row;
|
|
242
274
|
if (row.status === "cancelled") return fail("schedule_cancelled");
|
|
243
|
-
|
|
244
|
-
|
|
275
|
+
if (row.created_by_node_id === id.nodeId) {
|
|
276
|
+
const denied = targetDenied(id, route, { node_id: row.target_node_id, alias: row.target_alias });
|
|
277
|
+
if (denied) return denied;
|
|
278
|
+
}
|
|
245
279
|
try {
|
|
246
280
|
const result = dispatchScheduledOccurrence(row, new Date().toISOString(), false);
|
|
281
|
+
auditGrantMutation(id, row, "run_now");
|
|
247
282
|
const { event: _event, ...rest } = result;
|
|
248
283
|
return { ok: result.status !== "failed", ...rest };
|
|
249
284
|
} catch (e: any) {
|
|
@@ -636,6 +636,31 @@ describe("Hub scheduled task API and dispatcher", () => {
|
|
|
636
636
|
expect(runs.body.runs.length).toBeGreaterThanOrEqual(4);
|
|
637
637
|
});
|
|
638
638
|
|
|
639
|
+
test("purge deletes a stopped schedule with its runs; active ones and viewers are refused", async () => {
|
|
640
|
+
const q = `?network_id=${encodeURIComponent(networkId)}`;
|
|
641
|
+
const schedule = await createSchedule("purge me");
|
|
642
|
+
makeDue(schedule.schedule_id);
|
|
643
|
+
await runDueScheduledTasks(new Date());
|
|
644
|
+
expect(db.get<{ n: number }>("SELECT COUNT(*) AS n FROM scheduled_task_runs WHERE schedule_id = ?1", schedule.schedule_id)!.n).toBeGreaterThan(0);
|
|
645
|
+
// 还在跑的不让直接删:先 cancel。
|
|
646
|
+
const early = await api(ownerToken, `/api/scheduled-tasks/${schedule.schedule_id}/purge${q}`, { method: "POST", body: "{}" });
|
|
647
|
+
expect(early.status).toBe(409);
|
|
648
|
+
expect(early.body.error).toBe("schedule_not_stopped");
|
|
649
|
+
await api(ownerToken, `/api/scheduled-tasks/${schedule.schedule_id}/cancel${q}`, { method: "POST", body: "{}" });
|
|
650
|
+
// viewer 不能删(与 cancel 同一判据)。
|
|
651
|
+
const viewer = await api(viewerToken, `/api/scheduled-tasks/${schedule.schedule_id}/purge${q}`, { method: "POST", body: "{}" });
|
|
652
|
+
expect(viewer.status).toBe(403);
|
|
653
|
+
const purged = await api(ownerToken, `/api/scheduled-tasks/${schedule.schedule_id}/purge${q}`, { method: "POST", body: "{}" });
|
|
654
|
+
expect(purged.status).toBe(200);
|
|
655
|
+
expect(purged.body.status).toBe("purged");
|
|
656
|
+
expect((await api(ownerToken, `/api/scheduled-tasks/${schedule.schedule_id}${q}`)).status).toBe(404);
|
|
657
|
+
expect(db.get<{ n: number }>("SELECT COUNT(*) AS n FROM scheduled_task_runs WHERE schedule_id = ?1", schedule.schedule_id)!.n).toBe(0);
|
|
658
|
+
const listed = await api(ownerToken, `/api/scheduled-tasks${q}`);
|
|
659
|
+
expect(listed.body.schedules.some((r: any) => r.schedule_id === schedule.schedule_id)).toBe(false);
|
|
660
|
+
// 再删一次 = 404(行已经没了)。
|
|
661
|
+
expect((await api(ownerToken, `/api/scheduled-tasks/${schedule.schedule_id}/purge${q}`, { method: "POST", body: "{}" })).status).toBe(404);
|
|
662
|
+
});
|
|
663
|
+
|
|
639
664
|
test("a watcher can edit the schedule but cannot cancel it or change watchers", async () => {
|
|
640
665
|
const viewerId = db.get<{ user_id: string }>("SELECT user_id FROM network_members WHERE network_id = ?1 AND role = 'viewer'", networkId)!.user_id;
|
|
641
666
|
const schedule = await createSchedule(`watchers-${Date.now()}`);
|
package/src/scheduled-tasks.ts
CHANGED
|
@@ -6,10 +6,12 @@ import { sessionTaskOnDispatch } from "./session-task-on-dispatch.js";
|
|
|
6
6
|
import { TASK_CONTENT_MAX, sessionTaskPreview } from "./shared/task-content-limit.js";
|
|
7
7
|
import { assertNodeActive } from "./lifecycle-guard.js";
|
|
8
8
|
import { assertNodeHealthy } from "./node-health-guard.js";
|
|
9
|
+
import { neverConsumeGate, neverConsumedExpiryCounters, persistentNeverConsumedExpiries } from "./expiry-counters.js";
|
|
10
|
+
import { db as hubDb } from "./db.js";
|
|
9
11
|
import { nodeCanAcceptDispatch } from "./node-serviceability.js";
|
|
10
12
|
import { addNetworkScope, canRestWriteNetwork, singleNetworkId, type RestNetworkScope } from "./network-scope.js";
|
|
11
13
|
import { canMessageAgent, type AgentRef } from "./agent-access.js";
|
|
12
|
-
import { dispatchVerdict } from "./node-permissions.js";
|
|
14
|
+
import { dispatchVerdict, inboxDenied, type InboxSender } from "./node-permissions.js";
|
|
13
15
|
import { hasSubscribers, pushEvent, pushNetworkObserverEvent } from "./push.js";
|
|
14
16
|
import { SCHEDULED_TASK_STORAGE_SELECT } from "./rest-projections.js";
|
|
15
17
|
import { blockerTimedOut, blockerTimeoutClock, expireStuckBlocker, sendStuckNotice, skipsBlockedBy, stuckNoticeSkips, stuckTimeoutMs, type StuckNotice } from "./scheduled-stuck.js";
|
|
@@ -263,6 +265,15 @@ export function insertSchedule(networkId: string, createdBy: string | null, crea
|
|
|
263
265
|
}
|
|
264
266
|
|
|
265
267
|
/** Idempotent cancel (shared by REST DELETE / POST cancel and MCP schedule_cancel). */
|
|
268
|
+
/** 真删一条已停下的计划(见 purge 路由)。三张表一个事务。 */
|
|
269
|
+
export function purgeSchedule(scheduleId: string): void {
|
|
270
|
+
db.transaction(() => {
|
|
271
|
+
db.run("DELETE FROM scheduled_task_watchers WHERE schedule_id = ?1", [scheduleId]);
|
|
272
|
+
db.run("DELETE FROM scheduled_task_runs WHERE schedule_id = ?1", [scheduleId]);
|
|
273
|
+
db.run("DELETE FROM scheduled_tasks WHERE schedule_id = ?1", [scheduleId]);
|
|
274
|
+
});
|
|
275
|
+
}
|
|
276
|
+
|
|
266
277
|
export function cancelSchedule(row: ScheduledRow): void {
|
|
267
278
|
if (row.status === "cancelled") return;
|
|
268
279
|
db.run("UPDATE scheduled_tasks SET status = 'cancelled', next_run_at = NULL, backoff_streak = 0, backoff_effective_seconds = NULL, backoff_last_run_id = NULL, revision = revision + 1, updated_at = datetime('now') WHERE schedule_id = ?1", [row.schedule_id]);
|
|
@@ -403,6 +414,22 @@ function agentCreatorDenial(row: ScheduledRow, target: AgentRef): { code: string
|
|
|
403
414
|
return null;
|
|
404
415
|
}
|
|
405
416
|
|
|
417
|
+
/** 目标节点的收件白名单每次触发都按「建排程的人 / 节点」现判一次(名单可能在排程建好之后才设)。 */
|
|
418
|
+
function creatorInboxDenial(row: ScheduledRow, target: AgentRef): { code: string; message: string } | null {
|
|
419
|
+
let sender: InboxSender;
|
|
420
|
+
if (row.created_by_node_id) {
|
|
421
|
+
const alias = db.get<{ alias: string | null }>("SELECT alias FROM nodes WHERE node_id = ?1 AND network_id = ?2", row.created_by_node_id, row.network_id)?.alias;
|
|
422
|
+
sender = { kind: "node", nodeId: row.created_by_node_id, aliases: alias ? [alias] : [] };
|
|
423
|
+
} else if (row.created_by) {
|
|
424
|
+
const user = db.get<{ username: string | null; role: string | null }>("SELECT username, role FROM users WHERE user_id = ?1", row.created_by);
|
|
425
|
+
sender = { kind: "user", userId: row.created_by, username: user?.username ?? null, isHubAdmin: user?.role === "admin" };
|
|
426
|
+
} else {
|
|
427
|
+
sender = { kind: "legacy" };
|
|
428
|
+
}
|
|
429
|
+
const denial = inboxDenied(row.network_id, target, sender, "schedule:dispatch");
|
|
430
|
+
return denial ? { code: "sender_not_allowed", message: `The target agent's inbox allowlist does not accept the schedule creator (${denial.sender})` } : null;
|
|
431
|
+
}
|
|
432
|
+
|
|
406
433
|
type DispatchEvent = { alias: string; networkId: string; taskId: string; priority: string; state: "delivered" | "queued" };
|
|
407
434
|
|
|
408
435
|
export function dispatchScheduledOccurrence(row: ScheduledRow, scheduledFor: string, advanceSchedule: boolean, advanceAfter = new Date()): { runId: string; taskId?: string; status: string; event?: DispatchEvent } {
|
|
@@ -574,11 +601,11 @@ export function dispatchScheduledOccurrence(row: ScheduledRow, scheduledFor: str
|
|
|
574
601
|
// 给目标 Agent 发任务时,不再代他派发(否则受限前建的排程会永远绕过授权)。
|
|
575
602
|
// Board #733 — an Agent-created schedule is that node's standing send_task: every run re-evaluates the
|
|
576
603
|
// creating node as it is NOW (exists, not read-only, current owner) with send_task's own dispatchVerdict.
|
|
577
|
-
const creatorDenial = row.created_by_node_id
|
|
604
|
+
const creatorDenial = (row.created_by_node_id
|
|
578
605
|
? agentCreatorDenial(row, { alias: node.alias, nodeId: node.node_id })
|
|
579
606
|
: row.created_by && !canMessageAgent(row.created_by, row.network_id, { alias: node.alias, nodeId: node.node_id })
|
|
580
607
|
? { code: "creator_access_revoked", message: "The schedule creator is no longer allowed to message this agent" }
|
|
581
|
-
: null;
|
|
608
|
+
: null) ?? creatorInboxDenial(row, { alias: node.alias, nodeId: node.node_id });
|
|
582
609
|
if (creatorDenial) {
|
|
583
610
|
finalStatus = "failed";
|
|
584
611
|
db.run(
|
|
@@ -633,6 +660,29 @@ export function dispatchScheduledOccurrence(row: ScheduledRow, scheduledFor: str
|
|
|
633
660
|
return;
|
|
634
661
|
}
|
|
635
662
|
|
|
663
|
+
// #4307/#4315 —— **排程派单也必须过这道闸**。
|
|
664
|
+
// 不然「某节点长期不消费」会被排程一遍遍喂任务:每一条都过期成 expired,
|
|
665
|
+
// 反过来把 never-consume 的计数顶得更高(实测 TMW微软欧 144/145 条 expired 全是
|
|
666
|
+
// 从未 consume 的排程任务)。REST 与 MCP 两个派单面本来就要同形,这里是第三个面。
|
|
667
|
+
// 判据完全相同:只看「最后一次成功回复之后」的过期;命中就 skip,不写任务行。
|
|
668
|
+
{
|
|
669
|
+
const gate = neverConsumeGate({
|
|
670
|
+
alias: node.alias,
|
|
671
|
+
counters: neverConsumedExpiryCounters(),
|
|
672
|
+
force: false,
|
|
673
|
+
forceAllowed: false,
|
|
674
|
+
persistent: persistentNeverConsumedExpiries(hubDb, node.alias, row.network_id),
|
|
675
|
+
});
|
|
676
|
+
if (!gate.ok) {
|
|
677
|
+
db.run(
|
|
678
|
+
"UPDATE scheduled_task_runs SET status = 'skipped', error_code = 'target_never_consumes', error_message = ?1, completed_at = datetime('now') WHERE run_id = ?2",
|
|
679
|
+
[gate.message.slice(0, 500), runId],
|
|
680
|
+
);
|
|
681
|
+
if (advanceSchedule) advance(row, scheduledFor, advanceAfter);
|
|
682
|
+
return;
|
|
683
|
+
}
|
|
684
|
+
}
|
|
685
|
+
|
|
636
686
|
const taskId = crypto.randomUUID();
|
|
637
687
|
// claude-code 裸节点的 node-server 上报 report_status 不带 node_id,它的 sessions 行
|
|
638
688
|
// node_id 永远是 NULL —— 只按 node_id 找会话,这类节点每一次都判成 queued、门铃不响,
|
|
@@ -904,7 +954,7 @@ export async function handleScheduledTaskRequest(ctx: ScheduledRequestContext):
|
|
|
904
954
|
}
|
|
905
955
|
}
|
|
906
956
|
|
|
907
|
-
const match = url.pathname.match(/^\/api\/scheduled-tasks\/([^/]+)(?:\/(runs|run-now|cancel))?$/);
|
|
957
|
+
const match = url.pathname.match(/^\/api\/scheduled-tasks\/([^/]+)(?:\/(runs|run-now|cancel|purge))?$/);
|
|
908
958
|
if (!match) return jsonError("not_found", 404);
|
|
909
959
|
const scheduleId = decodeURIComponent(match[1]);
|
|
910
960
|
const sub = match[2] || null;
|
|
@@ -919,7 +969,7 @@ export async function handleScheduledTaskRequest(ctx: ScheduledRequestContext):
|
|
|
919
969
|
const watcher = watchingSchedule(row.schedule_id, ctx.auth?.userId ?? null);
|
|
920
970
|
const writer = writeAllowed(ctx, row.network_id);
|
|
921
971
|
if (!writer && !watcher) return jsonError("permission_denied", 403);
|
|
922
|
-
if (!writer && (sub === "cancel" || (!sub && req.method === "DELETE"))) return jsonError("watcher_cannot_cancel", 403);
|
|
972
|
+
if (!writer && (sub === "cancel" || sub === "purge" || (!sub && req.method === "DELETE"))) return jsonError("watcher_cannot_cancel", 403);
|
|
923
973
|
if (!writer && sub === "run-now") return jsonError("watcher_cannot_run", 403);
|
|
924
974
|
|
|
925
975
|
if (sub === "run-now" && req.method === "POST") {
|
|
@@ -947,6 +997,16 @@ export async function handleScheduledTaskRequest(ctx: ScheduledRequestContext):
|
|
|
947
997
|
return Response.json({ ok: true, status: "cancelled" });
|
|
948
998
|
}
|
|
949
999
|
|
|
1000
|
+
// Purge(admin 2026-11-11「没有删除定时任务的功能」)—— 真删:计划行 + 执行记录 + 关注人一起删掉,
|
|
1001
|
+
// 列表里不再出现。只删已经停下的计划(cancelled / completed);还在跑的先 cancel 再 purge,
|
|
1002
|
+
// 避免一次误点把正在派发的计划连同历史一起抹掉。已派出去的 task 行不动(那是节点收件箱的历史)。
|
|
1003
|
+
// 不存在 = 404(上面 scopedSchedule 已判);重复 purge 的第二次也就是 404。
|
|
1004
|
+
if (sub === "purge" && (req.method === "POST" || req.method === "DELETE")) {
|
|
1005
|
+
if (row.status !== "cancelled" && row.status !== "completed") return jsonError("schedule_not_stopped", 409, { status: row.status });
|
|
1006
|
+
purgeSchedule(row.schedule_id);
|
|
1007
|
+
return Response.json({ ok: true, status: "purged", schedule_id: row.schedule_id });
|
|
1008
|
+
}
|
|
1009
|
+
|
|
950
1010
|
if (!sub && req.method === "PATCH") {
|
|
951
1011
|
let body: Record<string, unknown>;
|
|
952
1012
|
try { body = await bodyObject(req); } catch { return jsonError("invalid_json", 400); }
|