Files
openclaw/src/plugin-sdk/session-transcript-hit.ts
Peter Steinberger 6b95f98fe7 fix(core): make indexed access explicit across remaining src (NUIA phase 3b) (#104773)
* fix(core): make indexed access explicit in auto-reply, infra, and config

Part 1/3 of the src NUIA phase-3b burn-down (#104600): iteration and
destructuring over index reads, boundary guards on parsed input, and
named invariants. Config path walkers bind the path head once; SQLite
migration key handling is hoisted without query-shape changes.

* fix(core): make indexed access explicit in cli, gateway, commands, security, shared

Part 2/3: argv/token selection restructured, gateway event/attachment
invariants named, security parsers stay fail-closed (invariant
violations throw), edit-distance matrices access checked entries.

* fix(core): make indexed access explicit across remaining src surfaces

Part 3/3: channels, plugins, process, cron, plugin-sdk, media, logging,
tui, hooks, daemon, and small directories. Latent bug fixed: a tailnet
resolver could leak undefined through a string|null contract and now
fails with a descriptive local error.

* fix(core): keep optional boundaries optional after per-commit review

Review findings: expectDefined misused where absence is a legitimate
state. CLI --profile/route-args missing next tokens take their existing
miss paths; help normalization compares --help against the last
positional again; first-time plugin install spreads absent cfg.plugins;
denylist scan iterates manifest dependency entries instead of throwing
on omitted sections; tailnet resolver returns a guaranteed string at
the source instead of a caller-side undefined throw.

* refactor(core): closed-key provider labels and honest optional passthroughs

PROVIDER_LABELS becomes a satisfies-typed closed record (static reads
provably defined; dynamic lookups go through providerUsageLabel with
honest string|undefined). Status-scan overview passes its optional
params through unchanged instead of asserting them.

* fix(channels): make getChatChannelMeta honestly optional

The original signature claimed ChatChannelMeta while leaking undefined
on bundled channel id metadata drift; three of four callers already
handled absence. The return type now says so, and the one assuming
caller falls back to the raw channel label.

* fix(core): index-safety for post-rebase main drift

Covers the sqlite-sessions flip and auth-source-plan code that landed
mid-phase, plus the channel-validation test consuming the now honestly
optional getChatChannelMeta.

* refactor(channels): split chat-meta accessors along the SDK contract

getChatChannelMeta keeps its shipped plugin-SDK signature (defined for
bundled ids, fail-loud on impossible misses); new findChatChannelMeta
carries the drift-tolerant optional contract for core auto-enable and
formatting paths.

* fix(qa-channel): own channel metadata instead of a guaranteed-undefined catalog lookup

qa-channel spread getChatChannelMeta over an id that is never in the
bundled catalog, shipping an empty setup meta by accident; the fail-loud
SDK accessor exposed it. The channel now declares its metadata once.

* fix(gateway): heartbeat projection lookahead is optional at the transcript tail

expectDefined wrapped messages[i + 1] whose absence on the final message
is the normal case; the adjacent ternary already handled it. Restores
the plain optional read with an explicit guard in the pair condition.

* fix(plugin-sdk): channel plugin factory tolerates non-bundled channel ids again

createChannelPluginBase spreads bundled catalog meta for ANY channel id,
where absence is the normal case for external plugins; the resolver is
honestly optional again while the exported bundled-id accessor keeps the
fail-loud contract.

* fix(core): spreads of optional config sections stay optional

Fresh-setup and first-install paths (crestodian setup inference, hook
installs, agent config base, target agent models) legitimately lack the
section being rebuilt; spreading undefined is the shipped {} semantics.
Removes the remaining gratuitous assertion wraps found by tree audit.
2026-07-11 20:47:34 -07:00

189 lines
7.4 KiB
TypeScript

// Session transcript hit helpers describe and load matched transcript snippets for plugins.
import path from "node:path";
import { expectDefined } from "@openclaw/normalization-core";
import { normalizeOptionalString } from "../../packages/normalization-core/src/string-coerce.js";
import { uniqueStrings } from "../../packages/normalization-core/src/string-normalization.js";
import { parseUsageCountedSessionIdFromFileName } from "../config/sessions/artifacts.js";
import type { SessionEntry } from "../config/sessions/types.js";
import { normalizeAgentId } from "../routing/session-key.js";
export {
formatSessionTranscriptMemoryHitKey,
parseSessionTranscriptMemoryHitKey,
resolveSessionTranscriptMemoryHitKeyToSessionKeys,
} from "./session-transcript-memory-hit.js";
export type {
ResolveSessionTranscriptMemoryHitKeyParams,
SessionTranscriptIdentity,
SessionTranscriptMemoryHitIdentity,
SessionTranscriptMemoryHitKey,
SessionTranscriptMemoryHitKeyParams,
SessionTranscriptReadParams,
} from "./session-transcript-memory-hit.js";
export { loadCombinedSessionStoreForGateway } from "../config/sessions/combined-store-gateway.js";
const QMD_ARCHIVE_STEM_RE = /^(.+)-jsonl-(reset|deleted)-(.+)$/;
const QMD_ARCHIVE_TIMESTAMP_RE =
/^(\d{4}-\d{2}-\d{2})[tT](\d{2}-\d{2}-\d{2})(?:(?:\.|-)(\d{3}))?[zZ]$/;
function restoreQmdNormalizedArchiveTimestamp(timestamp: string): string | null {
const match = QMD_ARCHIVE_TIMESTAMP_RE.exec(timestamp);
if (!match) {
return null;
}
const [, date, time, milliseconds] = match;
return `${date}T${time}${milliseconds ? `.${milliseconds}` : ""}Z`;
}
function restoreQmdNormalizedArchiveName(mdStem: string): string | null {
const match = QMD_ARCHIVE_STEM_RE.exec(mdStem);
if (!match) {
return null;
}
const [, sessionId, reason, timestamp] = match;
const restoredTimestamp = restoreQmdNormalizedArchiveTimestamp(
expectDefined(timestamp, "session transcript hit timestamp"),
);
return restoredTimestamp ? `${sessionId}.jsonl.${reason}.${restoredTimestamp}` : null;
}
function normalizeQmdSessionStem(stem: string): string {
return stem
.normalize("NFKD")
.toLowerCase()
.replace(/[^\p{Letter}\p{Number}]+/gu, "-")
.replace(/-{2,}/g, "-")
.replace(/^-+|-+$/g, "");
}
/** Canonical session identity parsed from a transcript search-hit path. */
export type SessionTranscriptHitIdentity = {
stem: string;
liveStem?: string;
ownerAgentId?: string;
archived: boolean;
};
function parseSessionsPath(hitPath: string): { base: string; ownerAgentId?: string } {
const normalized = hitPath.replace(/\\/g, "/");
const fromSessionsRoot = normalized.startsWith("sessions/")
? normalized.slice("sessions/".length)
: normalized;
const parts = fromSessionsRoot.split("/").filter(Boolean);
const base = path.posix.basename(fromSessionsRoot);
const ownerAgentId =
normalized.startsWith("sessions/") && parts.length === 2
? normalizeAgentId(parts[0])
: undefined;
return { base, ownerAgentId };
}
/**
* Derive transcript stem `S` from a memory search hit path for `source === "sessions"`.
* Builtin index uses `sessions/<basename>.jsonl`; QMD exports use `<stem>.md`.
* Archived transcripts (`.jsonl.reset.<iso>` / `.jsonl.deleted.<iso>`) resolve
* to the same stem as the live `.jsonl` they were rotated from.
*/
export function extractTranscriptStemFromSessionsMemoryHit(hitPath: string): string | null {
return extractTranscriptIdentityFromSessionsMemoryHit(hitPath)?.stem ?? null;
}
/** Parse live/archive ownership metadata from a sessions-memory hit path. */
export function extractTranscriptIdentityFromSessionsMemoryHit(
hitPath: string,
): SessionTranscriptHitIdentity | null {
const isQmdPath = hitPath.replace(/\\/g, "/").startsWith("qmd/");
const { base, ownerAgentId } = parseSessionsPath(hitPath);
const archivedStem = parseUsageCountedSessionIdFromFileName(base);
if (archivedStem && base !== `${archivedStem}.jsonl`) {
return { stem: archivedStem, ownerAgentId, archived: true };
}
if (base.endsWith(".jsonl")) {
const stem = base.slice(0, -".jsonl".length);
return stem ? { stem, ownerAgentId, archived: false } : null;
}
if (base.endsWith(".md")) {
const mdStem = base.slice(0, -".md".length);
if (!mdStem) {
return null;
}
if (isQmdPath) {
const exportedArchiveStem = parseUsageCountedSessionIdFromFileName(mdStem);
if (exportedArchiveStem && mdStem !== `${exportedArchiveStem}.jsonl`) {
return { stem: exportedArchiveStem, liveStem: mdStem, ownerAgentId, archived: true };
}
const restoredArchiveName = restoreQmdNormalizedArchiveName(mdStem);
if (restoredArchiveName) {
const archivedStemLocal = parseUsageCountedSessionIdFromFileName(restoredArchiveName);
if (archivedStemLocal && restoredArchiveName !== `${archivedStemLocal}.jsonl`) {
return { stem: archivedStemLocal, liveStem: mdStem, ownerAgentId, archived: true };
}
}
}
return { stem: mdStem, ownerAgentId, archived: false };
}
return null;
}
/**
* Map transcript stem to canonical session store keys (all agents in the combined store).
* Session tools visibility and agent-to-agent policy are enforced by the caller (e.g.
* `createSessionVisibilityGuard`), including cross-agent cases.
*/
export function resolveTranscriptStemToSessionKeys(params: {
store: Record<string, SessionEntry>;
stem: string;
archivedOwnerAgentId?: string;
allowQmdSlugFallback?: boolean;
}): string[] {
const { store } = params;
const matches: string[] = [];
const stemAsFile = params.stem.endsWith(".jsonl") ? params.stem : `${params.stem}.jsonl`;
const parsedStemId = parseUsageCountedSessionIdFromFileName(stemAsFile);
for (const [sessionKey, entry] of Object.entries(store)) {
const sessionFile = normalizeOptionalString(entry.sessionFile);
if (sessionFile) {
const base = path.basename(sessionFile);
const fileStem = base.endsWith(".jsonl") ? base.slice(0, -".jsonl".length) : base;
if (fileStem === params.stem) {
matches.push(sessionKey);
continue;
}
}
if (entry.sessionId === params.stem || (parsedStemId && entry.sessionId === parsedStemId)) {
matches.push(sessionKey);
}
}
const deduped = uniqueStrings(matches);
if (deduped.length > 0) {
return deduped;
}
const normalizedStem = normalizeQmdSessionStem(params.stem);
if (params.allowQmdSlugFallback === true && normalizedStem) {
for (const [sessionKey, entry] of Object.entries(store)) {
const sessionFile = normalizeOptionalString(entry.sessionFile);
if (sessionFile) {
const base = path.basename(sessionFile);
const fileStem = base.endsWith(".jsonl") ? base.slice(0, -".jsonl".length) : base;
if (normalizeQmdSessionStem(fileStem) === normalizedStem) {
matches.push(sessionKey);
continue;
}
}
const entrySessionId = normalizeOptionalString(entry.sessionId);
if (entrySessionId && normalizeQmdSessionStem(entrySessionId) === normalizedStem) {
matches.push(sessionKey);
}
}
}
const normalizedDeduped = uniqueStrings(matches);
if (normalizedDeduped.length > 0) {
return normalizedDeduped.length === 1 ? normalizedDeduped : [];
}
const archivedOwnerAgentId = normalizeOptionalString(params.archivedOwnerAgentId);
return archivedOwnerAgentId
? [`agent:${normalizeAgentId(archivedOwnerAgentId)}:${params.stem}`]
: [];
}