@sema-agent/server 3.20.0 → 3.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/dist/approval-hmac.d.ts +9 -9
  2. package/dist/approval-hmac.js +0 -31
  3. package/dist/approval.js +8 -1
  4. package/dist/boot/config-center.d.ts +3 -2
  5. package/dist/boot/resolve-spec.js +4 -4
  6. package/dist/boot/session-faces.js +3 -2
  7. package/dist/boot/workflow-orchestration.js +1 -1
  8. package/dist/budget.d.ts +2 -2
  9. package/dist/budget.js +11 -6
  10. package/dist/fleet/fleet-bus.d.ts +2 -0
  11. package/dist/fleet/fleet-bus.js +34 -7
  12. package/dist/hooks/hook-llm.d.ts +2 -2
  13. package/dist/hooks/hook-llm.js +1 -1
  14. package/dist/http/active-run-conflict.d.ts +68 -0
  15. package/dist/http/active-run-conflict.js +89 -0
  16. package/dist/http/principal-gate.d.ts +7 -3
  17. package/dist/http/principal-gate.js +7 -5
  18. package/dist/http/route-ctx.d.ts +34 -25
  19. package/dist/http/routes/approvals-assistant.js +5 -5
  20. package/dist/http/routes/images.js +8 -8
  21. package/dist/http/routes/runs.js +3 -1
  22. package/dist/http/routes/tasks.js +5 -3
  23. package/dist/http/server.d.ts +2 -2
  24. package/dist/http/server.js +2 -2
  25. package/dist/key-resolver.d.ts +7 -1
  26. package/dist/key-resolver.js +0 -23
  27. package/dist/leader/wire.d.ts +19 -1
  28. package/dist/leader/wire.js +48 -18
  29. package/dist/main.js +2 -2
  30. package/dist/parked-decide.js +4 -1
  31. package/dist/plugins/file-run-store.js +21 -8
  32. package/dist/plugins/host-platform.d.ts +11 -24
  33. package/dist/plugins/host-platform.js +14 -0
  34. package/dist/plugins/memory-engine-tidb.js +16 -0
  35. package/dist/plugins/memory-run-store.js +19 -8
  36. package/dist/plugins/remote-env-adb.js +12 -5
  37. package/dist/plugins/remote-env-local-docker.js +3 -7
  38. package/dist/plugins/remote-env-ssh.js +17 -2
  39. package/dist/plugins/run-store-sql.js +18 -12
  40. package/dist/plugins/store-backend.d.ts +1 -1
  41. package/dist/plugins/store-backend.js +2 -2
  42. package/dist/plugins/tool-result-store-sql.d.ts +7 -1
  43. package/dist/plugins/tool-result-store-sql.js +9 -8
  44. package/dist/plugins/workflow-run-store-sql.d.ts +11 -6
  45. package/dist/plugins/workflow-run-store-sql.js +18 -8
  46. package/dist/session-sync.js +6 -3
  47. package/package.json +2 -2
@@ -22,6 +22,7 @@
22
22
  * ⚠️ The win32 branches are UNVERIFIED on a real machine until S5 (Windows CI runner) — design D5 discipline:
23
23
  * structural tests only on mac/Linux; behavior-level bite happens on the first Windows-runner green.
24
24
  */
25
+ import os from "node:os";
25
26
  import { getShellConfig, killProcessTree, signalProcessTree } from "@sema-agent/core";
26
27
  export const IS_WIN32 = process.platform === "win32";
27
28
  /** S1([1870] test AI 全归因,2026-07-27):POSIX 不再硬编码 `/bin/sh`——Debian/Ubuntu 的 /bin/sh 是
@@ -135,6 +136,19 @@ export function collapseWin32EnvKeys(env) {
135
136
  return env;
136
137
  return collapseEnvKeysCaseInsensitive(env);
137
138
  }
139
+ /**
140
+ * Conventional exit-code mapping for a process killed by a signal (128 + signal number). Single pattern-home
141
+ * construction point for every exec adapter that must turn a `close` event's external-kill case
142
+ * (`code===null`, `signal` set) into an exit code instead of silently reporting a fake success 0 — the host
143
+ * lane, ssh, adb, and local-docker all consume THIS function; none of them may hand-write their own signal
144
+ * table. Uses Node's authoritative platform table (`os.constants.signals`) rather than a hand-written list —
145
+ * a hand-written table has previously missed `SIGABRT`/`SIGPIPE` (`kill -ABRT` reported 137, impersonating
146
+ * `SIGKILL`). Callers keep a `?? 9` fallback for a name the platform table doesn't define, matching core's
147
+ * `SIGNUM[signal] ?? 9`.
148
+ */
149
+ export function signalNumber(signal) {
150
+ return os.constants.signals[signal];
151
+ }
138
152
  /** The platform-free collapse algorithm (exported so the mac/Linux suite can pin the win32 behavior — design
139
153
  * D5: structural verification everywhere, behavioral bite on the Windows runner). */
140
154
  export function collapseEnvKeysCaseInsensitive(env) {
@@ -23,6 +23,7 @@
23
23
  // (`${name ?? slug} ${description} ${body}`——memoryBackendContract 的 search 等价断言依赖)。
24
24
  import { jaccardDistance, termSet } from "./memory-engine-vector-util.js";
25
25
  import { computeEntryRev, serializeEntryFile } from "@sema-agent/core";
26
+ import { pgHasUnstorable } from "./pg-safe-json.js";
26
27
  /** Table names (single source) — SAME names as PG_MEMORY_ENGINE_TABLES (the two dialects never share
27
28
  * one database), deliberately DISJOINT from the legacy `agent_memory*` MemoryStore plane. */
28
29
  export const TIDB_MEMORY_ENGINE_TABLES = {
@@ -224,6 +225,15 @@ export class TiDBMemoryEngineBackend {
224
225
  report.conflicts.push({ op: "add", id: patch.id, reason: "add patch without an entry" });
225
226
  return;
226
227
  }
228
+ // Reject-not-rewrite for bytes SQL cannot store(Pg 版 applyOne add 分支同一守卫,复用同一
229
+ // pgHasUnstorable——不是重派生一份近似正则):NUL / 孤立 UTF-16 代理不是 PG 独有的病,mysql2/
230
+ // utf8mb4 对同样的字节没有 PG 的 22P05 fail-loud 报错,驱动或服务端会静默 mangle(丢字节/替换为
231
+ // U+FFFD 视驱动版本而定),写入侧不炸、读回侧才发现内容偏离——这比 PG 的写时报错更隐蔽。三后端
232
+ // (pg/tidb/local)必须对同一输入给出同一行为,否则同一份 sync 数据在不同部署形态下悄悄分叉。
233
+ if (pgHasUnstorable(entry.frontmatter) || pgHasUnstorable(entry.body) || pgHasUnstorable(entry.slug)) {
234
+ report.conflicts.push({ op: "add", id: entry.id, reason: "unstorable_bytes (utf8mb4 cannot store NUL/lone surrogates without mangling; strip them at the source — the store never rewrites content)" });
235
+ return;
236
+ }
227
237
  // Cross-scope add refusal (opus 审 C3,Pg 版同注): an add whose id already lives in a DIFFERENT
228
238
  // scope must not silently MOVE the row; same-scope re-add stays the idempotent overwrite.
229
239
  // One probe serves BOTH the E-02 guard and the cross-scope refusal (File/Pg parity).
@@ -369,6 +379,12 @@ export class TiDBMemoryEngineBackend {
369
379
  report.conflicts.push({ op: "update", id: patch.id, reason: "update patch without an entry" });
370
380
  return;
371
381
  }
382
+ // Same reject-not-rewrite guard as the add leg above(Pg 版 applyOne update 分支同一守卫)—
383
+ // an update carrying unstorable bytes must refuse before the CAS write, not mangle silently.
384
+ if (pgHasUnstorable(entry.frontmatter) || pgHasUnstorable(entry.body) || pgHasUnstorable(entry.slug)) {
385
+ report.conflicts.push({ op: "update", id: patch.id, reason: "unstorable_bytes (utf8mb4 cannot store NUL/lone surrogates without mangling; strip them at the source — the store never rewrites content)" });
386
+ return;
387
+ }
372
388
  const rev = computeEntryRev(entry);
373
389
  const res = await this.write(`UPDATE ${T} SET scope = ?, slug = ?, frontmatter = ?, body = ?, rev = ?, mtime_ms = ?, size_bytes = ?, embedding = NULL WHERE id = ? AND rev = ?`, [entry.scope, entry.slug, JSON.stringify(entry.frontmatter), entry.body, rev, this.clock(), Buffer.byteLength(serializeEntryFile(entry), "utf8"), entry.id, currentRev]);
374
390
  if (res.affectedRows === 0) {
@@ -127,8 +127,15 @@ export class MemoryRunStore {
127
127
  * [1.207 codex M1] 负向形漏 blocked/timeout);claim 释放保持无条件(幂等)。 */
128
128
  async setTerminal(taskId, status, result, error) {
129
129
  const r = this.runs.get(taskId);
130
- if (!r)
130
+ if (!r) {
131
+ // [2255]③ file 孪生同判据(parity oracle):行缺席时终局动词仍放锁(反查 active)。
132
+ for (const [sessionId, tid] of this.active)
133
+ if (tid === taskId) {
134
+ this.active.delete(sessionId);
135
+ break;
136
+ }
131
137
  return;
138
+ }
132
139
  if (r.status === "running" || r.status === "suspended" || r.status === "needs_review") {
133
140
  r.status = status;
134
141
  r.result = result;
@@ -184,9 +191,9 @@ export class MemoryRunStore {
184
191
  const cursorAt = opts.cursor ? Date.parse(opts.cursor.createdAt) : undefined;
185
192
  const rows = [...this.runs.values()]
186
193
  .filter((r) => (opts.status ? r.status === opts.status : true))
187
- .filter((r) => (opts.jobId ? r.jobId === opts.jobId : true))
188
- .filter((r) => (opts.source ? r.source === opts.source : true))
189
- .filter((r) => (opts.owner ? r.owner === opts.owner : true)) // exact (SQL `owner = ?`): a set owner excludes null-owner rows
194
+ .filter((r) => (opts.jobId !== undefined ? r.jobId === opts.jobId : true)) // "" is a valid exact jobId, not "no filter" (B10)
195
+ .filter((r) => (opts.source !== undefined ? r.source === opts.source : true)) // "" is a valid exact source, not "no filter" (B10)
196
+ .filter((r) => (opts.owner !== undefined ? r.owner === opts.owner : true)) // exact (SQL `owner = ?`): "" is a valid exact owner, not "no filter" (B10)
190
197
  .filter((r) => {
191
198
  if (cursorAt === undefined)
192
199
  return true;
@@ -200,8 +207,8 @@ export class MemoryRunStore {
200
207
  async listSessions(opts) {
201
208
  const bySession = new Map();
202
209
  for (const r of this.runs.values()) {
203
- if (opts.owner && r.owner !== opts.owner)
204
- continue; // exact owner filter (SQL `owner = ?`)
210
+ if (opts.owner !== undefined && r.owner !== opts.owner)
211
+ continue; // exact owner filter (SQL `owner = ?`); "" is a valid exact owner (B10)
205
212
  const arr = bySession.get(r.sessionId) ?? [];
206
213
  arr.push(r);
207
214
  bySession.set(r.sessionId, arr);
@@ -328,8 +335,10 @@ export class MemoryRunStore {
328
335
  */
329
336
  async reapSuspended(olderThanMs) {
330
337
  const probe = this.checkpointProbe;
331
- if (!probe)
338
+ if (!probe) {
339
+ this.releaseTerminalClaims();
332
340
  return 0;
341
+ } // [2255]③ claim 不变式维护不跟 probe 走
333
342
  const cutoff = Date.now() - olderThanMs;
334
343
  let reaped = 0;
335
344
  for (const r of this.runs.values()) {
@@ -358,8 +367,10 @@ export class MemoryRunStore {
358
367
  */
359
368
  async failSuspendedWithExpiredCheckpoint() {
360
369
  const probe = this.checkpointProbe;
361
- if (!probe)
370
+ if (!probe) {
371
+ this.releaseTerminalClaims();
362
372
  return 0;
373
+ } // [2255]③ claim 不变式维护不跟 probe 走
363
374
  let reaped = 0;
364
375
  for (const r of this.runs.values()) {
365
376
  if (r.status !== "suspended" && r.status !== "needs_review")
@@ -29,6 +29,7 @@ import os from "node:os";
29
29
  import fs from "node:fs/promises";
30
30
  import { spawn } from "node:child_process";
31
31
  import { shellQuote, armPipeDestroyGrace } from "./remote-shell.js";
32
+ import { signalNumber } from "./host-platform.js";
32
33
  import { FileError, ExecutionError, RemoteExecutionError, withRetry, RollingTailBuffer, markTruncated, } from "@sema-agent/core";
33
34
  import { fileErrorFromExec } from "./remote-env-file-error.js";
34
35
  import { createPosixShellFs } from "./posix-shell-fs.js";
@@ -234,13 +235,15 @@ export class RemoteAdbExecutionEnv {
234
235
  finished = true;
235
236
  signalReady();
236
237
  });
237
- child.on("close", (code) => {
238
+ child.on("close", (code, signal) => {
238
239
  if ((code ?? 0) !== 0 && isAdbTransportLost(stderrTail) && !failure) {
239
240
  // device transport died mid-stream — typed retryable, not a fake exit ([R78]#1)
240
241
  this.connected = false;
241
242
  failure = new RemoteExecutionError("transport_lost", `adb transport lost mid-stream: ${stderrTail.trim().slice(0, 200)}`);
242
243
  }
243
- exitCode = code ?? 0;
244
+ // code==null WITH a signal = the adb child was killed by an external signal (SIGKILL/OOM) — conventional
245
+ // 128+signo, NOT a fake success 0 ([R78]#2; the second `close` argument was dropped before this fix).
246
+ exitCode = code ?? (signal ? 128 + (signalNumber(signal) ?? 9) : 0);
244
247
  finished = true;
245
248
  signalReady();
246
249
  });
@@ -483,19 +486,23 @@ export class RemoteAdbExecutionEnv {
483
486
  opts?.onStderr?.(d.toString());
484
487
  });
485
488
  child.on("error", (e) => finish({ ok: false, error: new ExecutionError("spawn_error", `adb spawn failed (is '${this.cfg.adbPath}' installed?): ${e.message}`, e) }));
486
- child.on("close", (code) => {
489
+ child.on("close", (code, signal) => {
487
490
  if (forceSettleTimer)
488
491
  clearTimeout(forceSettleTimer); // `close` fired → pipes closed naturally; clear D5 grace
489
492
  const err = errBuf.result();
490
493
  const stderr = markTruncated(err.text, err.droppedBytes);
494
+ // code==null WITH a signal = the adb child was killed by an external signal (SIGKILL/OOM) —
495
+ // conventional 128+signo, NOT a fake success 0 ([R78]#2; the second `close` argument was dropped
496
+ // before this fix).
497
+ const exitCode = code ?? (signal ? 128 + (signalNumber(signal) ?? 9) : 0);
491
498
  if (binary) {
492
499
  // byte-exact: readBinaryFile decodes stdoutBytes; never truncate.
493
500
  const stdoutBytes = Buffer.concat(outBufs);
494
- finish(ok({ stdout: stdoutBytes.toString("utf8"), stderr, exitCode: code ?? 0, stdoutBytes: new Uint8Array(stdoutBytes) }));
501
+ finish(ok({ stdout: stdoutBytes.toString("utf8"), stderr, exitCode, stdoutBytes: new Uint8Array(stdoutBytes) }));
495
502
  }
496
503
  else {
497
504
  const out = outTail.result();
498
- finish(ok({ stdout: markTruncated(out.text, out.droppedBytes), stderr, exitCode: code ?? 0 }));
505
+ finish(ok({ stdout: markTruncated(out.text, out.droppedBytes), stderr, exitCode }));
499
506
  }
500
507
  });
501
508
  });
@@ -42,6 +42,7 @@ import fs from "node:fs/promises";
42
42
  import { spawn } from "node:child_process";
43
43
  import { randomBytes } from "node:crypto";
44
44
  import { shellQuote, armPipeDestroyGrace } from "./remote-shell.js";
45
+ import { signalNumber } from "./host-platform.js";
45
46
  import { FileError, ExecutionError, RemoteExecutionError, RollingTailBuffer, markTruncated, } from "@sema-agent/core";
46
47
  import { fileErrorFromExec, classifyFsStderr } from "./remote-env-file-error.js";
47
48
  import { createPosixShellFs } from "./posix-shell-fs.js";
@@ -290,7 +291,7 @@ export class RemoteLocalDockerExecutionEnv {
290
291
  child.on("close", (code, signal) => {
291
292
  if (finished)
292
293
  return;
293
- exitCode = code ?? (signal ? 128 + (signalNumber(signal) ?? 0) : 1);
294
+ exitCode = code ?? (signal ? 128 + (signalNumber(signal) ?? 9) : 1);
294
295
  finished = true;
295
296
  signalReady();
296
297
  });
@@ -586,7 +587,7 @@ export class RemoteLocalDockerExecutionEnv {
586
587
  clearTimeout(forceSettleTimer); // `close` fired → pipes closed naturally; clear D5 grace
587
588
  // A signal-killed process (external SIGKILL/OOM) has code===null → derive the conventional 128+signo
588
589
  // (parity with execStream + the host adapter); NEVER report a killed command as a success exitCode 0.
589
- const exitCode = code ?? (signal ? 128 + (signalNumber(signal) ?? 0) : 1);
590
+ const exitCode = code ?? (signal ? 128 + (signalNumber(signal) ?? 9) : 1);
590
591
  const err = errBuf.result();
591
592
  const stderr = markTruncated(err.text, err.droppedBytes);
592
593
  if (binary) {
@@ -664,11 +665,6 @@ function sanitizeId(id) {
664
665
  function errMsg(e) {
665
666
  return e instanceof Error ? e.message : String(e);
666
667
  }
667
- /** Conventional exit code for a process killed by a signal (128 + signal number); falls back to undefined. */
668
- function signalNumber(signal) {
669
- const table = { SIGHUP: 1, SIGINT: 2, SIGQUIT: 3, SIGKILL: 9, SIGTERM: 15, SIGSEGV: 11 };
670
- return table[signal];
671
- }
672
668
  /**
673
669
  * `ExecutionEnvFactory` for the TOC `local-docker` backend (DUAL-MODE-DESIGN §5). Wiring this onto a deployment
674
670
  * makes its agent run each task in a per-task container on the worker's OWN docker daemon (isolation:true,
@@ -22,6 +22,7 @@
22
22
  import path from "node:path";
23
23
  import { Client } from "ssh2";
24
24
  import { shellQuote, kindFromMode } from "./remote-shell.js";
25
+ import { signalNumber } from "./host-platform.js";
25
26
  import { createPosixShellFs } from "./posix-shell-fs.js";
26
27
  import { FileError, ExecutionError, RemoteExecutionError, withRetry, RollingTailBuffer, markTruncated, } from "@sema-agent/core";
27
28
  import { fileErrorFromExec } from "./remote-env-file-error.js";
@@ -31,6 +32,13 @@ const unsupported = (op) => ({
31
32
  ok: false,
32
33
  error: new RemoteExecutionError("unsupported", `${op} is not supported on an SSH target (real machine — not snapshotable; capabilities.suspendable=false)`),
33
34
  });
35
+ /** ssh2's ClientChannel "close" event gives the killing signal's BARE POSIX name (e.g. "KILL"), unlike Node's
36
+ * own `child.on("close")` which gives `NodeJS.Signals` names (e.g. "SIGKILL") — re-prefix before looking it
37
+ * up in the shared, authoritative signal table (host-platform.ts `signalNumber`; single pattern-home, no
38
+ * hand-written table here). `?? 9` matches the convention every other exec adapter uses for an unmapped name. */
39
+ function exitCodeForSignalKill(signal) {
40
+ return 128 + (signalNumber(`SIG${signal}`) ?? 9);
41
+ }
34
42
  export class RemoteSshExecutionEnv {
35
43
  capabilities = { isolation: false, suspendable: false };
36
44
  /** Working directory; relative paths resolve against it (ExecutionEnv contract). Starts at mountPath. */
@@ -341,7 +349,12 @@ export class RemoteSshExecutionEnv {
341
349
  }
342
350
  const out = outBuf.result();
343
351
  const err = errBuf.result();
344
- finish(ok({ stdout: markTruncated(out.text, out.droppedBytes), stderr: markTruncated(err.text, err.droppedBytes), exitCode: code ?? 0 }));
352
+ // code==null WITH a signal = the remote command was killed by that signal — conventional 128+signo,
353
+ // NOT a fake success 0 ([R78]#2; was silently mapped to exitCode 0 before this fix). The `: 1`
354
+ // arm is unreachable (the transport_lost return above already covers code==null && !signal) but
355
+ // keeps the type honest without a non-null assertion.
356
+ const exitCode = code ?? (signal ? exitCodeForSignalKill(signal) : 1);
357
+ finish(ok({ stdout: markTruncated(out.text, out.droppedBytes), stderr: markTruncated(err.text, err.droppedBytes), exitCode }));
345
358
  })
346
359
  .stderr.on("data", (d) => {
347
360
  errBuf.push(d);
@@ -445,7 +458,9 @@ export class RemoteSshExecutionEnv {
445
458
  // channel died without an exit status (transport drop) — typed retryable, not a fake exit 0 ([R78]#1)
446
459
  failure = new RemoteExecutionError("transport_lost", "ssh channel closed without exit status (transport lost)");
447
460
  }
448
- exitCode = code ?? 0;
461
+ // code==null WITH a signal = the remote command was killed by that signal — conventional 128+signo,
462
+ // NOT a fake success 0 ([R78]#2; was silently mapped to exitCode 0 before this fix).
463
+ exitCode = code ?? (signal ? exitCodeForSignalKill(signal) : 0);
449
464
  finished = true;
450
465
  signalReady();
451
466
  })
@@ -289,16 +289,16 @@ export class SqlRunStore {
289
289
  where.push("status = ?");
290
290
  params.push(opts.status);
291
291
  }
292
- if (opts.jobId) {
292
+ if (opts.jobId !== undefined) {
293
293
  where.push("job_id = ?");
294
294
  params.push(opts.jobId);
295
295
  }
296
- if (opts.source) {
296
+ if (opts.source !== undefined) {
297
297
  where.push("source = ?");
298
298
  params.push(opts.source);
299
299
  }
300
- if (opts.owner) {
301
- where.push("owner = ?"); // idx_owner — the per-user list view (portal scopes a normal user to their own)
300
+ if (opts.owner !== undefined) {
301
+ where.push("owner = ?"); // idx_owner — the per-user list view (portal scopes a normal user to their own); "" is a valid exact owner, not "no filter" (B10)
302
302
  params.push(opts.owner);
303
303
  }
304
304
  if (opts.cursor) {
@@ -320,12 +320,12 @@ export class SqlRunStore {
320
320
  const where = [];
321
321
  if (opts.status)
322
322
  where.push(`status = ${p(opts.status)}`);
323
- if (opts.jobId)
323
+ if (opts.jobId !== undefined)
324
324
  where.push(`job_id = ${p(opts.jobId)}`);
325
- if (opts.source)
326
- where.push(`source = ${p(opts.source)}`);
327
- if (opts.owner)
328
- where.push(`owner = ${p(opts.owner)}`);
325
+ if (opts.source !== undefined)
326
+ where.push(`source = ${p(opts.source)}`); // "" exact-matches (B10, same family as owner)
327
+ if (opts.owner !== undefined)
328
+ where.push(`owner = ${p(opts.owner)}`); // "" is a valid exact owner, not "no filter" (B10)
329
329
  if (opts.cursor) {
330
330
  const a = p(new Date(opts.cursor.createdAt));
331
331
  const b = p(new Date(opts.cursor.createdAt));
@@ -348,8 +348,8 @@ export class SqlRunStore {
348
348
  if (this.db.dialect === "tidb") {
349
349
  const params = [];
350
350
  let innerWhere = "";
351
- if (opts.owner) {
352
- innerWhere = " WHERE owner = ?";
351
+ if (opts.owner !== undefined) {
352
+ innerWhere = " WHERE owner = ?"; // "" is a valid exact owner, not "no filter" (B10)
353
353
  params.push(opts.owner);
354
354
  }
355
355
  const outer = ["rn = 1"];
@@ -381,7 +381,7 @@ export class SqlRunStore {
381
381
  params.push(v);
382
382
  return `$${params.length}`;
383
383
  };
384
- const innerWhere = opts.owner ? ` WHERE owner = ${p(opts.owner)}` : "";
384
+ const innerWhere = opts.owner !== undefined ? ` WHERE owner = ${p(opts.owner)}` : ""; // "" is a valid exact owner, not "no filter" (B10)
385
385
  const outer = ["rn = 1"];
386
386
  // `?q=` — the PG twin of the TiDB EXISTS predicate above.
387
387
  if (opts.q)
@@ -520,6 +520,12 @@ export class SqlRunStore {
520
520
  // claim — the session stays locked until an operator resumes it or reapSuspended expires it. (Was
521
521
  // `<> 'running'`, which would have prematurely unlocked a parked suspended session.)
522
522
  await conn.query(this.q("DELETE ta FROM task_active ta JOIN task_run tr ON ta.task_id = tr.task_id WHERE tr.status NOT IN ('running','suspended','needs_review')", "DELETE FROM task_active ta USING task_run tr WHERE ta.task_id = tr.task_id AND tr.status NOT IN ('running','suspended','needs_review')"));
523
+ // [2255]③ 孤儿 claim 清扫(纵深防御):claim 无对应 task_run 行时,三处 INNER JOIN 释放腿永远碰不到
524
+ // 它。正常路径不产孤儿(createRun 单事务、setTerminal 无条件 DELETE、deleteBySession 同事务对称)——
525
+ // 这形只来自带外(手工 SQL/半截迁移),但一旦出现该 session 只剩 cancel 一条自救路。挂在 reapStale
526
+ // (每 tick 无条件跑)一处即可。同文双方言(关联 NOT EXISTS 指向**另一张**表,两引擎都合法);
527
+ // 无竞态:createRun 的 claim+row 同事务提交,已提交的 claim 必有行。
528
+ await conn.query(this.q("DELETE FROM task_active WHERE NOT EXISTS (SELECT 1 FROM task_run tr WHERE tr.task_id = task_active.task_id)", "DELETE FROM task_active WHERE NOT EXISTS (SELECT 1 FROM task_run tr WHERE tr.task_id = task_active.task_id)"));
523
529
  });
524
530
  return reaped;
525
531
  }
@@ -144,7 +144,7 @@ export interface StoreBackend {
144
144
  /** P1 (fleet failover): durable cross-replica WorkflowRunStore + completion-inbox twins. OPTIONAL —
145
145
  * SQL backends only (local keeps the File pair: single box, no cross-replica surface). main.ts prefers
146
146
  * these under WORKFLOW_RUN_STORE=auto (the default). */
147
- workflowRun?(): import("@sema-agent/core").WorkflowRunStore;
147
+ workflowRun?(onWarn?: InboxWarn): import("@sema-agent/core").WorkflowRunStore;
148
148
  completionInbox?(onWarn?: InboxWarn): import("../orchestration/workflow-completion-inbox.js").WorkflowCompletionInbox;
149
149
  /** 1.108 review fix (lens③ HIGH): the notify-JOURNAL twin — third leg of the same axis (a SQL run store +
150
150
  * inbox with a replica-LOCAL File journal stranded a dead replica's un-acked notify forever). */
@@ -113,7 +113,7 @@ class TiDBBackend {
113
113
  fileSnapshot() { return new TiDBFileSnapshotStore(this.pool, snapshotBlobBackend(this.config, "tidb", this.pool), snapshotBoundsFromConfig(this.config)); }
114
114
  workflowJournal() { return new TiDBWorkflowJournalStore(this.pool); }
115
115
  outcomeSink() { return new TiDBOutcomeLedger(this.pool); } // design/73 §1→§7 bridge (recordCore)
116
- workflowRun() { return new TiDBWorkflowRunStore(this.pool); } // P1: cross-replica workflow record
116
+ workflowRun(onWarn) { return new TiDBWorkflowRunStore(this.pool, onWarn); } // P1: cross-replica workflow record(onWarn = C5 oversize-slim 留痕,completionInbox 同款先例)
117
117
  completionInbox(onWarn) { return new TiDBWorkflowCompletionInbox(this.pool, onWarn); } // P1: cross-replica push half
118
118
  notifyJournal() { return new TiDBWorkflowNotifyJournalStore(this.pool); } // 1.108: cross-replica at-least-once notify
119
119
  checkpoint(logger) { return new TiDBCheckpointStore(this.pool, logger); }
@@ -147,7 +147,7 @@ class PgBackend {
147
147
  fileSnapshot() { return new PgFileSnapshotStore(this.pool, snapshotBlobBackend(this.config, "pg", this.pool), snapshotBoundsFromConfig(this.config)); }
148
148
  workflowJournal() { return new PgWorkflowJournalStore(this.pool); }
149
149
  outcomeSink() { return new PgOutcomeLedger(this.pool); } // design/73 §1→§7 bridge (recordCore)
150
- workflowRun() { return new PgWorkflowRunStore(this.pool); } // P1: cross-replica workflow record
150
+ workflowRun(onWarn) { return new PgWorkflowRunStore(this.pool, onWarn); } // P1: cross-replica workflow record(onWarn = C5 oversize-slim 留痕,completionInbox 同款先例)
151
151
  completionInbox(onWarn) { return new PgWorkflowCompletionInbox(this.pool, onWarn); } // P1: cross-replica push half
152
152
  notifyJournal() { return new PgWorkflowNotifyJournalStore(this.pool); } // 1.108: cross-replica at-least-once notify
153
153
  checkpoint(logger) { return new PgCheckpointStore(this.pool, logger); }
@@ -29,7 +29,13 @@ export declare class SqlToolResultStore implements ToolResultStore {
29
29
  offset?: number;
30
30
  limit?: number;
31
31
  }): Promise<ToolResultSlice | undefined>;
32
- /** TTL reap: delete results older than `cutoffMs`. Returns rows removed. */
32
+ /** TTL reap: delete results older than `cutoffMs`. Returns rows removed.
33
+ * C6: a real DB error must NOT collapse into the same `0` a legitimate "nothing was old enough" returns —
34
+ * those are different facts (query failed vs. query succeeded on an empty set) and folding them together
35
+ * makes a stuck/broken reaper indistinguishable from a healthy quiet one. Matches every sibling reaper's
36
+ * form (roster-store-sql.ts `reapOlderThan`, checkpoint-store-sql.ts `reapExpired`,
37
+ * workflow-journal-store-sql.ts `reapExpired`): let the error propagate — the periodic-sweep call site
38
+ * (boot/reapers.ts) already wraps this call in `.catch(() => undefined)` so the reap loop itself never dies. */
33
39
  reapOlderThan(cutoffMs: number): Promise<number>;
34
40
  /**
35
41
  * E21 (§0.5 session delete) — purge offloaded tool results for one session. core namespaces every ref as
@@ -123,15 +123,16 @@ export class SqlToolResultStore {
123
123
  return undefined; // unknown ref (e.g. reaped) → core reports "no longer available"
124
124
  return { content: String(rows[0].slice ?? ""), offset, totalChars: Number(rows[0].total) };
125
125
  }
126
- /** TTL reap: delete results older than `cutoffMs`. Returns rows removed. */
126
+ /** TTL reap: delete results older than `cutoffMs`. Returns rows removed.
127
+ * C6: a real DB error must NOT collapse into the same `0` a legitimate "nothing was old enough" returns —
128
+ * those are different facts (query failed vs. query succeeded on an empty set) and folding them together
129
+ * makes a stuck/broken reaper indistinguishable from a healthy quiet one. Matches every sibling reaper's
130
+ * form (roster-store-sql.ts `reapOlderThan`, checkpoint-store-sql.ts `reapExpired`,
131
+ * workflow-journal-store-sql.ts `reapExpired`): let the error propagate — the periodic-sweep call site
132
+ * (boot/reapers.ts) already wraps this call in `.catch(() => undefined)` so the reap loop itself never dies. */
127
133
  async reapOlderThan(cutoffMs) {
128
- try {
129
- const { affected } = await this.db.query(this.q("DELETE FROM tool_result WHERE created_at < ?", "DELETE FROM tool_result WHERE created_at < $1"), [new Date(cutoffMs)]);
130
- return affected;
131
- }
132
- catch {
133
- return 0; // best-effort reaper — never throw into the loop
134
- }
134
+ const { affected } = await this.db.query(this.q("DELETE FROM tool_result WHERE created_at < ?", "DELETE FROM tool_result WHERE created_at < $1"), [new Date(cutoffMs)]);
135
+ return affected;
135
136
  }
136
137
  /**
137
138
  * E21 (§0.5 session delete) — purge offloaded tool results for one session. core namespaces every ref as
@@ -79,10 +79,13 @@ export declare function slimOversizeRun(run: WorkflowRun & {
79
79
  id: string;
80
80
  scope: string;
81
81
  }, maxBytes: number): string | null;
82
- /** Dual-dialect durable `WorkflowRunStore`. See the file header for the dialect-delta ledger. */
82
+ /** Dual-dialect durable `WorkflowRunStore`. See the file header for the dialect-delta ledger.
83
+ * `onWarn` (optional, same shape as the completion-inbox's {@link InboxWarn}) is the C5 trace channel for
84
+ * `update`'s oversize-slim degrade (see there) — omit it and construction/behavior is unchanged (additive). */
83
85
  export declare class SqlWorkflowRunStore implements WorkflowRunStore {
84
86
  protected readonly db: SqlDriver;
85
- constructor(db: SqlDriver);
87
+ private readonly onWarn?;
88
+ constructor(db: SqlDriver, onWarn?: InboxWarn | undefined);
86
89
  /** Pick the dialect's SQL text. Both statements stay written out at the call site ON PURPOSE. */
87
90
  private q;
88
91
  put(id: string, run: WorkflowRun): Promise<void>;
@@ -145,9 +148,10 @@ export declare class SqlWorkflowNotifyJournalStore implements WorkflowNotifyJour
145
148
  reapAcked(before: number): Promise<number>;
146
149
  get(runId: string): Promise<WorkflowNotifyJournalEntry | null>;
147
150
  }
148
- /** MySQL-protocol (TiDB) bindings — historical class names + ctor shapes preserved. */
151
+ /** MySQL-protocol (TiDB) bindings — historical class names preserved; `onWarn` is an ADDITIVE optional 2nd
152
+ * ctor arg (existing 1-arg call sites are unaffected — see {@link SqlWorkflowRunStore}'s C5 trace channel). */
149
153
  export declare class TiDBWorkflowRunStore extends SqlWorkflowRunStore {
150
- constructor(pool: MySqlPool);
154
+ constructor(pool: MySqlPool, onWarn?: InboxWarn);
151
155
  }
152
156
  export declare class TiDBWorkflowCompletionInbox extends SqlWorkflowCompletionInbox {
153
157
  constructor(pool: MySqlPool, onWarn?: InboxWarn);
@@ -155,9 +159,10 @@ export declare class TiDBWorkflowCompletionInbox extends SqlWorkflowCompletionIn
155
159
  export declare class TiDBWorkflowNotifyJournalStore extends SqlWorkflowNotifyJournalStore {
156
160
  constructor(pool: MySqlPool);
157
161
  }
158
- /** PostgreSQL bindings — historical class names + ctor shapes preserved. */
162
+ /** PostgreSQL bindings — historical class names preserved; `onWarn` is an ADDITIVE optional 2nd ctor arg
163
+ * (existing 1-arg call sites are unaffected — see {@link SqlWorkflowRunStore}'s C5 trace channel). */
159
164
  export declare class PgWorkflowRunStore extends SqlWorkflowRunStore {
160
- constructor(pool: PgPool);
165
+ constructor(pool: PgPool, onWarn?: InboxWarn);
161
166
  }
162
167
  export declare class PgWorkflowCompletionInbox extends SqlWorkflowCompletionInbox {
163
168
  constructor(pool: PgPool, onWarn?: InboxWarn);
@@ -29,11 +29,15 @@ export function slimOversizeRun(run, maxBytes) {
29
29
  blob = JSON.stringify(step2);
30
30
  return Buffer.byteLength(blob) <= maxBytes ? blob : null;
31
31
  }
32
- /** Dual-dialect durable `WorkflowRunStore`. See the file header for the dialect-delta ledger. */
32
+ /** Dual-dialect durable `WorkflowRunStore`. See the file header for the dialect-delta ledger.
33
+ * `onWarn` (optional, same shape as the completion-inbox's {@link InboxWarn}) is the C5 trace channel for
34
+ * `update`'s oversize-slim degrade (see there) — omit it and construction/behavior is unchanged (additive). */
33
35
  export class SqlWorkflowRunStore {
34
36
  db;
35
- constructor(db) {
37
+ onWarn;
38
+ constructor(db, onWarn) {
36
39
  this.db = db;
40
+ this.onWarn = onWarn;
37
41
  }
38
42
  /** Pick the dialect's SQL text. Both statements stay written out at the call site ON PURPOSE. */
39
43
  q(tidb, pg) {
@@ -70,6 +74,10 @@ export class SqlWorkflowRunStore {
70
74
  if (Buffer.byteLength(blob) > MAX_RUN_BLOB_BYTES) {
71
75
  // Oversize degrade (1.108 review fix): slim the payload so the write — critically the TERMINAL one —
72
76
  // still lands (a `false` here would never be retried with a smaller payload; see slimOversizeRun).
77
+ // C5 (2026-07-31): the degrade drops real data (phases/agents/groups → []) — that must leave a trace
78
+ // reaching whoever can act on it, not just a same-shaped `true` return. `onWarn` is optional so a
79
+ // caller that hasn't wired a sink yet keeps building/running unchanged.
80
+ this.onWarn?.("workflow_run_blob_oversize_slimmed", { id, scope, fullBytes: Buffer.byteLength(blob), capBytes: MAX_RUN_BLOB_BYTES });
73
81
  const slim = slimOversizeRun({ ...run, id, scope }, MAX_RUN_BLOB_BYTES);
74
82
  if (slim === null)
75
83
  return false; // even the skeleton is oversize — keep the prior revision
@@ -342,10 +350,11 @@ export class SqlWorkflowNotifyJournalStore {
342
350
  };
343
351
  }
344
352
  }
345
- /** MySQL-protocol (TiDB) bindings — historical class names + ctor shapes preserved. */
353
+ /** MySQL-protocol (TiDB) bindings — historical class names preserved; `onWarn` is an ADDITIVE optional 2nd
354
+ * ctor arg (existing 1-arg call sites are unaffected — see {@link SqlWorkflowRunStore}'s C5 trace channel). */
346
355
  export class TiDBWorkflowRunStore extends SqlWorkflowRunStore {
347
- constructor(pool) {
348
- super(mysqlDriver(pool));
356
+ constructor(pool, onWarn) {
357
+ super(mysqlDriver(pool), onWarn);
349
358
  }
350
359
  }
351
360
  export class TiDBWorkflowCompletionInbox extends SqlWorkflowCompletionInbox {
@@ -358,10 +367,11 @@ export class TiDBWorkflowNotifyJournalStore extends SqlWorkflowNotifyJournalStor
358
367
  super(mysqlDriver(pool));
359
368
  }
360
369
  }
361
- /** PostgreSQL bindings — historical class names + ctor shapes preserved. */
370
+ /** PostgreSQL bindings — historical class names preserved; `onWarn` is an ADDITIVE optional 2nd ctor arg
371
+ * (existing 1-arg call sites are unaffected — see {@link SqlWorkflowRunStore}'s C5 trace channel). */
362
372
  export class PgWorkflowRunStore extends SqlWorkflowRunStore {
363
- constructor(pool) {
364
- super(pgDriver(pool));
373
+ constructor(pool, onWarn) {
374
+ super(pgDriver(pool), onWarn);
365
375
  }
366
376
  }
367
377
  export class PgWorkflowCompletionInbox extends SqlWorkflowCompletionInbox {
@@ -310,9 +310,12 @@ export async function importSession(bundle, getBlob, dstBackend, importingPrinci
310
310
  // entirely (the snapshot/policy/anchor replay below is idempotent and still runs to heal anything missing). A
311
311
  // destination without the replace seam can't accept a session at all → throw.
312
312
  // 🔴 同上(`session-sync-content.ts` 顶注):`identical` 只说明 id 集合相等,不说明内容相同。这条路上
313
- // `bundle.entries` 与目的端日志都在手上 ⇒ 直接比内容摘要;不符就照常改写(不抛错、不 409)
314
- const dstEntriesForContent = await ownerAware(dstBackend).exportEntries?.(sessionId).catch(() => null) ?? null;
315
- const contentEqual = rel.relation === "identical" && identicalIdsAlsoIdenticalContent(bundle.entries, dstEntriesForContent);
313
+ // `bundle.entries` 与目的端日志都在手上 ⇒ 直接比内容摘要;不符就照常改写(不抛错、不 409)。复用 §7 已经
314
+ // 读到的 `dstEntries`(同一个 dstBackend/sessionId)——这两次读之间 dst 未被任何写触碰(overwrite-dst 擦除
315
+ // 只在 relation fork/stale 时才跑,identical 分支不可能落进那条腿),不必也不该对同一行重新 exportEntries
316
+ // 一次(旧实现还用 `.catch(() => null)` 把这次读的故障裸吞成"目的端为空",见下方 identicalIdsAlsoIdenticalContent
317
+ // 对 null 的处置——一次真实的店读故障会被悄悄当成"内容不等"而不是 fail-loud)。
318
+ const contentEqual = rel.relation === "identical" && identicalIdsAlsoIdenticalContent(bundle.entries, dstEntries);
316
319
  if (rel.relation !== "identical" || !contentEqual) {
317
320
  const session = ownerAware(dstBackend);
318
321
  const replaceEntries = session.replaceEntries?.bind(session);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sema-agent/server",
3
- "version": "3.20.0",
3
+ "version": "3.22.0",
4
4
  "description": "Sema Server — the server/API implementation layer for Sema, wiring core, registry, model providers, and cloud agent execution. Built on @sema-agent/core.",
5
5
  "type": "module",
6
6
  "license": "BUSL-1.1",
@@ -68,7 +68,7 @@
68
68
  "sharp": "^0.35.3"
69
69
  },
70
70
  "devDependencies": {
71
- "@sema-agent/sdk": "^2.2.0",
71
+ "@sema-agent/sdk": "^2.3.0",
72
72
  "@types/libsodium-wrappers": "^0.7.14",
73
73
  "@types/node": "22.10.2",
74
74
  "@types/pg": "^8.20.0",