Skip to content

Commit f4871eb

Browse files
authored
refactor(types): remove chained assertions in runtime boundaries (#124082)
1 parent 250b1e6 commit f4871eb

34 files changed

Lines changed: 196 additions & 162 deletions

‎src/auto-reply/reply/agent-runner.test-fixtures.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ export function createTestFollowupRun(overrides: Partial<FollowupRun["run"]> = {
1717
sessionFile: "/tmp/session.jsonl",
1818
workspaceDir: "/tmp",
1919
config: {},
20-
skillsSnapshot: {},
20+
skillsSnapshot: { prompt: "", skills: [] },
2121
provider: "anthropic",
2222
model: "claude",
2323
thinkLevel: "low",
@@ -29,7 +29,7 @@ export function createTestFollowupRun(overrides: Partial<FollowupRun["run"]> = {
2929
skipProviderRuntimeHints: true,
3030
...overrides,
3131
},
32-
} as unknown as FollowupRun;
32+
} satisfies FollowupRun;
3333
}
3434

3535
export async function writeTestSessionStore(

‎src/cron/service/store.ts‎

Lines changed: 20 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
/** Loads, normalizes, quarantines, and persists cron service store state. */
2+
import { isRecord } from "@openclaw/normalization-core/record-coerce";
23
import { normalizeCronJobIdentityFields } from "../normalize-job-identity.js";
34
import { normalizeCronJobInput } from "../normalize.js";
45
import { getInvalidPersistedCronJobReason } from "../persisted-shape.js";
@@ -134,6 +135,12 @@ function warnInvalidPersistedCronJob(params: {
134135
);
135136
}
136137

138+
function isValidatedCronJob(
139+
value: Record<string, unknown>,
140+
): value is CronJob & Record<string, unknown> {
141+
return getInvalidPersistedCronJobReason(value) === null;
142+
}
143+
137144
/** Loads and normalizes the cron store, quarantining invalid persisted rows before runtime use. */
138145
export async function ensureLoaded(
139146
state: CronServiceState,
@@ -163,7 +170,7 @@ export async function ensureLoaded(
163170
const loadNowMs = state.deps.nowMs();
164171
// Persisted cron rows are validated lazily, so treat them as raw records at the
165172
// store boundary and only trust the CronJob shape after validation below.
166-
const loadedJobs = (loaded.store.jobs ?? []) as unknown as Record<string, unknown>[];
173+
const loadedJobs = (loaded.store.jobs ?? []).filter(isRecord);
167174
const jobs: CronJob[] = [];
168175
const durableNextRunAtMsByJobId = new Map<string, number | undefined>();
169176
const quarantinedConfigJobs: QuarantinedCronConfigJob[] = [...loaded.invalidConfigRows];
@@ -190,11 +197,16 @@ export async function ensureLoaded(
190197
}
191198
const hydratedRaw = normalized ?? raw;
192199
let invalidReason = rawInvalidReason ?? getInvalidPersistedCronJobReason(hydratedRaw);
193-
const hydratedSchedule = (hydratedRaw.schedule ?? {}) as Record<string, unknown>;
194-
if (!invalidReason && hydratedRaw.enabled !== false && hydratedSchedule.kind === "every") {
200+
const hydratedSchedule = isRecord(hydratedRaw.schedule) ? hydratedRaw.schedule : {};
201+
if (
202+
!invalidReason &&
203+
isValidatedCronJob(hydratedRaw) &&
204+
hydratedRaw.enabled &&
205+
hydratedSchedule.kind === "every"
206+
) {
195207
try {
196208
assertTimeScheduleSatisfiable(
197-
{ ...(hydratedRaw as unknown as CronJob), state: {} },
209+
{ ...hydratedRaw, state: {} },
198210
loadNowMs,
199211
computeJobNextRunAtMs,
200212
);
@@ -226,7 +238,10 @@ export async function ensureLoaded(
226238
continue;
227239
}
228240
// Validated above, so the raw record is now a trusted CronJob.
229-
const hydrated = hydratedRaw as unknown as CronJob;
241+
if (!isValidatedCronJob(hydratedRaw)) {
242+
continue;
243+
}
244+
const hydrated = hydratedRaw;
230245
jobs.push(hydrated);
231246
// Capture the value SQLite actually held before schedule-identity repair
232247
// mutates the runtime view. A later save can then publish that transition.

‎src/cron/store/row-codec.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -193,13 +193,13 @@ function bindCronJobRow(storeKey: string, job: CronStoredJob, sortOrder: number)
193193
job_json: JSON.stringify(stripJobRuntimeFields(job)),
194194
state_json: JSON.stringify(job.state ?? {}),
195195
runtime_updated_at_ms: job.updatedAtMs,
196-
schedule_identity: tryCronScheduleIdentity(job as unknown as Record<string, unknown>) ?? null,
196+
schedule_identity: tryCronScheduleIdentity({ ...job }) ?? null,
197197
sort_order: sortOrder,
198198
};
199199
}
200200

201201
function normalizeCronJobForSqlite(job: CronStoreFile["jobs"][number]): CronStoredJob | null {
202-
const raw = structuredClone(job) as unknown as Record<string, unknown>;
202+
const raw: Record<string, unknown> = { ...structuredClone(job) };
203203
const hadDeleteAfterRun = Object.hasOwn(raw, "deleteAfterRun");
204204
normalizeCronJobIdentityFields(raw);
205205
const normalized = normalizeCronJobInput(raw, { applyDefaults: true });
@@ -570,7 +570,7 @@ export function updateCronRuntimeRows(
570570
...bindStateColumns(job.state ?? {}),
571571
state_json: JSON.stringify(job.state ?? {}),
572572
runtime_updated_at_ms: job.updatedAtMs,
573-
schedule_identity: tryCronScheduleIdentity(job as unknown as Record<string, unknown>),
573+
schedule_identity: tryCronScheduleIdentity({ ...job }),
574574
})
575575
.where("store_key", "=", storeKey)
576576
.where("job_id", "=", job.id),

‎src/gateway/exec-approval-manager.ts‎

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -161,7 +161,7 @@ type PendingEntry<TPayload = ExecApprovalRequestPayload> = {
161161
record: ExecApprovalRecord<TPayload>;
162162
resolve: (decision: ExecApprovalDecision | null) => void;
163163
reject: (err: Error) => void;
164-
timer: ReturnType<typeof setTimeout>;
164+
timer: ReturnType<typeof setTimeout> | null;
165165
cleanupTimer: ReturnType<typeof setTimeout> | null;
166166
handoffRetainCount: number;
167167
handoffReleasedAtMs: number | null;
@@ -367,7 +367,7 @@ export class ExecApprovalManager<TPayload = ExecApprovalRequestPayload> {
367367
record,
368368
resolve: resolvePromise!,
369369
reject: rejectPromise!,
370-
timer: null as unknown as ReturnType<typeof setTimeout>,
370+
timer: null,
371371
cleanupTimer: null,
372372
handoffRetainCount: 0,
373373
handoffReleasedAtMs: null,
@@ -757,7 +757,9 @@ export class ExecApprovalManager<TPayload = ExecApprovalRequestPayload> {
757757
if (!pending || pending.record.resolvedAtMs !== undefined) {
758758
return false;
759759
}
760-
clearTimeout(pending.timer);
760+
if (pending.timer) {
761+
clearTimeout(pending.timer);
762+
}
761763
pending.record.resolvedAtMs = params.resolvedAtMs;
762764
if (params.decision === null) {
763765
delete pending.record.decision;
@@ -875,12 +877,16 @@ export class ExecApprovalManager<TPayload = ExecApprovalRequestPayload> {
875877
}
876878

877879
private scheduleExpiryTimer(entry: PendingEntry<TPayload>): void {
878-
const timerDelayMs = resolveApprovalTimeoutMs(entry.record.expiresAtMs - Date.now());
879-
entry.timer = setTimeout(() => {
880+
entry.timer = this.createExpiryTimer(entry.record);
881+
}
882+
883+
private createExpiryTimer(record: ExecApprovalRecord<TPayload>): ReturnType<typeof setTimeout> {
884+
const timerDelayMs = resolveApprovalTimeoutMs(record.expiresAtMs - Date.now());
885+
return setTimeout(() => {
880886
try {
881-
this.expireDue(entry.record.id);
887+
this.expireDue(record.id);
882888
} catch (error) {
883-
this.reportError(error, { approvalId: entry.record.id, operation: "expire" });
889+
this.reportError(error, { approvalId: record.id, operation: "expire" });
884890
}
885891
}, timerDelayMs);
886892
}

‎src/gateway/mcp-http.schema.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ export type McpToolSchemaEntry = {
2121

2222
function readLoopbackToolField(tool: McpLoopbackTool, key: "name" | "description" | "parameters") {
2323
try {
24-
return (tool as unknown as Record<typeof key, unknown>)[key];
24+
return tool[key];
2525
} catch {
2626
return undefined;
2727
}
@@ -45,7 +45,7 @@ function readLoopbackToolDescription(tool: McpLoopbackTool): string | undefined
4545
function readLoopbackToolParameters(tool: McpLoopbackTool): Record<string, unknown> | undefined {
4646
let value;
4747
try {
48-
value = (tool as unknown as { parameters?: unknown }).parameters;
48+
value = tool.parameters;
4949
} catch {
5050
return undefined;
5151
}

‎src/gateway/question-manager.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -116,15 +116,15 @@ export class QuestionManager {
116116
expiresAtMs,
117117
status: "pending",
118118
};
119+
const expiryTimer = setTimeout(() => this.expire(record.id), timeoutMs);
119120
const entry: QuestionEntry = {
120121
record,
121-
expiryTimer: null as unknown as ReturnType<typeof setTimeout>,
122+
expiryTimer,
122123
cleanupTimer: null,
123124
waiters: new Set(),
124125
onResolved: params.onResolved,
125126
};
126127
this.entries.set(record.id, entry);
127-
entry.expiryTimer = setTimeout(() => this.expire(record.id), timeoutMs);
128128
unrefTimer(entry.expiryTimer);
129129
return record;
130130
}

‎src/gateway/server-methods/cron.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -888,6 +888,10 @@ export const cronHandlers: GatewayRequestHandlers = {
888888
if (!assertValidParams(candidate, validateCronUpdateParams, "cron.update", respond)) {
889889
return;
890890
}
891+
if (!normalizedPatch) {
892+
respondInvalidCronParams(respond, "cron.update", "patch did not normalize");
893+
return;
894+
}
891895
const p = candidate as {
892896
id?: string;
893897
jobId?: string;
@@ -912,7 +916,7 @@ export const cronHandlers: GatewayRequestHandlers = {
912916
);
913917
return;
914918
}
915-
const patch = p.patch as unknown as CronJobPatch;
919+
const patch: CronJobPatch = normalizedPatch;
916920
const cfg = context.getRuntimeConfig();
917921
const currentJob = await context.cron.readJob(jobId);
918922
if (

‎src/gateway/server-methods/sessions-compaction-runner.ts‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import { resolveAgentWorkspaceDir } from "../../agents/agent-scope.js";
44
import { compactEmbeddedAgentSession } from "../../agents/embedded-agent.js";
55
import { resolveManualCompactionCliTarget } from "../../agents/session-runtime-compat.js";
66
import { preflightManualSessionCompaction } from "../../agents/sessions/manual-compaction-preflight.js";
7-
import type { SessionEntry as AgentSessionEntry } from "../../agents/sessions/session-manager.js";
7+
import { isIndexedSessionEntry } from "../../agents/sessions/session-manager-codec.js";
88
import { resolveIngressWorkspaceOverrideForSessionRun } from "../../agents/spawned-context.js";
99
import { normalizeReasoningLevel, normalizeThinkLevel } from "../../auto-reply/thinking.js";
1010
import type { SessionEntry } from "../../config/sessions.js";
@@ -14,7 +14,6 @@ import {
1414
resolveSessionTranscriptRuntimeTarget,
1515
} from "../../config/sessions/session-accessor.js";
1616
import {
17-
isCanonicalSessionTranscriptEntry,
1817
scanSessionTranscriptTree,
1918
selectSessionTranscriptTreePathNodes,
2019
} from "../../config/sessions/transcript-tree.js";
@@ -71,7 +70,7 @@ export async function preflightGatewaySessionCompaction(
7170
const tree = scanSessionTranscriptTree(transcriptEvents);
7271
const branch = selectSessionTranscriptTreePathNodes(tree, tree.leafId)
7372
.map((node) => node.entry)
74-
.filter(isCanonicalSessionTranscriptEntry) as unknown as AgentSessionEntry[];
73+
.filter(isIndexedSessionEntry);
7574
const preflight = preflightManualSessionCompaction(branch, {
7675
enabled: true,
7776
reserveTokens: 0,

‎src/gateway/server-reload-restart.ts‎

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -183,14 +183,8 @@ class GatewayRestartTransaction {
183183
acceptedConfig &&
184184
configDebt.restartOwnedPaths.every((path) =>
185185
isDeepStrictEqual(
186-
getConfigValueAtPath(
187-
configDebt.nextConfig as unknown as Record<string, unknown>,
188-
path.split("."),
189-
),
190-
getConfigValueAtPath(
191-
acceptedConfig as unknown as Record<string, unknown>,
192-
path.split("."),
193-
),
186+
getConfigValueAtPath({ ...configDebt.nextConfig }, path.split(".")),
187+
getConfigValueAtPath({ ...acceptedConfig }, path.split(".")),
194188
),
195189
);
196190
if (!retainsConfigDebt) {

‎src/gateway/server-runtime-state-prepare.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -211,9 +211,9 @@ export async function prepareGatewayKernelState(params: {
211211
const channelLogs = Object.fromEntries(
212212
listGatewayStartupChannelPlugins().map((plugin) => [plugin.id, logChannels.child(plugin.id)]),
213213
) as Record<ChannelId, ReturnType<typeof createSubsystemLogger>>;
214-
const channelRuntimeEnvs = Object.fromEntries(
214+
const channelRuntimeEnvs: Partial<Record<ChannelId, RuntimeEnv>> = Object.fromEntries(
215215
Object.entries(channelLogs).map(([id, logger]) => [id, runtimeForLogger(logger)]),
216-
) as unknown as Record<ChannelId, RuntimeEnv>;
216+
);
217217
const listStartupChannelGatewayMethods = () => {
218218
const methods: string[] = [];
219219
for (const plugin of listGatewayStartupChannelPlugins()) {

0 commit comments

Comments
 (0)