@sema-agent/server 7.85.0 → 7.87.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 (73) hide show
  1. package/USAGE.md +19 -1
  2. package/dist/approval-hmac.d.ts +77 -2
  3. package/dist/approval-hmac.js +16 -1
  4. package/dist/boot/stage-01-config.js +2 -2
  5. package/dist/capabilities/execution-lane.d.ts +22 -0
  6. package/dist/capabilities/execution-lane.js +8 -0
  7. package/dist/capabilities/memory-notice.d.ts +4 -1
  8. package/dist/config-catalog.js +2 -1
  9. package/dist/execution-lane-caps.d.ts +13 -0
  10. package/dist/execution-lane-caps.js +1 -0
  11. package/dist/fleet/fleet-bus.d.ts +23 -3
  12. package/dist/fleet/fleet-reconciler.d.ts +35 -0
  13. package/dist/fleet/fleet-reconciler.js +52 -9
  14. package/dist/http/approval-sweeps.js +1 -1
  15. package/dist/http/resume-legs.d.ts +2 -1
  16. package/dist/http/resume-legs.js +24 -8
  17. package/dist/http/route-ctx.d.ts +51 -17
  18. package/dist/http/route-ctx.js +0 -3
  19. package/dist/http/routes/a2a-serve.js +1 -1
  20. package/dist/http/routes/approvals-assistant.d.ts +46 -23
  21. package/dist/http/routes/approvals-assistant.js +167 -45
  22. package/dist/http/routes/capabilities.js +2 -0
  23. package/dist/http/routes/images.js +38 -8
  24. package/dist/http/routes/mcp-reconnect.d.ts +1 -1
  25. package/dist/http/routes/mcp-reconnect.js +2 -2
  26. package/dist/http/routes/memory-policy.js +3 -6
  27. package/dist/http/routes/notify-wake.js +11 -3
  28. package/dist/http/routes/run-memory-capture.js +3 -5
  29. package/dist/http/routes/runs.js +21 -23
  30. package/dist/http/routes/sessions.js +10 -2
  31. package/dist/http/routes/shared-memory.js +5 -1
  32. package/dist/http/routes/tasks.js +2 -2
  33. package/dist/http/routes/workflows.js +1 -1
  34. package/dist/http/server.d.ts +2 -2
  35. package/dist/http/server.js +3 -3
  36. package/dist/leader/diffout.js +1 -1
  37. package/dist/leader/endpoint.js +1 -1
  38. package/dist/leader/fanout.js +1 -1
  39. package/dist/leader/leader.js +1 -1
  40. package/dist/leader/merge.js +1 -1
  41. package/dist/leader/planner.js +1 -1
  42. package/dist/leader/repair-oracle.js +1 -1
  43. package/dist/leader/repair-wire.js +1 -1
  44. package/dist/leader/wire.js +1 -1
  45. package/dist/memory-scope.d.ts +16 -0
  46. package/dist/observability/fail-open.d.ts +8 -0
  47. package/dist/observability/fail-open.js +8 -0
  48. package/dist/observability/metrics.d.ts +12 -0
  49. package/dist/observability/metrics.js +17 -0
  50. package/dist/observability/{run-terminal-log.d.ts → run-terminal.d.ts} +50 -10
  51. package/dist/observability/{run-terminal-log.js → run-terminal.js} +27 -8
  52. package/dist/plugins/checkpoint-store-sql.d.ts +8 -2
  53. package/dist/plugins/file-run-store.js +2 -2
  54. package/dist/plugins/memory-run-store.js +2 -2
  55. package/dist/plugins/remote-scratchpad.js +1 -1
  56. package/dist/plugins/run-store-sql.js +8 -7
  57. package/dist/plugins/store-contracts.d.ts +25 -2
  58. package/dist/plugins/store-contracts.js +3 -0
  59. package/dist/plugins/workflow-run-store-sql.js +1 -1
  60. package/dist/principal-jwt.d.ts +15 -7
  61. package/dist/principal-jwt.js +1 -1
  62. package/dist/runs.js +1 -1
  63. package/dist/session-titler.js +9 -5
  64. package/dist/task-settings.d.ts +35 -0
  65. package/dist/task-settings.js +7 -0
  66. package/dist/tool-approval.d.ts +22 -2
  67. package/dist/tool-approval.js +2 -0
  68. package/dist/trace/core-keyset-guard.d.ts +1 -1
  69. package/dist/trace/ledger-events.d.ts +1 -1
  70. package/dist/trace/project.d.ts +1 -1
  71. package/dist/trace/project.js +1 -1
  72. package/dist/trace/redact.d.ts +1 -1
  73. package/package.json +2 -2
@@ -1,9 +1,9 @@
1
1
  import { persistedPlaneOf } from "../../terminal.js";
2
- import { memoRedactedRead, memoRedactTerminalResult, redactErrorMessage, redactHead, redactLedgerEventData, redactTerminalResult } from "../../observability/run-terminal-log.js";
2
+ import { memoRedactedRead, memoRedactTerminalResult, redactErrorMessage, redactHead, redactLedgerEventData, redactTerminalResult } from "../../observability/run-terminal.js";
3
3
  import { isModelTextLedgerEventType } from "../../trace/ledger-events.js";
4
4
  import { z } from "zod";
5
5
  import { uuidv7, mintCheckpointToken, CheckpointError, validatePendingSteer } from "@sema-agent/core";
6
- import { isTerminalRunStatus, isParkedRunStatus } from "../../plugins/store-contracts.js";
6
+ import { isTerminalRunStatus, isParkedRunStatus, runProvenElsewhere } from "../../plugins/store-contracts.js";
7
7
  import { LIVE_RUN_GATE_KINDS, TERMINAL_PARK_GATE_KINDS } from "../../plugins/checkpoint-store-sql.js";
8
8
  import { redactSecrets } from "../../trace/redact.js";
9
9
  import { HttpError, verifiedPrincipal, isUuidV7, encodeCheckpointScope } from "../../security.js";
@@ -27,7 +27,7 @@ import { headerStr, gatedPrincipal, explicitOperatorOk, sendPrincipalRefusal } f
27
27
  import { ActorAssertionWire } from "@sema-agent/settings-schema";
28
28
  import { assertNever } from "../route-ctx.js";
29
29
  import { mintAndDriveDurableRun } from "../durable-run-leg.js";
30
- import { RUN_NOT_FOUND_MESSAGE, runNotFoundMessage, runProvenElsewhere } from "../route-ctx.js";
30
+ import { RUN_NOT_FOUND_MESSAGE, runNotFoundMessage } from "../route-ctx.js";
31
31
  import { withPrincipal } from "../../observability/principal-context.js";
32
32
  const ASK_PARKING_RETRY_AFTER_SEC = 2;
33
33
  const ASK_ACTOR_LABEL_MAX = 256;
@@ -64,7 +64,8 @@ export function projectDecisionActor(raw) {
64
64
  const parsed = AskDecisionActorSchema.safeParse(raw);
65
65
  return parsed.success ? parsed.data : undefined;
66
66
  }
67
- async function subagentReadGate(req, res, deps, runId, search) {
67
+ async function subagentReadGate(req, res, ctx, runId, search) {
68
+ const { deps } = ctx;
68
69
  const principal = gatedPrincipal(req, deps.config);
69
70
  if (deps.config.requirePrincipal && principal === undefined) {
70
71
  sendPrincipalRefusal(res, req, deps.config);
@@ -72,10 +73,13 @@ async function subagentReadGate(req, res, deps, runId, search) {
72
73
  }
73
74
  const trusted = explicitOperatorOk(principal, deps.config.operatorPrincipals);
74
75
  const run = await deps.runStore.getRun(runId);
75
- if (!run || (!trusted && run.owner !== null && run.owner !== principal)) {
76
+ if (!run) {
76
77
  sendError(res, 404, "not_found.run", RUN_NOT_FOUND_MESSAGE);
77
78
  return null;
78
79
  }
80
+ if (!trusted && !ctx.helpers.runOwnerOk(req, res, run.owner)) {
81
+ return null;
82
+ }
79
83
  const callerSession = new URLSearchParams(search).get("session");
80
84
  if (!trusted && run.sessionId && callerSession !== run.sessionId) {
81
85
  sendError(res, 404, "not_found.run", RUN_NOT_FOUND_MESSAGE);
@@ -85,7 +89,7 @@ async function subagentReadGate(req, res, deps, runId, search) {
85
89
  }
86
90
  function sendHandleMiss(res, run, thisInstanceId) {
87
91
  if (isTerminalRunStatus(run.status)) {
88
- sendError(res, 404, "not_found.task_owner_settled", "no such background task handle here. Routing hint about its OWNER (not about this handle): the run has already settled, and background handles live in the replica-local registry for the parent's lifetime, so none of its handles are readable any more. Read the run's own outcome via GET /v1/runs/:id");
92
+ sendError(res, 404, "not_found.task_owner_settled", "no such background task handle here. Routing hint about its OWNER (not about this handle): the run has already settled. Read the run's own outcome via GET /v1/runs/:id");
89
93
  return true;
90
94
  }
91
95
  if (run.status === "running" && runProvenElsewhere(run, thisInstanceId)) {
@@ -429,10 +433,8 @@ export async function handleRuns(req, res, match, ctx) {
429
433
  sendError(res, 404, "not_found.run", runNotFoundMessage(taskId));
430
434
  return;
431
435
  }
432
- if (!trusted && run.owner !== null && run.owner !== principal) {
433
- sendError(res, 404, "not_found.run", RUN_NOT_FOUND_MESSAGE);
436
+ if (!trusted && !runOwnerOk(req, res, run.owner))
434
437
  return;
435
- }
436
438
  if (!runSessionAcceptOk(req, res, run, "run.steer"))
437
439
  return;
438
440
  let parkQueueFull;
@@ -714,10 +716,8 @@ export async function handleRuns(req, res, match, ctx) {
714
716
  sendError(res, 404, "not_found.run", runNotFoundMessage(taskId));
715
717
  return;
716
718
  }
717
- if (!trusted && run.owner !== null && run.owner !== principal) {
718
- sendError(res, 404, "not_found.run", RUN_NOT_FOUND_MESSAGE);
719
+ if (!trusted && !runOwnerOk(req, res, run.owner))
719
720
  return;
720
- }
721
721
  if (!runSessionAcceptOk(req, res, run, "run.interrupt"))
722
722
  return;
723
723
  const sendInterruptNotRunning = (error) => sendError(res, 409, "steering.not_running", error);
@@ -812,10 +812,8 @@ export async function handleRuns(req, res, match, ctx) {
812
812
  return;
813
813
  }
814
814
  const operator = explicitOperatorOk(principal, deps.config.operatorPrincipals);
815
- if (!operator && run.owner !== null && run.owner !== principal) {
816
- sendError(res, 404, "not_found.run", RUN_NOT_FOUND_MESSAGE);
815
+ if (!operator && !runOwnerOk(req, res, run.owner))
817
816
  return;
818
- }
819
817
  if (!runSessionAcceptOk(req, res, run, "run.compact"))
820
818
  return;
821
819
  let compactBody;
@@ -894,10 +892,8 @@ export async function handleRuns(req, res, match, ctx) {
894
892
  return;
895
893
  }
896
894
  const operator = explicitOperatorOk(principal, deps.config.operatorPrincipals);
897
- if (!operator && run.owner !== null && run.owner !== principal) {
898
- sendError(res, 404, "not_found.run", RUN_NOT_FOUND_MESSAGE);
895
+ if (!operator && !runOwnerOk(req, res, run.owner))
899
896
  return;
900
- }
901
897
  if (!runSessionAcceptOk(req, res, run, "run.detach"))
902
898
  return;
903
899
  const live = steerableRuns.get(taskId);
@@ -913,7 +909,7 @@ export async function handleRuns(req, res, match, ctx) {
913
909
  }
914
910
  export async function handleRunVerbs(req, res, match, ctx) {
915
911
  const { deps } = ctx;
916
- const { readJson, rateLimited, quotaExceeded, ownerQuotaDenied, leaseDenied, ownerLeaseDenied, safeDecode, runSessionAcceptOk } = ctx.helpers;
912
+ const { readJson, rateLimited, quotaExceeded, ownerQuotaDenied, leaseDenied, ownerLeaseDenied, safeDecode, runOwnerOk, runSessionAcceptOk } = ctx.helpers;
917
913
  if (match.decl.id === "run-subagent-output") {
918
914
  if (!deps.runStore || !deps.subagentTaskOutput) {
919
915
  sendError(res, 501, "capability.run_store_required", "subagent output reads require the run store");
@@ -925,7 +921,7 @@ export async function handleRunVerbs(req, res, match, ctx) {
925
921
  sendError(res, 400, "request.path_malformed", "malformed subagent path (invalid percent-encoding)");
926
922
  return;
927
923
  }
928
- const gated = await subagentReadGate(req, res, deps, runId, match.search);
924
+ const gated = await subagentReadGate(req, res, ctx, runId, match.search);
929
925
  if (!gated)
930
926
  return;
931
927
  const { run } = gated;
@@ -950,7 +946,7 @@ export async function handleRunVerbs(req, res, match, ctx) {
950
946
  sendError(res, 400, "request.path_malformed", "malformed subagent path (invalid percent-encoding)");
951
947
  return;
952
948
  }
953
- const gatedTail = await subagentReadGate(req, res, deps, runId, match.search);
949
+ const gatedTail = await subagentReadGate(req, res, ctx, runId, match.search);
954
950
  if (!gatedTail)
955
951
  return;
956
952
  const { run } = gatedTail;
@@ -1015,7 +1011,7 @@ export async function handleRunVerbs(req, res, match, ctx) {
1015
1011
  sendError(res, 400, "request.path_malformed", "malformed task path (invalid percent-encoding)");
1016
1012
  return;
1017
1013
  }
1018
- const gatedB = await subagentReadGate(req, res, deps, runId, match.search);
1014
+ const gatedB = await subagentReadGate(req, res, ctx, runId, match.search);
1019
1015
  if (!gatedB)
1020
1016
  return;
1021
1017
  const { run } = gatedB;
@@ -1113,10 +1109,12 @@ export async function handleRunVerbs(req, res, match, ctx) {
1113
1109
  }
1114
1110
  const trusted = explicitOperatorOk(principal, deps.config.operatorPrincipals);
1115
1111
  const run = await deps.runStore.getRun(runId);
1116
- if (!run || (!trusted && run.owner !== null && run.owner !== principal)) {
1112
+ if (!run) {
1117
1113
  sendError(res, 404, "not_found.run", RUN_NOT_FOUND_MESSAGE);
1118
1114
  return;
1119
1115
  }
1116
+ if (!trusted && !runOwnerOk(req, res, run.owner))
1117
+ return;
1120
1118
  if (!runSessionAcceptOk(req, res, run, `subagent.${verb}`))
1121
1119
  return;
1122
1120
  const send409 = (errorCode, error) => sendError(res, 409, errorCode, error);
@@ -219,7 +219,11 @@ export async function handleSessions(req, res, match, ctx) {
219
219
  sendError(res, 501, "capability.session_store_required", "session head probe requires a durable session store (DB_BACKEND=mysql|pg|local)");
220
220
  return;
221
221
  }
222
- const headSession = decodeURIComponent(match.params.sessionId);
222
+ const headSession = safeDecode(match.params.sessionId);
223
+ if (headSession === null) {
224
+ sendError(res, 400, "request.path_malformed", "session id segment is not valid percent-encoding");
225
+ return;
226
+ }
223
227
  const getHead = deps.sessionStorage?.getHead?.bind(deps.sessionStorage);
224
228
  let owner;
225
229
  let leafId;
@@ -262,7 +266,11 @@ export async function handleSessions(req, res, match, ctx) {
262
266
  sendError(res, 501, "capability.session_store_required", "session events require a durable session store (DB_BACKEND=mysql|pg|local)");
263
267
  return;
264
268
  }
265
- const evSession = decodeURIComponent(match.params.sessionId);
269
+ const evSession = safeDecode(match.params.sessionId);
270
+ if (evSession === null) {
271
+ sendError(res, 400, "request.path_malformed", "session id segment is not valid percent-encoding");
272
+ return;
273
+ }
266
274
  if (sse.sseConnections >= (deps.sessionEventsMaxConnections ?? 256)) {
267
275
  res.setHeader("retry-after", "5");
268
276
  sendError(res, 503, "state.sse_connection_cap", "session-events connection cap reached — fall back to /head polling");
@@ -90,7 +90,11 @@ export async function handleSharedMemory(req, res, match, ctx) {
90
90
  }
91
91
  case "shared-memory-store-documents":
92
92
  case "shared-memory-store-document": {
93
- const storeId = decodeURIComponent(match.params.store);
93
+ const storeId = ctx.helpers.safeDecode(match.params.store);
94
+ if (storeId === null) {
95
+ sendError(res, 400, "request.path_malformed", "malformed id (invalid percent-encoding)");
96
+ return;
97
+ }
94
98
  const query = new URLSearchParams(match.search);
95
99
  const snapshot = await bindSnapshot(req, res, ctx);
96
100
  if (!snapshot)
@@ -1,4 +1,4 @@
1
- import { redactErrorMessage, redactHead, redactTerminalResult } from "../../observability/run-terminal-log.js";
1
+ import { redactErrorMessage, redactHead, redactTerminalResult } from "../../observability/run-terminal.js";
2
2
  import { runWithVerification, runCascade, uuidv7, terminalProjection } from "@sema-agent/core";
3
3
  import { graftParkToolCallId, markChildrenStoppedByUserOnAbort, resumeAtHttpStatus, HEARTBEAT_MS } from "../../runs.js";
4
4
  import { stripResumeToken } from "../../terminal.js";
@@ -414,7 +414,7 @@ export async function handleTasks(req, res, match, ctx) {
414
414
  finalizeTaskResult(ev.result, principal, prepared.spec.objective, prepared.spec.sessionId);
415
415
  noteRunOutcome(finalResult);
416
416
  putRewindAnchor();
417
- settleFleet(finalResult ? terminalProjection(finalResult.terminal).status : "completed", fleetRunResiduals(finalResult));
417
+ settleFleet(terminalProjection(finalResult.terminal).status, fleetRunResiduals(finalResult));
418
418
  if (ledgerSink && finalResult) {
419
419
  if (usageKey && deps.modelUsage && deps.runStore && durableTaskId) {
420
420
  const rs2 = deps.runStore;
@@ -5,7 +5,7 @@ import { redactSteerIn, STEER_IN_MAX_CHARS, STEER_IN_MAX_REQUEST_CHARS } from ".
5
5
  import { journalEntryOfRow, journalEntryPayload, journalRowPayloadOf } from "../../orchestration/workflow-journal-entry.js";
6
6
  import { redactSecrets } from "../../trace/redact.js";
7
7
  import { createHash } from "node:crypto";
8
- import { redactErrorMessage, redactHead } from "../../observability/run-terminal-log.js";
8
+ import { redactErrorMessage, redactHead } from "../../observability/run-terminal.js";
9
9
  const JOURNAL_PROJECTION_MEMO_CAP = 1024;
10
10
  const journalProjectionMemo = new Map();
11
11
  import { sendJson, sendError, sseHeaders } from "../send.js";
@@ -28,8 +28,8 @@ import type { ModelUsageTracker, PromptManifestTracker } from "../budget.js";
28
28
  import { scopedIdempotencyKey } from "./idempotency.js";
29
29
  export { scopedIdempotencyKey };
30
30
  import type { ConsolidationSeatLabel } from "../boot/memory-consolidation.js";
31
- import { streamApprovals, isQuestionAnswer } from "./routes/approvals-assistant.js";
32
- export { streamApprovals, isQuestionAnswer };
31
+ import { streamApprovals, checkQuestionAnswer } from "./routes/approvals-assistant.js";
32
+ export { streamApprovals, checkQuestionAnswer };
33
33
  import { cascadeConfig } from "./run-meta.js";
34
34
  export { cascadeConfig };
35
35
  import { coarseStatusForState, errorCodeForExit } from "./routes/images.js";
@@ -1,5 +1,5 @@
1
1
  import http from "node:http";
2
- import { redactHead } from "../observability/run-terminal-log.js";
2
+ import { redactHead } from "../observability/run-terminal.js";
3
3
  import { validatePendingSteer, terminalProjection } from "@sema-agent/core";
4
4
  import {} from "../config-center/facade.js";
5
5
  import { HttpError } from "../security.js";
@@ -12,8 +12,8 @@ import {} from "../tool-approval.js";
12
12
  import {} from "../observability/rate-limit.js";
13
13
  import { IdempotencyCache, scopedIdempotencyKey } from "./idempotency.js";
14
14
  export { scopedIdempotencyKey };
15
- import { streamApprovals, isQuestionAnswer } from "./routes/approvals-assistant.js";
16
- export { streamApprovals, isQuestionAnswer };
15
+ import { streamApprovals, checkQuestionAnswer } from "./routes/approvals-assistant.js";
16
+ export { streamApprovals, checkQuestionAnswer };
17
17
  import { cascadeConfig } from "./run-meta.js";
18
18
  export { cascadeConfig };
19
19
  import { coarseStatusForState, errorCodeForExit } from "./routes/images.js";
@@ -1,4 +1,4 @@
1
- import { redactHead } from "../observability/run-terminal-log.js";
1
+ import { redactHead } from "../observability/run-terminal.js";
2
2
  export const DEFAULT_MAX_DIFF_BYTES = 5 * 1024 * 1024;
3
3
  const DEFAULT_READ_TIMEOUT_MS = 30_000;
4
4
  const SAFE_REV = /^[A-Za-z0-9._/-]{1,200}$/;
@@ -1,5 +1,5 @@
1
1
  import { uuidv7 } from "@sema-agent/core";
2
- import { redactErrorMessage, redactHead, redactLeaderResult, redactLeaderResultWithFlag } from "../observability/run-terminal-log.js";
2
+ import { redactErrorMessage, redactHead, redactLeaderResult, redactLeaderResultWithFlag } from "../observability/run-terminal.js";
3
3
  import { withPrincipal } from "../observability/principal-context.js";
4
4
  import { leaderIdemKey } from "../plugins/leader-run-store-sql.js";
5
5
  function statusForLeaderResult(result) {
@@ -1,5 +1,5 @@
1
1
  import { terminalProjection } from "@sema-agent/core";
2
- import { redactErrorMessage, redactWorkerReportError } from "../observability/run-terminal-log.js";
2
+ import { redactErrorMessage, redactWorkerReportError } from "../observability/run-terminal.js";
3
3
  import { pausedCauseOf } from "../terminal.js";
4
4
  class Semaphore {
5
5
  max;
@@ -1,5 +1,5 @@
1
1
  import { fanOut } from "./fanout.js";
2
- import { redactErrorMessage, redactHead } from "../observability/run-terminal-log.js";
2
+ import { redactErrorMessage, redactHead } from "../observability/run-terminal.js";
3
3
  import { pullDiff } from "./diffout.js";
4
4
  import { mergeBranches } from "./merge.js";
5
5
  import { Runner, runWithVerification, resumeWithVerification, terminalProjection } from "@sema-agent/core";
@@ -1,5 +1,5 @@
1
1
  import { delimitUntrusted } from "@sema-agent/core";
2
- import { OVERSIZED_DIAG_PLACEHOLDER, redactArtifactText, redactErrorMessage, redactHead, redactTail } from "../observability/run-terminal-log.js";
2
+ import { OVERSIZED_DIAG_PLACEHOLDER, redactArtifactText, redactErrorMessage, redactHead, redactTail } from "../observability/run-terminal.js";
3
3
  import { applyAndGrade, changedFilesOutOfAllowlist } from "./grader-env-factory.js";
4
4
  import { shellQuote as Q } from "../plugins/remote-shell.js";
5
5
  const CONFLICT_FILES_MAX = 200;
@@ -1,4 +1,4 @@
1
- import { redactErrorMessage, redactHead, redactTail } from "../observability/run-terminal-log.js";
1
+ import { redactErrorMessage, redactHead, redactTail } from "../observability/run-terminal.js";
2
2
  export function economicGuard(objective, opts = {}) {
3
3
  if (opts.fanoutEnabled === false)
4
4
  return { single: true, reason: "fan-out disabled by deployment (A6)" };
@@ -1,7 +1,7 @@
1
1
  import { runExecGate, } from "@sema-agent/core";
2
2
  import { createHash } from "node:crypto";
3
3
  import { shellQuote as sq } from "../plugins/remote-shell.js";
4
- import { redactHead, redactTail } from "../observability/run-terminal-log.js";
4
+ import { redactHead, redactTail } from "../observability/run-terminal.js";
5
5
  const sha = (s) => createHash("sha256").update(s).digest("hex").slice(0, 16);
6
6
  function changedFilesOf(patch) {
7
7
  const out = new Set();
@@ -1,7 +1,7 @@
1
1
  import { runRepairLoop, delimitUntrusted, } from "@sema-agent/core";
2
2
  import { mkRepairOracle } from "./repair-oracle.js";
3
3
  import { terminalProjection } from "@sema-agent/core";
4
- import { redactHead } from "../observability/run-terminal-log.js";
4
+ import { redactHead } from "../observability/run-terminal.js";
5
5
  function statusForTerminal(t) {
6
6
  return t === "fixed" || t === "candidate_only" ? "completed" : "failed";
7
7
  }
@@ -16,7 +16,7 @@ import { attachRepairLoopDeps } from "./repair-wire.js";
16
16
  import { routePlanWithFallback, validateSubtasks } from "./planner.js";
17
17
  import { createEngineNoticeSeat } from "../boot/runner-deps.js";
18
18
  import { currentPrincipal } from "../observability/principal-context.js";
19
- import { redactHead } from "../observability/run-terminal-log.js";
19
+ import { redactHead } from "../observability/run-terminal.js";
20
20
  const REPAIR_LOOP_WIRED = true;
21
21
  const sh = (env) => async (cmd) => {
22
22
  const r = await env.exec(`bash -lc ${JSON.stringify(cmd)}`);
@@ -221,6 +221,22 @@ declarations?: {
221
221
  * `normalizeMemorySpec(spec)?.enabled === true`。S-405 之后 `memory:"off"` 铸的是「键在场 + `enabled:false`」(保留事实),
222
222
  * 任何按「键在不在场」判挂没挂的读者从那一天起都读错(改前 `memory-notice` 正是那样,把无记忆面的披露一起吞掉)。
223
223
  * 消费方拿本函数的布尔,不拿 `spec.memory` 自己判。
224
+ *
225
+ * ⚠️ **本函数会抛,而「抛」本身就是一条判据**(S-424 补注)。`normalizeMemorySpec` 对两形直接 throw
226
+ * (亲核安装态 core 7.22.0 `dist/core/memory.js:367-372` 与 `:373-385`):
227
+ * · 单数 `scope` 键在场 ⇒ `code:"config.memory_scope_spelling"`(core 已删的旧拼写;它的报错原话
228
+ * 是「Refusing to start with memory silently off」—— 静默关闭正是那次 HIGH 的伤害面);
229
+ * · `capture` 在场且不是字面 `"off"` ⇒ `code:"config.memory_capture_spelling"`。
230
+ *
231
+ * 这两形在本仓的 wire 面上**都到不了这里**,各有属主:
232
+ * · 请求体侧 = 值闭包门 `singleMemberOffFieldIssue`(`src/request-value-closure.ts`;fresh 400 与 resume
233
+ * 重放共用的同一只)—— 到得了下游的 `memory`/`memoryCapture` 只可能是字面 `"off"` 或缺席;
234
+ * · spec 侧 = 唯一铸点 {@link memorySpecForRequest}(本文件)—— 它恒产 `scopes: [scope, ...extras]`,
235
+ * 从不产单数 `scope`,`capture` 也只在声明为 `"off"` 时才铸。
236
+ *
237
+ * 所以这里抛 = **调用方没先过值闭包门**(手搓 spec、或绕过铸点直接喂一份 `TaskSpec.memory`),不是这一腿
238
+ * 的运行期异常,**不要在本函数里加吞异常的臂**:吞掉就退回「memory 静默整体关闭」,即上面那条报错原话
239
+ * 拒绝的那件事。要放宽/收紧值域,改上面两个属主。
224
240
  */
225
241
  export declare function memoryFaceMounted(memory: TaskSpec["memory"]): boolean;
226
242
  //# sourceMappingURL=memory-scope.d.ts.map
@@ -141,6 +141,10 @@ export declare const FAIL_OPEN_TAGS: {
141
141
  readonly cls: "F";
142
142
  readonly note: "#261 fleet 存活对账腿的一次 durable 读失败/超预算(2s)⇒ **本周期整轮跳过**并开熔断,不做任何投影。放行的最坏后果 = 幽灵行(发布方已死、行僵在内存 Map 里)在面板上多活几个周期,与本腿存在之前的行为等同(那时它永远活着),不是新损失;真源不受影响(`GET /v1/runs/:id` 照常)。方向刻意 fail-open 且**只向留行一侧**:读不出来 ≠ 该退休——库抖一下就把一屏在跑的任务从面板上抹掉,比多留一条幽灵行伤得多。必须留痕:静默吞掉之后「对账腿为什么一直没生效」在遥测里没有任何痕迹,而本腿的全部价值就是「幽灵行会自己走」。";
143
143
  };
144
+ readonly "server.fleet.terminal-notify": {
145
+ readonly cls: "F";
146
+ readonly note: "S-450:**两条臂共用**(detail 里 `read-failed` 分得开)—— ① `observability/run-terminal.ts` 的**行为订阅者**扇出(唯一铸点 `notifyRunTerminal`,三只 store 的 CAS 赢分支各调一次):某个订阅者(今天只有 fleet 对账腿的候补窗升级腿)在 `setTerminal` 的调用栈上抛错 ⇒ 吞掉并计数,终局写照常成功;② `fleet/fleet-reconciler.ts` 的事件腿在收到事件后那一次 durable 点读失败 ⇒ 这条行留在候补窗里等周期臂。⚠️ 同一只铸点上的**日志腿**(`setRunTerminalLogObserver`)走的是**相反**契约(刻意不 try、抛出让 `setTerminal` reject),**不计本 tag** —— 读遥测别把两席混成一件。方向承重:这条腿的全部价值是「把候补窗行的成对终帧从『下一个对账周期(≤60s)』提前到『durable 写落地的同一 tick』」,它是一格**投影提速**;把它的 bug 外溢成终局写 reject 会让 run 卡 running 到 reaper、claim 悬挂([868] 指纹),代价高出几个量级。放行的最坏后果 = 这条行的成对终帧退回到周期臂补发,**与本件存在之前的行为逐字等同**,不是新损失;故 F 类。必须留痕:静默吞掉之后「事件腿为什么一直没生效」在遥测里没有任何痕迹,而面板上看到的只是『偶尔慢一分钟』这种没人会立案的症状。";
147
+ };
144
148
  readonly "server.fleet.run-status-unmapped": {
145
149
  readonly cls: "F";
146
150
  readonly note: "A-032 P1-④:`runStatusToFleet` 收到**词表外**的 run 状态词(闭集签名之外的唯一来路 = `rowToRun` 把无约束的 status 文本列裸 cast,滚动升级里更新的副本写的新词被旧副本读到)⇒ 折成 `idle`。放行的最坏后果 = 该行在 fleet 面板上**永久滞留**(removal 集 {completed,failed,killed} 收不到 idle),纯展示面、不影响 run 本身与任何执法判据,故 F 类。方向刻意不改(把 miss 折成终局会把一条还在跑的任务从面板上摘掉,误摘比多一行更伤)。留痕是承重的:2026-06-28 on-box e2e 逮到的 `blocked` 泄漏当年只能靠人眼在面板上发现——计数让下一次词表漂移在遥测里当场显形。编译期一侧已由闭集入参 + `never` 臂执法。";
@@ -189,6 +193,10 @@ export declare const FAIL_OPEN_TAGS: {
189
193
  readonly cls: "F";
190
194
  readonly note: "S-02 codex R1-[medium](验真后修):decide 的 409 `approval_stale` 臂对**调用方回显的旧 token** 做归属判定(`cs.get(binding.checkpointToken)`),那次读**抛了**(store 抖动 / 版本守卫 / 行恰被清理)。修前这里是静默 `catch(()=>null)`,「读不出」被折成「确认不在库」——叠上 S-02 的 404 收口后,一次 store 抖动就会把合法旧 token 的 409+terminal 谎报成 404「没有这条审批」。修后:unreadable ⇒ **保持 409**(`terminal` 不披露——证不出归属就不说,与 2026-07-26 纪律同向;404 折叠只在读成功且未命中时走,探测方无法自控 store 故障 ⇒ 谕示封闭不破)。放行的最坏后果 = 该次拒体 `terminal` 诚实缺席(`currentPending` 由它自己的读口与属主复核另判,不受本臂牵连),壳退回重拉列表,judgment 面 fail-safe,故 F 类。留痕理由:这次读是 terminal 披露与 404 折叠两个判定的输入,长期抖动必须在遥测显形。";
191
195
  };
196
+ readonly "server.resume.reopen-confirm-unreadable": {
197
+ readonly cls: "F";
198
+ readonly note: "S-447(#60 M2 自查项,`http/resume-legs.ts` 的 `confirmCheckpointReopened`):续跑腿在 core 给出 reopen 族失败后按 **token** 复核「这张 checkpoint 是不是又 pending 了」,这一读抛(库拖/版本太新/店不可达)。**方向本来就是 fail-closed**:读不出 ⇒ `return true` ⇒ 「不写任何终局、重新 park」(`:1206-1212` 头注已把取舍与有界代价写死:错 park 由 `reapSuspended` 兑,错终局会孤儿化一张活 park 到 TTL)—— 所以这条腿不是 P 类,缺的只是**留痕**。放行的最坏后果 = 多一次多余的 re-park(一张已经被决掉的卡重新挂到 reaper 窗里),人面上是「这条续跑没动」而不是谁被放行了。必须登记的理由是 **uniformity**:同文件三只同形读(`:249` `server.approvals.stale-echoed-token-unreadable` · `:288` `server.approvals.stale-current-pending-unreadable` · 本腿)中只有它是黑的,于是「店一直读不出所以每条续跑都在白白 re-park」与「一切正常」在遥测上同形。计数非零 = 这台机器的 checkpoint 店在拖,运维要去看库。";
199
+ };
192
200
  readonly "server.approvals.stale-current-pending-unreadable": {
193
201
  readonly cls: "F";
194
202
  readonly note: "S-02 件2([5522]④→[5525]):409 `approval_stale` 拒体铸 additive 指路键 `currentPending`(本会话当前 pending 的 D-1 坐标,壳一跳重定位)时,当前 pending 行的 `cs.get(token)` 读**抛了**(store 抖动 / 滚动升级期 checkpoint 格式 version guard / 行恰被并发消费)⇒ 本次拒体**缺 `currentPending` 键**,409 本体与 `terminal` 判定照旧。放行的最坏后果 = 壳退回该键到货前的行为(重拉 GET /v1/approvals 自行重定位),纯指路/便利面,不参与任何门/CAS/resume 判定,故 F 类(同族先例:`server.park.toolcallid-read-failed`,同为 cs.get 投影读失败臂)。必须留痕:键缺席与「此刻确实没有 pending」在 wire 上同形,不计数则「指路为什么总缺」在遥测里永不显形。";
@@ -132,6 +132,10 @@ export const FAIL_OPEN_TAGS = {
132
132
  cls: "F",
133
133
  note: "#261 fleet 存活对账腿的一次 durable 读失败/超预算(2s)⇒ **本周期整轮跳过**并开熔断,不做任何投影。放行的最坏后果 = 幽灵行(发布方已死、行僵在内存 Map 里)在面板上多活几个周期,与本腿存在之前的行为等同(那时它永远活着),不是新损失;真源不受影响(`GET /v1/runs/:id` 照常)。方向刻意 fail-open 且**只向留行一侧**:读不出来 ≠ 该退休——库抖一下就把一屏在跑的任务从面板上抹掉,比多留一条幽灵行伤得多。必须留痕:静默吞掉之后「对账腿为什么一直没生效」在遥测里没有任何痕迹,而本腿的全部价值就是「幽灵行会自己走」。",
134
134
  },
135
+ "server.fleet.terminal-notify": {
136
+ cls: "F",
137
+ note: "S-450:**两条臂共用**(detail 里 `read-failed` 分得开)—— ① `observability/run-terminal.ts` 的**行为订阅者**扇出(唯一铸点 `notifyRunTerminal`,三只 store 的 CAS 赢分支各调一次):某个订阅者(今天只有 fleet 对账腿的候补窗升级腿)在 `setTerminal` 的调用栈上抛错 ⇒ 吞掉并计数,终局写照常成功;② `fleet/fleet-reconciler.ts` 的事件腿在收到事件后那一次 durable 点读失败 ⇒ 这条行留在候补窗里等周期臂。⚠️ 同一只铸点上的**日志腿**(`setRunTerminalLogObserver`)走的是**相反**契约(刻意不 try、抛出让 `setTerminal` reject),**不计本 tag** —— 读遥测别把两席混成一件。方向承重:这条腿的全部价值是「把候补窗行的成对终帧从『下一个对账周期(≤60s)』提前到『durable 写落地的同一 tick』」,它是一格**投影提速**;把它的 bug 外溢成终局写 reject 会让 run 卡 running 到 reaper、claim 悬挂([868] 指纹),代价高出几个量级。放行的最坏后果 = 这条行的成对终帧退回到周期臂补发,**与本件存在之前的行为逐字等同**,不是新损失;故 F 类。必须留痕:静默吞掉之后「事件腿为什么一直没生效」在遥测里没有任何痕迹,而面板上看到的只是『偶尔慢一分钟』这种没人会立案的症状。",
138
+ },
135
139
  "server.fleet.run-status-unmapped": {
136
140
  cls: "F",
137
141
  note: "A-032 P1-④:`runStatusToFleet` 收到**词表外**的 run 状态词(闭集签名之外的唯一来路 = `rowToRun` 把无约束的 status 文本列裸 cast,滚动升级里更新的副本写的新词被旧副本读到)⇒ 折成 `idle`。放行的最坏后果 = 该行在 fleet 面板上**永久滞留**(removal 集 {completed,failed,killed} 收不到 idle),纯展示面、不影响 run 本身与任何执法判据,故 F 类。方向刻意不改(把 miss 折成终局会把一条还在跑的任务从面板上摘掉,误摘比多一行更伤)。留痕是承重的:2026-06-28 on-box e2e 逮到的 `blocked` 泄漏当年只能靠人眼在面板上发现——计数让下一次词表漂移在遥测里当场显形。编译期一侧已由闭集入参 + `never` 臂执法。",
@@ -180,6 +184,10 @@ export const FAIL_OPEN_TAGS = {
180
184
  cls: "F",
181
185
  note: "S-02 codex R1-[medium](验真后修):decide 的 409 `approval_stale` 臂对**调用方回显的旧 token** 做归属判定(`cs.get(binding.checkpointToken)`),那次读**抛了**(store 抖动 / 版本守卫 / 行恰被清理)。修前这里是静默 `catch(()=>null)`,「读不出」被折成「确认不在库」——叠上 S-02 的 404 收口后,一次 store 抖动就会把合法旧 token 的 409+terminal 谎报成 404「没有这条审批」。修后:unreadable ⇒ **保持 409**(`terminal` 不披露——证不出归属就不说,与 2026-07-26 纪律同向;404 折叠只在读成功且未命中时走,探测方无法自控 store 故障 ⇒ 谕示封闭不破)。放行的最坏后果 = 该次拒体 `terminal` 诚实缺席(`currentPending` 由它自己的读口与属主复核另判,不受本臂牵连),壳退回重拉列表,judgment 面 fail-safe,故 F 类。留痕理由:这次读是 terminal 披露与 404 折叠两个判定的输入,长期抖动必须在遥测显形。",
182
186
  },
187
+ "server.resume.reopen-confirm-unreadable": {
188
+ cls: "F",
189
+ note: "S-447(#60 M2 自查项,`http/resume-legs.ts` 的 `confirmCheckpointReopened`):续跑腿在 core 给出 reopen 族失败后按 **token** 复核「这张 checkpoint 是不是又 pending 了」,这一读抛(库拖/版本太新/店不可达)。**方向本来就是 fail-closed**:读不出 ⇒ `return true` ⇒ 「不写任何终局、重新 park」(`:1206-1212` 头注已把取舍与有界代价写死:错 park 由 `reapSuspended` 兑,错终局会孤儿化一张活 park 到 TTL)—— 所以这条腿不是 P 类,缺的只是**留痕**。放行的最坏后果 = 多一次多余的 re-park(一张已经被决掉的卡重新挂到 reaper 窗里),人面上是「这条续跑没动」而不是谁被放行了。必须登记的理由是 **uniformity**:同文件三只同形读(`:249` `server.approvals.stale-echoed-token-unreadable` · `:288` `server.approvals.stale-current-pending-unreadable` · 本腿)中只有它是黑的,于是「店一直读不出所以每条续跑都在白白 re-park」与「一切正常」在遥测上同形。计数非零 = 这台机器的 checkpoint 店在拖,运维要去看库。",
190
+ },
183
191
  "server.approvals.stale-current-pending-unreadable": {
184
192
  cls: "F",
185
193
  note: "S-02 件2([5522]④→[5525]):409 `approval_stale` 拒体铸 additive 指路键 `currentPending`(本会话当前 pending 的 D-1 坐标,壳一跳重定位)时,当前 pending 行的 `cs.get(token)` 读**抛了**(store 抖动 / 滚动升级期 checkpoint 格式 version guard / 行恰被并发消费)⇒ 本次拒体**缺 `currentPending` 键**,409 本体与 `terminal` 判定照旧。放行的最坏后果 = 壳退回该键到货前的行为(重拉 GET /v1/approvals 自行重定位),纯指路/便利面,不参与任何门/CAS/resume 判定,故 F 类(同族先例:`server.park.toolcallid-read-failed`,同为 cs.get 投影读失败臂)。必须留痕:键缺席与「此刻确实没有 pending」在 wire 上同形,不计数则「指路为什么总缺」在遥测里永不显形。",
@@ -28,6 +28,9 @@ export declare class Metrics {
28
28
  * needed). Counters are cumulative totals; histograms are reported as averages (sum/count). */
29
29
  summarize(): MetricsSummary;
30
30
  }
31
+ /** S-451:`/metrics/summary` 上「失败最多的路由」保留几条。看板要的是**头部**,不是全表;
32
+ * `routeLabel` 的值域本来就有界(路由声明表 + `"other"`),这个上限只是让这张脸的大小与路由表长解耦。 */
33
+ export declare const HTTP_ERROR_ROUTE_TOP_N = 10;
31
34
  export interface MetricsSummary {
32
35
  runsActive: number;
33
36
  tasks: Record<string, number>;
@@ -61,6 +64,15 @@ export interface MetricsSummary {
61
64
  verifications: Record<string, number>;
62
65
  councilRuns: Record<string, number>;
63
66
  toolErrors: Record<string, number>;
67
+ /** S-451(additive,7.87.0):窗内 HTTP **失败**请求数,按状态码**类**聚合 —— 键只有 `"4xx"` / `"5xx"`
68
+ * 两种,2xx/3xx 一格不进。⚠️ `"4xx"` 里**含 `499`**(本仓给「客户端在响应结束前断连」铸的标签,
69
+ * SSE 长连接上是常态)—— 看一场真风暴时按 {@link httpErrorsByRoute} 分辨是哪条腿。
70
+ * 空对象 = 窗内零失败(与 `tasks`/`toolErrors` 同律:键恒在场,不用缺席表示零)。 */
71
+ httpErrorsByClass: Record<string, number>;
72
+ /** S-451(additive,7.87.0):失败(4xx+5xx 合计)最多的前 {@link HTTP_ERROR_ROUTE_TOP_N} 条 **route 标签**
73
+ * (`routeLabel` 的低基数形,id 已折成 `:id`;未命中路由表的落 `"other"`)。按计数降序。
74
+ * 这是「180 次 404 到底打在哪」的那一格。 */
75
+ httpErrorsByRoute: Record<string, number>;
64
76
  }
65
77
  export interface MetricSnapshot {
66
78
  counters: Array<{
@@ -188,9 +188,25 @@ export class Metrics {
188
188
  toolErrors: Object.fromEntries([...(this.counters.get("tool_calls_total")?.series.values() ?? [])]
189
189
  .filter((s) => s.labels.ok === "false")
190
190
  .map((s) => [s.labels.name ?? "?", s.value])),
191
+ ...(() => {
192
+ const failures = [...(this.counters.get("http_requests_total")?.series.values() ?? [])]
193
+ .map((s) => ({ cls: /^([45])\d\d$/.exec(s.labels.status ?? "")?.[1], route: s.labels.route ?? "?", value: s.value }))
194
+ .filter((x) => x.cls !== undefined);
195
+ const byClass = {};
196
+ const byRoute = {};
197
+ for (const f of failures) {
198
+ byClass[`${f.cls}xx`] = (byClass[`${f.cls}xx`] ?? 0) + f.value;
199
+ byRoute[f.route] = (byRoute[f.route] ?? 0) + f.value;
200
+ }
201
+ return {
202
+ httpErrorsByClass: byClass,
203
+ httpErrorsByRoute: Object.fromEntries(Object.entries(byRoute).sort((a, b) => b[1] - a[1]).slice(0, HTTP_ERROR_ROUTE_TOP_N)),
204
+ };
205
+ })(),
191
206
  };
192
207
  }
193
208
  }
209
+ export const HTTP_ERROR_ROUTE_TOP_N = 10;
194
210
  export function createMetrics() {
195
211
  const m = new Metrics();
196
212
  m.counter("metric_gauge_eval_errors_total", "Dynamic gauge eval errors by gauge name (an erroring gauge emits NO sample that scrape — absence means unknown, not 0)");
@@ -270,6 +286,7 @@ export function createMetrics() {
270
286
  m.counter("compaction_events_total", "Compaction lifecycle events by outcome (started/completed/failed/skipped) and trigger");
271
287
  m.counter("hook_llm_calls_total", "prompt/agent hook entries that completed a model call (hooks 3b), by type");
272
288
  m.counter("auth_bridge_verify_total", "Registry SSO JWT verifications (auth-bridge), by outcome");
289
+ m.counter("fleet_rows_reconciled_total", "Fleet rows the #261 liveness-reconcile leg acted on, by `disposition`: 'retired' = durable was terminal, the leg projected the settled pair (terminal task frame → task_remove); 'retired_deferred' = a row that had already left declaratively (removeReason:\"orphaned\") got its settled pair BACKFILLED once durable turned terminal; 'orphaned' / 'orphaned_child' = declarative exit, NO terminal was minted (the reaper owns the death ruling); 'workflow_retired' = same projection for a workflow row. `trigger` rides ONLY the retired_deferred series (S-450): 'event' = the backfill fired on the same tick a terminal write landed through the run-store write口 (single replica), 'cycle' = it fired on the 60s reconcile cycle (cross-replica writes, and terminals flipped by the BATCH reapers, which never pass through the write口). A retired_deferred series that is 100% trigger=cycle means the event leg is not wired or this deployment\'s terminals all come from those two families");
273
290
  m.counter("fleet_lease_issued_total", "Fleet trace-lease tokens issued");
274
291
  m.counter("fleet_lease_rejected_total", "Fleet trace-lease requests rejected");
275
292
  m.counter("fleet_lease_exhausted_total", "Fleet trace-lease requests rejected because the pool was exhausted");
@@ -3,8 +3,14 @@ import { type RunRecord } from "../plugins/store-contracts.js";
3
3
  export interface RunTerminalRecord {
4
4
  /** 这条 run 的账本 id = `GET /v1/runs/:id` 的 id(本仓 run 行主键名为 taskId,同一个值)。 */
5
5
  runId: string;
6
- sessionId: string;
7
- owner: string | null;
6
+ /**
7
+ * 🔴 **只在「这条终局要出声」时在场**(S-450):三只 store 只在 `runTerminalLogLevel(...) !== undefined`
8
+ * 时才多付那一次 PK 读去装它(成功终局零额外查询 —— 那条注在 `run-store-sql.ts` 的 `setTerminal` 里)。
9
+ * 日志腿恰好只在同一形下运行,所以**它读到的恒是在场的**;行为订阅者不得依赖它。
10
+ */
11
+ sessionId?: string;
12
+ /** 同 {@link RunTerminalRecord.sessionId}:只在要出声的那一形在场。`null` = 行上没有 owner。 */
13
+ owner?: string | null;
8
14
  status: RunRecord["status"];
9
15
  /** 终局结果里的引擎侧 taskId —— 只在与 {@link RunTerminalRecord.runId} **不同**时进日志(sync 腿上 core 会把它
10
16
  * 铸成 sessionId,两者同值时重复一遍只是噪音)。 */
@@ -15,8 +21,16 @@ export interface RunTerminalRecord {
15
21
  /** 行创建到终局的墙钟毫秒(store 侧用行的 createdAt 算;算不出=不传,键缺席)。 */
16
22
  elapsedMs?: number | undefined;
17
23
  }
18
- /** 观测者收到的是**已判级 + 已脱敏 + 已截断**的成品——装配层只负责把它送进 logger。 */
19
- export type RunTerminalObserver = (level: "error" | "info", fields: Record<string, unknown>) => void;
24
+ /** **日志腿**收到的是**已判级 + 已脱敏 + 已截断**的成品——装配层只负责把它送进 logger。 */
25
+ export type RunTerminalLogObserver = (level: "error" | "info", fields: Record<string, unknown>) => void;
26
+ /**
27
+ * **行为订阅者**(S-450):CAS 赢的那一刻收到整只 {@link RunTerminalRecord}。
28
+ *
29
+ * 🔴 载荷是**这次写自己的视角**,不是回读的 durable 行 —— 只有 `runId` / `status` 两位在**任何**形下
30
+ * 都为真(CAS 赢 ⇒ 行就是这个词)。日志腿专用的那几位在成功终局上**刻意缺席**(store 不为它们多付一次
31
+ * PK 往返,见 {@link RunTerminalRecord.sessionId})。要更多事实的订阅者请自己按 `runId` 读 durable。
32
+ */
33
+ export type RunTerminalSubscriber = (rec: RunTerminalRecord) => void;
20
34
  /**
21
35
  * 终局行的级别判据。`undefined` = 不打行。
22
36
  *
@@ -25,13 +39,39 @@ export type RunTerminalObserver = (level: "error" | "info", fields: Record<strin
25
39
  * 穷举 switch,并在 `blocked` 那一格给出与 fleet 读面互斥的答案)。表的编译期双向钉在属主处。
26
40
  */
27
41
  export declare function runTerminalLogLevel(status: RunRecord["status"], errorCode: string | undefined): "error" | "info" | undefined;
28
- /** 装配点(`main.ts` 唯一)。传 `undefined` 卸载(测试隔离)。 */
29
- export declare function setRunTerminalObserver(fn: RunTerminalObserver | undefined): void;
42
+ /** **日志腿**的装配点(`boot/stage-01-config.ts` 唯一)。传 `undefined` 卸载(测试隔离)。 */
43
+ export declare function setRunTerminalLogObserver(fn: RunTerminalLogObserver | undefined): void;
44
+ /**
45
+ * **行为订阅者**的登记口(S-450)。返回解除登记的句柄。
46
+ *
47
+ * 与 {@link setRunTerminalLogObserver} 是**两个语义不同的席**,不是一个带旗的列表:
48
+ * · 日志腿**恰一只**、装配层亲接、**不隔离**(抛出会让 `setTerminal` reject —— 见 {@link notifyRunTerminal});
49
+ * · 行为订阅者**可多只**、运行期来去、**逐只隔离**(抛出吞掉 + `recordFailOpen`)。
50
+ * 两条失败契约相反,所以它们必须是两个名字;混进一个列表再加一个 `isolate` 位,就是把「这条腿出事
51
+ * 该不该把 run 拖下水」这个**语义**降级成一个**配置**。
52
+ */
53
+ export declare function subscribeRunTerminal(fn: RunTerminalSubscriber): () => void;
54
+ /** test-only:清空行为订阅者(用例之间不串台;日志腿用 `setRunTerminalLogObserver(undefined)`)。 */
55
+ export declare function resetRunTerminalSubscribersForTest(): void;
30
56
  /**
31
- * store 的终局写口在 **CAS 赢了之后**调用它。未装配观测者 ⇒ 无操作(纯内存/无 boot 的单测车道)。
57
+ * 🔴 **run 行翻终局的唯一铸点** —— 三个 run store 的 `setTerminal` 在 **CAS 赢了之后**各调它一次
58
+ * (SQL 腿 `w.affected > 0`,file / memory 腿在同判据的 CAS 分支内)。「CAS 赢了才发」是**恰一次**的来源:
59
+ * 调用侧的兜底腿有意会对同一行重复写(cancel × leg-throw × reaper 三向),打空的那几次一个字都不发。
60
+ *
61
+ * 两条出口,**失败契约相反**,顺序承重:
62
+ * ① **行为订阅者先**({@link subscribeRunTerminal},逐只 try)—— 它们要在日志腿万一违约抛出之前跑完;
63
+ * ② **日志腿后**({@link setRunTerminalLogObserver},级别筛 + 脱敏 + 不 try)。
64
+ *
65
+ * 为什么日志腿**刻意不 try**(原文保留,[ref] 的成文理由):静默吞掉观测者异常 = 又造一条「走了兜底与
66
+ * 一切正常同形」的路,方向与本模块的存在理由相反;生产装配的那一只只调 `Logger`(`createLogger` 的 emit
67
+ * 内部已把 JSON.stringify 与 write 全部 try 住,结构上不抛)。
68
+ * 为什么行为订阅者**必须 try**(S-450 新加的那一半):它们是**行为腿**,不是一只结构上不抛的 logger;
69
+ * 而本函数跑在 `setTerminal` 的调用栈上、**CAS 已经赢了、行已经落盘**,此时把订阅者的 bug 放大成
70
+ * 「终局写 reject」= run 卡 `running` 到 reaper + claim 悬挂([ref] 指纹)。吞但**不静默**:
71
+ * `recordFailOpen("server.fleet.terminal-notify")`(F 类,普查登记在案)。
32
72
  *
33
- * 脱敏:`errorMessage` 过 `redactSecrets` 再截断到 {@link MESSAGE_CAP} —— provider 的错误体
34
- * 会原样回显请求片段(取证里的 403 体带订阅链接;别的 provider 会回显 Authorization 头前缀),
73
+ * 脱敏(只在日志腿那一格):`errorMessage` 过 `redactSecrets` 再截断到 {@link MESSAGE_CAP} —— provider 的
74
+ * 错误体会原样回显请求片段(取证里的 403 体带订阅链接;别的 provider 会回显 Authorization 头前缀),
35
75
  * 而引擎日志是运维面、常被整条采集走。`errorCode` / `model` 是闭集式短标量,verbatim。
36
76
  */
37
77
  export declare function notifyRunTerminal(rec: RunTerminalRecord): void;
@@ -164,4 +204,4 @@ export declare function memoRedactTerminalResult<T extends Parameters<typeof red
164
204
  export declare function diffScanShadowCountForTest(): number;
165
205
  export declare function resetDiffScanShadowCountForTest(): void;
166
206
  export declare function resetReadRedactionMemoForTest(): void;
167
- //# sourceMappingURL=run-terminal-log.d.ts.map
207
+ //# sourceMappingURL=run-terminal.d.ts.map