Skip to content

Commit 9427852

Browse files
committed
refactor(skills): consolidate workshop transcript and record normalization
1 parent 85fd4c9 commit 9427852

9 files changed

Lines changed: 87 additions & 158 deletions

‎src/skills/lifecycle/skill-change-hook.ts‎

Lines changed: 1 addition & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import fs from "node:fs/promises";
22
import path from "node:path";
3+
import { normalizeOptionalString } from "@openclaw/normalization-core/string-coerce";
34
import { sha256Hex } from "../../infra/crypto-digest.js";
45
import { getGlobalHookRunner } from "../../plugins/hook-runner-global.js";
56
import type {
@@ -23,14 +24,6 @@ type SkillTreeFile = {
2324
sizeBytes: number;
2425
};
2526

26-
function normalizeOptionalString(value: unknown): string | undefined {
27-
if (typeof value !== "string") {
28-
return undefined;
29-
}
30-
const normalized = value.trim();
31-
return normalized || undefined;
32-
}
33-
3427
async function collectSkillTreeFiles(skillDir: string, relativeDir = ""): Promise<SkillTreeFile[]> {
3528
const entries = await fs.readdir(path.join(skillDir, relativeDir), { withFileTypes: true });
3629
const files: SkillTreeFile[] = [];

‎src/skills/research/autocapture.ts‎

Lines changed: 18 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { isRecord } from "@openclaw/normalization-core/record-coerce";
12
import { resolveStorePath } from "../../config/sessions/paths.js";
23
import {
34
claimSessionSkillCaptureSignals,
@@ -14,6 +15,7 @@ import { KeyedAsyncQueue } from "../../plugin-sdk/keyed-async-queue.js";
1415
import { readWorkspaceSkillFile } from "../lifecycle/workspace-skill-write.js";
1516
import { autoApplySkillProposal } from "../workshop/auto-apply.js";
1617
import { resolveSkillWorkshopConfig } from "../workshop/config.js";
18+
import { selectCurrentSkillTurnMessages } from "../workshop/experience-review-prompt.js";
1719
import { stripProposalFrontmatterForSkill } from "../workshop/frontmatter.js";
1820
import {
1921
inspectSkillProposal,
@@ -91,51 +93,41 @@ function readToolCallAction(value: unknown): string | undefined {
9193
return undefined;
9294
}
9395
}
94-
if (!input || typeof input !== "object" || Array.isArray(input)) {
96+
if (!isRecord(input)) {
9597
return undefined;
9698
}
97-
const action = (input as { action?: unknown }).action;
99+
const action = input.action;
98100
return typeof action === "string" ? action.trim().toLowerCase() : undefined;
99101
}
100102

101-
function isSkillWorkshopMutationBlock(value: unknown): boolean {
102-
if (!value || typeof value !== "object" || Array.isArray(value)) {
103+
function isSkillWorkshopMutationBlock(value: unknown): value is Record<string, unknown> {
104+
if (!isRecord(value)) {
103105
return false;
104106
}
105-
const block = value as {
106-
type?: unknown;
107-
name?: unknown;
108-
arguments?: unknown;
109-
input?: unknown;
110-
args?: unknown;
111-
};
112-
if (!TOOL_CALL_BLOCK_TYPES.has(String(block.type))) {
107+
if (!TOOL_CALL_BLOCK_TYPES.has(String(value.type))) {
113108
return false;
114109
}
115-
if (typeof block.name !== "string" || block.name.trim().toLowerCase() !== "skill_workshop") {
110+
if (typeof value.name !== "string" || value.name.trim().toLowerCase() !== "skill_workshop") {
116111
return false;
117112
}
118-
const action = readToolCallAction(block.arguments ?? block.input ?? block.args);
113+
const action = readToolCallAction(value.arguments ?? value.input ?? value.args);
119114
return action ? SKILL_WORKSHOP_MUTATING_ACTIONS.has(action) : false;
120115
}
121116

122117
function hasUnfailedSkillWorkshopMutationCall(messages: readonly unknown[]): boolean {
123118
const callIds = new Set<string>();
124119
let hasUnidentifiedCall = false;
125120
for (const message of messages) {
126-
if (!message || typeof message !== "object" || Array.isArray(message)) {
121+
if (!isRecord(message)) {
127122
continue;
128123
}
129-
const content = (message as { content?: unknown }).content;
124+
const content = message.content;
130125
const blocks = Array.isArray(content) ? content : [content];
131126
for (const block of blocks) {
132127
if (!isSkillWorkshopMutationBlock(block)) {
133128
continue;
134129
}
135-
const id =
136-
block && typeof block === "object" && !Array.isArray(block)
137-
? (block as { id?: unknown }).id
138-
: undefined;
130+
const id = block.id;
139131
if (typeof id === "string" && id) {
140132
callIds.add(id);
141133
} else {
@@ -147,36 +139,20 @@ function hasUnfailedSkillWorkshopMutationCall(messages: readonly unknown[]): boo
147139
return true;
148140
}
149141
for (const message of messages) {
150-
if (!message || typeof message !== "object" || Array.isArray(message)) {
142+
if (!isRecord(message)) {
151143
continue;
152144
}
153-
const result = message as { role?: unknown; toolCallId?: unknown; isError?: unknown };
154145
if (
155-
result.role === "toolResult" &&
156-
result.isError === true &&
157-
typeof result.toolCallId === "string"
146+
message.role === "toolResult" &&
147+
message.isError === true &&
148+
typeof message.toolCallId === "string"
158149
) {
159-
callIds.delete(result.toolCallId);
150+
callIds.delete(message.toolCallId);
160151
}
161152
}
162153
return callIds.size > 0;
163154
}
164155

165-
function currentTurnMessages(messages: readonly unknown[]): readonly unknown[] {
166-
for (let index = messages.length - 1; index >= 0; index -= 1) {
167-
const message = messages[index];
168-
if (
169-
message &&
170-
typeof message === "object" &&
171-
!Array.isArray(message) &&
172-
(message as { role?: unknown }).role === "user"
173-
) {
174-
return messages.slice(index);
175-
}
176-
}
177-
return messages;
178-
}
179-
180156
function fingerprintInstructions(instructions: readonly string[]): string {
181157
const normalized = instructions
182158
.map((instruction) => compactWhitespace(instruction).toLowerCase())
@@ -239,7 +215,7 @@ export async function runSkillResearchAutoCapture(params: {
239215
// Proposals are workspace-scoped, so different sessions must not inspect and revise the same
240216
// pending draft concurrently from stale content.
241217
await skillCaptureQueue.enqueue(workspaceDir, async () => {
242-
const turnMessages = currentTurnMessages(params.event.messages);
218+
const turnMessages = selectCurrentSkillTurnMessages(params.event.messages);
243219
if (hasUnfailedSkillWorkshopMutationCall(turnMessages)) {
244220
const signalHashes = extractDurableInstructions([...turnMessages]).map((instruction) =>
245221
fingerprintInstructions([instruction]),

‎src/skills/workshop/experience-review-prompt.ts‎

Lines changed: 29 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { isRecord } from "@openclaw/normalization-core/record-coerce";
12
import { sliceUtf16Safe, truncateUtf16Safe } from "@openclaw/normalization-core/utf16-slice";
23
import { SKILL_AUTHORING_STANDARDS_PROMPT } from "./skill-authoring-standards.js";
34

@@ -18,6 +19,23 @@ function safeJson(value: unknown): string {
1819
}
1920
}
2021

22+
export function selectCurrentSkillTurnMessages(messages: readonly unknown[]): readonly unknown[] {
23+
for (let index = messages.length - 1; index >= 0; index -= 1) {
24+
const message = messages[index];
25+
if (isRecord(message) && message.role === "user") {
26+
return messages.slice(index);
27+
}
28+
}
29+
return messages;
30+
}
31+
32+
export function countSkillModelIterations(messages: readonly unknown[]): number {
33+
return messages.reduce<number>(
34+
(count, message) => count + (isRecord(message) && message.role === "assistant" ? 1 : 0),
35+
0,
36+
);
37+
}
38+
2139
function renderContent(content: unknown): string {
2240
if (typeof content === "string") {
2341
return content;
@@ -30,17 +48,16 @@ function renderContent(content: unknown): string {
3048
if (typeof block === "string") {
3149
return block;
3250
}
33-
if (!block || typeof block !== "object" || Array.isArray(block)) {
51+
if (!isRecord(block)) {
3452
return safeJson(block);
3553
}
36-
const record = block as Record<string, unknown>;
37-
if (record.type === "text" && typeof record.text === "string") {
38-
return record.text;
54+
if (block.type === "text" && typeof block.text === "string") {
55+
return block.text;
3956
}
40-
if (["toolCall", "tool_use", "function_call"].includes(String(record.type))) {
41-
const toolName = typeof record.name === "string" ? record.name : "unknown";
57+
if (["toolCall", "tool_use", "function_call"].includes(String(block.type))) {
58+
const toolName = typeof block.name === "string" ? block.name : "unknown";
4259
return `[tool call: ${toolName}] ${safeJson(
43-
record.arguments ?? record.input ?? record.args ?? {},
60+
block.arguments ?? block.input ?? block.args ?? {},
4461
)}`;
4562
}
4663
return safeJson(block);
@@ -49,14 +66,13 @@ function renderContent(content: unknown): string {
4966
}
5067

5168
function renderMessage(message: unknown): string {
52-
if (!message || typeof message !== "object" || Array.isArray(message)) {
69+
if (!isRecord(message)) {
5370
return `[unknown]\n${safeJson(message)}`;
5471
}
55-
const record = message as Record<string, unknown>;
56-
const role = typeof record.role === "string" ? record.role : "unknown";
57-
const error = record.isError === true ? " error" : "";
58-
const toolName = typeof record.toolName === "string" ? ` ${record.toolName}` : "";
59-
return `[${role}${toolName}${error}]\n${renderContent(record.content)}`;
72+
const role = typeof message.role === "string" ? message.role : "unknown";
73+
const error = message.isError === true ? " error" : "";
74+
const toolName = typeof message.toolName === "string" ? ` ${message.toolName}` : "";
75+
return `[${role}${toolName}${error}]\n${renderContent(message.content)}`;
6076
}
6177

6278
export function formatSkillExperienceReviewTranscript(messages: readonly unknown[]): string {

‎src/skills/workshop/experience-review.ts‎

Lines changed: 4 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,9 @@ import { autoApplySkillProposal } from "./auto-apply.js";
99
import { resolveSkillWorkshopConfig } from "./config.js";
1010
import {
1111
buildSkillExperienceReviewPrompt,
12+
countSkillModelIterations,
1213
formatSkillExperienceReviewTranscript,
14+
selectCurrentSkillTurnMessages,
1315
} from "./experience-review-prompt.js";
1416
import type { SkillWorkshopProposalMutationBudget } from "./types.js";
1517

@@ -134,30 +136,6 @@ function isEligibleContext(ctx: ExperienceReviewAgentContext): boolean {
134136
.some((segment) => EXPERIENCE_REVIEW_BLOCKED_SESSION_SEGMENTS.has(segment));
135137
}
136138

137-
function currentTurnMessages(messages: readonly unknown[]): readonly unknown[] {
138-
for (let index = messages.length - 1; index >= 0; index -= 1) {
139-
const message = messages[index];
140-
if (
141-
message &&
142-
typeof message === "object" &&
143-
!Array.isArray(message) &&
144-
(message as { role?: unknown }).role === "user"
145-
) {
146-
return messages.slice(index);
147-
}
148-
}
149-
return messages;
150-
}
151-
152-
function countModelIterations(messages: readonly unknown[]): number {
153-
return messages.reduce<number>((count, message) => {
154-
if (!message || typeof message !== "object" || Array.isArray(message)) {
155-
return count;
156-
}
157-
return count + ((message as { role?: unknown }).role === "assistant" ? 1 : 0);
158-
}, 0);
159-
}
160-
161139
export async function prepareSkillExperienceReviewCandidate(
162140
candidate: ExperienceReviewCandidate,
163141
config: OpenClawConfig,
@@ -336,13 +314,13 @@ export function createSkillExperienceReviewScheduler(deps: ExperienceReviewSched
336314
return;
337315
}
338316

339-
const turnMessages = currentTurnMessages(params.event.messages);
317+
const turnMessages = selectCurrentSkillTurnMessages(params.event.messages);
340318
// Native harnesses can report exact provider iterations even when their
341319
// transcript projection has a different assistant-message cardinality.
342320
const reportedModelIterations = params.ctx.modelIterations;
343321
const modelIterations =
344322
reportedModelIterations === undefined
345-
? countModelIterations(turnMessages)
323+
? countSkillModelIterations(turnMessages)
346324
: Number.isSafeInteger(reportedModelIterations) && reportedModelIterations >= 0
347325
? reportedModelIterations
348326
: 0;

‎src/skills/workshop/history-scan-state.ts‎

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { createHash } from "node:crypto";
22
import path from "node:path";
3+
import { isRecord } from "@openclaw/normalization-core/record-coerce";
34
import { resolveStorePath } from "../../config/sessions/paths.js";
45
import type { OpenClawConfig } from "../../config/types.openclaw.js";
56
import {
@@ -88,12 +89,7 @@ export function emptyHistoryScanResult(): SkillHistoryScanResult {
8889
}
8990

9091
export function isStoredHistoryScanState(value: unknown): value is StoredSkillHistoryScanState {
91-
return Boolean(
92-
value &&
93-
typeof value === "object" &&
94-
!Array.isArray(value) &&
95-
(value as { schema?: unknown }).schema === HISTORY_SCAN_SCHEMA,
96-
);
92+
return isRecord(value) && value.schema === HISTORY_SCAN_SCHEMA;
9793
}
9894

9995
function loadHistoryScanState(params: Omit<SkillHistoryScanScope, "direction">) {

‎src/skills/workshop/history-scan-transcript-content.ts‎

Lines changed: 10 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,15 @@
1+
import { isRecord } from "@openclaw/normalization-core/record-coerce";
12
import { sliceUtf16Safe, truncateUtf16Safe } from "@openclaw/normalization-core/utf16-slice";
23
import { filterHeartbeatTranscriptTurns } from "../../auto-reply/heartbeat-transcript-turns.js";
34
import { redactSensitiveText } from "../../logging/redact.js";
4-
import { formatSkillExperienceReviewTranscript } from "./experience-review-prompt.js";
5+
import {
6+
countSkillModelIterations,
7+
formatSkillExperienceReviewTranscript,
8+
} from "./experience-review-prompt.js";
59

610
const HISTORY_SCAN_MAX_RECENT_MESSAGES = 80;
711
const HISTORY_SCAN_MAX_LOCAL_TRANSCRIPT_BYTES = 8 * 1024 * 1024;
812

9-
function countModelIterations(messages: readonly unknown[]): number {
10-
return messages.reduce<number>((count, message) => {
11-
if (!message || typeof message !== "object" || Array.isArray(message)) {
12-
return count;
13-
}
14-
return count + ((message as { role?: unknown }).role === "assistant" ? 1 : 0);
15-
}, 0);
16-
}
17-
1813
function capSessionTranscript(transcript: string, maxChars: number): string {
1914
if (transcript.length <= maxChars) {
2015
return transcript;
@@ -32,12 +27,7 @@ function capSessionTranscript(transcript: string, maxChars: number): string {
3227

3328
function hasLegacyHookTranscriptContent(messages: readonly unknown[]): boolean {
3429
return messages.some((message) => {
35-
if (
36-
!message ||
37-
typeof message !== "object" ||
38-
Array.isArray(message) ||
39-
(message as { role?: unknown }).role !== "user"
40-
) {
30+
if (!isRecord(message) || message.role !== "user") {
4131
return false;
4232
}
4333
const rendered = formatSkillExperienceReviewTranscript([message]);
@@ -56,13 +46,9 @@ function filterSkillHistoryScanReviewMessages(
5646
if (hasLegacyHookTranscriptContent(messages)) {
5747
return undefined;
5848
}
59-
const roleMessages = messages.filter((message): message is { role: string; content?: unknown } =>
60-
Boolean(
61-
message &&
62-
typeof message === "object" &&
63-
!Array.isArray(message) &&
64-
typeof (message as { role?: unknown }).role === "string",
65-
),
49+
const roleMessages = messages.filter(
50+
(message): message is { role: string; content?: unknown } =>
51+
isRecord(message) && typeof message.role === "string",
6652
);
6753
return filterHeartbeatTranscriptTurns(roleMessages, heartbeatPrompt);
6854
}
@@ -77,7 +63,7 @@ export function prepareSkillHistoryScanReviewMessages(
7763
}
7864
return {
7965
messages: filtered.slice(-HISTORY_SCAN_MAX_RECENT_MESSAGES),
80-
modelIterations: countModelIterations(filtered),
66+
modelIterations: countSkillModelIterations(filtered),
8167
};
8268
}
8369

‎src/skills/workshop/proposal-origin-validation.ts‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,15 @@
1+
import { isRecord } from "@openclaw/normalization-core/record-coerce";
12
import { MAX_SKILL_PROPOSAL_ORIGIN_RUN_IDS } from "./types.js";
23

34
function isValidOrigin(value: unknown): boolean {
45
if (value === undefined) {
56
return true;
67
}
7-
if (!value || typeof value !== "object" || Array.isArray(value)) {
8+
if (!isRecord(value)) {
89
return false;
910
}
10-
const origin = value as Record<string, unknown>;
1111
return ["agentId", "sessionKey", "runId", "messageId"].every((key) => {
12-
const item = origin[key];
12+
const item = value[key];
1313
return item === undefined || typeof item === "string";
1414
});
1515
}
@@ -35,7 +35,7 @@ function isValidMutationCounts(value: unknown, originRunIds: string[] | undefine
3535
if (value === undefined) {
3636
return true;
3737
}
38-
if (!value || typeof value !== "object" || Array.isArray(value)) {
38+
if (!isRecord(value)) {
3939
return false;
4040
}
4141
const allowedIds = new Set(originRunIds);

0 commit comments

Comments
 (0)