Skip to content

Commit 2b003f1

Browse files
authored
refactor(memory-wiki): reuse canonical plugin normalization (#119449)
1 parent 752dd2b commit 2b003f1

5 files changed

Lines changed: 85 additions & 179 deletions

File tree

‎extensions/memory-wiki/src/chatgpt-import.ts‎

Lines changed: 18 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,11 @@ import {
88
} from "openclaw/plugin-sdk/memory-host-markdown";
99
import { timestampMsToIsoString } from "openclaw/plugin-sdk/number-runtime";
1010
import { FsSafeError, root as fsRoot } from "openclaw/plugin-sdk/security-runtime";
11-
import { uniqueStrings } from "openclaw/plugin-sdk/string-coerce-runtime";
11+
import {
12+
asNullableRecord,
13+
isRecord,
14+
uniqueStrings,
15+
} from "openclaw/plugin-sdk/string-coerce-runtime";
1216
import { compileMemoryWikiVault } from "./compile.js";
1317
import type { ResolvedMemoryWikiConfig } from "./config.js";
1418
import {
@@ -134,19 +138,12 @@ export type ChatGptRollbackResult = {
134138
alreadyRolledBack: boolean;
135139
};
136140

137-
function asRecord(value: unknown): Record<string, unknown> | null {
138-
if (!value || typeof value !== "object" || Array.isArray(value)) {
139-
return null;
140-
}
141-
return value as Record<string, unknown>;
142-
}
143-
144141
function normalizeWhitespace(value: string): string {
145142
return value.trim().replace(/\s+/g, " ");
146143
}
147144

148145
function isMissingConversationPageError(error: unknown): boolean {
149-
return asRecord(error)?.code === "ENOENT";
146+
return asNullableRecord(error)?.code === "ENOENT";
150147
}
151148

152149
async function readExistingConversationPage(absolutePath: string): Promise<string> {
@@ -186,30 +183,13 @@ async function loadConversations(exportInputPath: string): Promise<{
186183
const { exportPath, conversationsPath } = resolveConversationSourcePath(exportInputPath);
187184
const raw = await fs.readFile(conversationsPath, "utf8");
188185
const parsed = JSON.parse(raw) as unknown;
189-
if (Array.isArray(parsed)) {
190-
return {
191-
exportPath,
192-
conversationsPath,
193-
conversations: parsed.filter(
194-
(entry): entry is Record<string, unknown> => asRecord(entry) !== null,
195-
),
196-
};
197-
}
198-
const record = asRecord(parsed);
199-
if (record) {
200-
for (const value of Object.values(record)) {
201-
if (Array.isArray(value)) {
202-
return {
203-
exportPath,
204-
conversationsPath,
205-
conversations: value.filter(
206-
(entry): entry is Record<string, unknown> => asRecord(entry) !== null,
207-
),
208-
};
209-
}
210-
}
186+
const conversations = Array.isArray(parsed)
187+
? parsed
188+
: Object.values(asNullableRecord(parsed) ?? {}).find(Array.isArray);
189+
if (!conversations) {
190+
throw new Error(`Unrecognized ChatGPT conversations export format: ${conversationsPath}`);
211191
}
212-
throw new Error(`Unrecognized ChatGPT conversations export format: ${conversationsPath}`);
192+
return { exportPath, conversationsPath, conversations: conversations.filter(isRecord) };
213193
}
214194

215195
function isoFromUnix(raw: unknown): string | undefined {
@@ -249,7 +229,7 @@ function cleanMessageText(value: string): string {
249229
}
250230

251231
function extractMessageText(message: Record<string, unknown>): string {
252-
const content = asRecord(message.content);
232+
const content = asNullableRecord(message.content);
253233
if (content) {
254234
const parts = content.parts;
255235
if (Array.isArray(parts)) {
@@ -262,7 +242,7 @@ function extractMessageText(message: Record<string, unknown>): string {
262242
}
263243
continue;
264244
}
265-
const partRecord = asRecord(part);
245+
const partRecord = asNullableRecord(part);
266246
if (partRecord && typeof partRecord.text === "string" && partRecord.text.trim()) {
267247
collected.push(partRecord.text.trim());
268248
}
@@ -277,7 +257,7 @@ function extractMessageText(message: Record<string, unknown>): string {
277257
}
278258

279259
function activeBranchMessages(conversation: Record<string, unknown>): ChatGptMessage[] {
280-
const mapping = asRecord(conversation.mapping);
260+
const mapping = asNullableRecord(conversation.mapping);
281261
if (!mapping) {
282262
return [];
283263
}
@@ -287,13 +267,13 @@ function activeBranchMessages(conversation: Record<string, unknown>): ChatGptMes
287267
const chain: ChatGptMessage[] = [];
288268
while (currentNode && !seen.has(currentNode)) {
289269
seen.add(currentNode);
290-
const node = asRecord(mapping[currentNode]);
270+
const node = asNullableRecord(mapping[currentNode]);
291271
if (!node) {
292272
break;
293273
}
294-
const message = asRecord(node.message);
274+
const message = asNullableRecord(node.message);
295275
if (message) {
296-
const author = asRecord(message.author);
276+
const author = asNullableRecord(message.author);
297277
const role = typeof author?.role === "string" ? author.role : "unknown";
298278
const text = extractMessageText(message);
299279
if (text) {

‎extensions/memory-wiki/src/import-insights.ts‎

Lines changed: 5 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { normalizeOptionalString } from "openclaw/plugin-sdk/string-coerce-runtime";
12
import { truncateUtf16Safe } from "openclaw/plugin-sdk/text-utility-runtime";
23
// Memory Wiki plugin module implements import insights behavior.
34
import type { ResolvedMemoryWikiConfig } from "./config.js";
@@ -61,14 +62,6 @@ function normalizeFiniteInt(value: unknown): number {
6162
return Math.max(0, Math.floor(value));
6263
}
6364

64-
function normalizeTimestamp(value: unknown): string | undefined {
65-
if (typeof value !== "string") {
66-
return undefined;
67-
}
68-
const trimmed = value.trim();
69-
return trimmed.length > 0 ? trimmed : undefined;
70-
}
71-
7265
function humanizeLabelSuffix(label: string): string {
7366
const suffix = label.includes("/") ? label.split("/").slice(1).join("/") : label;
7467
return suffix
@@ -348,6 +341,8 @@ export async function listMemoryWikiImportInsights(
348341
const lastUserLine = exposeImportContent
349342
? extractDigestField(digestLines, "Last user line")
350343
: undefined;
344+
const createdAt = normalizeOptionalString(parsed.frontmatter.createdAt);
345+
const updatedAt = normalizeOptionalString(parsed.frontmatter.updatedAt);
351346
return [
352347
{
353348
pagePath: page.relativePath,
@@ -381,12 +376,8 @@ export async function listMemoryWikiImportInsights(
381376
candidateSignals,
382377
correctionSignals,
383378
preferenceSignals,
384-
...(normalizeTimestamp(parsed.frontmatter.createdAt)
385-
? { createdAt: normalizeTimestamp(parsed.frontmatter.createdAt) }
386-
: {}),
387-
...(normalizeTimestamp(parsed.frontmatter.updatedAt)
388-
? { updatedAt: normalizeTimestamp(parsed.frontmatter.updatedAt) }
389-
: {}),
379+
...(createdAt ? { createdAt } : {}),
380+
...(updatedAt ? { updatedAt } : {}),
390381
} satisfies MemoryWikiImportInsightItem,
391382
];
392383
})

‎extensions/memory-wiki/src/import-runs-state.ts‎

Lines changed: 23 additions & 61 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,11 @@ import type {
66
OpenKeyedStoreOptions,
77
PluginStateKeyedStore,
88
} from "openclaw/plugin-sdk/plugin-state-runtime";
9+
import {
10+
asNullableRecord,
11+
normalizeOptionalString,
12+
normalizeUniqueTrimmedStringList,
13+
} from "openclaw/plugin-sdk/string-coerce-runtime";
914
import pMap, { pMapSkip } from "p-map";
1015
import { walkMemoryWikiDirectory } from "./bounded-walk.js";
1116

@@ -113,13 +118,6 @@ function cloneImportRunRecord(record: ChatGptImportRunRecord): ChatGptImportRunR
113118
};
114119
}
115120

116-
function asRecord(value: unknown): Record<string, unknown> | null {
117-
if (!value || typeof value !== "object" || Array.isArray(value)) {
118-
return null;
119-
}
120-
return value as Record<string, unknown>;
121-
}
122-
123121
function normalizeImportRunEntries(value: unknown): ChatGptImportRunEntry[] {
124122
if (!Array.isArray(value)) {
125123
return [];
@@ -129,23 +127,17 @@ function normalizeImportRunEntries(value: unknown): ChatGptImportRunEntry[] {
129127
const entryPath = raw.trim();
130128
return entryPath ? [{ path: entryPath }] : [];
131129
}
132-
const entry = asRecord(raw);
130+
const entry = asNullableRecord(raw);
133131
if (!entry) {
134132
return [];
135133
}
136134
const entryPath = typeof entry.path === "string" ? entry.path.trim() : "";
137135
if (!entryPath) {
138136
return [];
139137
}
140-
const snapshotPath =
141-
typeof entry.snapshotPath === "string" && entry.snapshotPath.trim()
142-
? entry.snapshotPath.trim()
143-
: undefined;
144-
const contentHash =
145-
typeof entry.contentHash === "string" && entry.contentHash.trim()
146-
? entry.contentHash.trim()
147-
: undefined;
148-
const recoveryPaths = normalizeStringArray(entry.recoveryPaths);
138+
const snapshotPath = normalizeOptionalString(entry.snapshotPath);
139+
const contentHash = normalizeOptionalString(entry.contentHash);
140+
const recoveryPaths = normalizeUniqueTrimmedStringList(entry.recoveryPaths);
149141
return [
150142
{
151143
path: entryPath,
@@ -157,33 +149,19 @@ function normalizeImportRunEntries(value: unknown): ChatGptImportRunEntry[] {
157149
});
158150
}
159151

160-
function normalizeStringArray(value: unknown): string[] {
161-
if (!Array.isArray(value)) {
162-
return [];
163-
}
164-
return [
165-
...new Set(
166-
value
167-
.filter((entry): entry is string => typeof entry === "string")
168-
.map((entry) => entry.trim())
169-
.filter(Boolean),
170-
),
171-
];
172-
}
173-
174152
function asNonNegativeInteger(value: unknown): number {
175153
return typeof value === "number" && Number.isFinite(value) ? Math.max(0, Math.floor(value)) : 0;
176154
}
177155

178156
function normalizeMemoryWikiImportRunRecord(raw: unknown): ChatGptImportRunRecord | null {
179-
const record = asRecord(raw);
157+
const record = asNullableRecord(raw);
180158
if (!record) {
181159
return null;
182160
}
183-
const runId = typeof record.runId === "string" ? record.runId.trim() : "";
184-
const exportPath = typeof record.exportPath === "string" ? record.exportPath.trim() : "";
185-
const sourcePath = typeof record.sourcePath === "string" ? record.sourcePath.trim() : "";
186-
const appliedAt = typeof record.appliedAt === "string" ? record.appliedAt.trim() : "";
161+
const runId = normalizeOptionalString(record.runId) ?? "";
162+
const exportPath = normalizeOptionalString(record.exportPath) ?? "";
163+
const sourcePath = normalizeOptionalString(record.sourcePath) ?? "";
164+
const appliedAt = normalizeOptionalString(record.appliedAt) ?? "";
187165
if (
188166
record.version !== 1 ||
189167
record.importType !== "chatgpt" ||
@@ -194,19 +172,9 @@ function normalizeMemoryWikiImportRunRecord(raw: unknown): ChatGptImportRunRecor
194172
) {
195173
return null;
196174
}
197-
const rolledBackAt =
198-
typeof record.rolledBackAt === "string" && record.rolledBackAt.trim()
199-
? record.rolledBackAt.trim()
200-
: undefined;
201-
const rollbackStartedAt =
202-
typeof record.rollbackStartedAt === "string" && record.rollbackStartedAt.trim()
203-
? record.rollbackStartedAt.trim()
204-
: undefined;
205-
const rollbackTargetsFinalizedAt =
206-
typeof record.rollbackTargetsFinalizedAt === "string" &&
207-
record.rollbackTargetsFinalizedAt.trim()
208-
? record.rollbackTargetsFinalizedAt.trim()
209-
: undefined;
175+
const rolledBackAt = normalizeOptionalString(record.rolledBackAt);
176+
const rollbackStartedAt = normalizeOptionalString(record.rollbackStartedAt);
177+
const rollbackTargetsFinalizedAt = normalizeOptionalString(record.rollbackTargetsFinalizedAt);
210178
return {
211179
version: 1,
212180
runId,
@@ -227,7 +195,7 @@ function normalizeMemoryWikiImportRunRecord(raw: unknown): ChatGptImportRunRecor
227195
}
228196

229197
function normalizeMetaRecord(raw: unknown): MemoryWikiImportRunMetaStateRecord | null {
230-
const record = asRecord(raw);
198+
const record = asNullableRecord(raw);
231199
if (!record || record.kind !== "meta") {
232200
return null;
233201
}
@@ -247,7 +215,7 @@ function normalizeMetaRecord(raw: unknown): MemoryWikiImportRunMetaStateRecord |
247215
}
248216

249217
function normalizePathRecord(raw: unknown): MemoryWikiImportRunPathStateRecord | null {
250-
const record = asRecord(raw);
218+
const record = asNullableRecord(raw);
251219
if (
252220
!record ||
253221
(record.kind !== "created-path" && record.kind !== "updated-path") ||
@@ -259,15 +227,9 @@ function normalizePathRecord(raw: unknown): MemoryWikiImportRunPathStateRecord |
259227
) {
260228
return null;
261229
}
262-
const snapshotPath =
263-
typeof record.snapshotPath === "string" && record.snapshotPath.trim()
264-
? record.snapshotPath.trim()
265-
: undefined;
266-
const contentHash =
267-
typeof record.contentHash === "string" && record.contentHash.trim()
268-
? record.contentHash.trim()
269-
: undefined;
270-
const recoveryPaths = normalizeStringArray(record.recoveryPaths);
230+
const snapshotPath = normalizeOptionalString(record.snapshotPath);
231+
const contentHash = normalizeOptionalString(record.contentHash);
232+
const recoveryPaths = normalizeUniqueTrimmedStringList(record.recoveryPaths);
271233
return {
272234
kind: record.kind,
273235
vaultRootKey: record.vaultRootKey,
@@ -545,7 +507,7 @@ export async function readLegacyMemoryWikiImportRunRecords(
545507
? "include"
546508
: "skip",
547509
}).catch((error: unknown) => {
548-
const code = asRecord(error)?.code;
510+
const code = asNullableRecord(error)?.code;
549511
if (code === "ENOENT") {
550512
return [];
551513
}

0 commit comments

Comments
 (0)