Files
openclaw/src/plugin-sdk/session-transcript-hit.ts
T
Peter Steinberger 4273ca9dbd refactor(sessions): remove file-era transcript runtime (#113233)
* refactor(sessions): keep helper transcripts in memory

* refactor(sessions): remove file-era transcript storage

* test(sessions): use SQLite identity in attempt persistence

* test(codex): isolate legacy transcript fixtures

* fix(sessions): preserve SQLite transcript identity

* fix(sessions): harden transcript lifecycle invariants

* fix(sessions): validate transcript identities

* fix(sessions): close identity compatibility gaps

* fix(sessions): preserve leaf and plugin identities

* fix(sessions): retain dispatch transcript targets

* fix(sessions): preserve active transcript context

* fix(sessions): isolate artifact accounting

* fix(sessions): bound SQLite usage accounting

* fix(sessions): retain bounded latest usage

* fix(sessions): align rebased transcript targets

* test(sessions): align accessor scope fixture

* fix(telegram): derive SQLite transcript identity

* refactor(sessions): remove file-era compaction residue

* chore(sessions): lower max-lines baseline

* fix(sessions): preserve structured transcript identity

* test(sessions): align doctor identity assertions

* fix(sessions): isolate default SDK database

* refactor(sessions): remove dead file-era exports

* fix(sessions): reconcile SQLite transcript identity

* fix(sessions): pass checkpoint identity explicitly

* test(sessions): make entry field probe explicit

* test(sessions): satisfy transcript cleanup lint

* test(sessions): align diagnostics identity proof

* fix(sessions): finish transcript runtime teardown

* fix(sessions): preserve transcript identity invariants

* fix(sessions): harden transcript compatibility edges

* fix(sessions): preserve checkpoint transcript anchors

* fix(sessions): preserve SQLite lifecycle invariants

* fix(sessions): retarget compaction successors

* test(sessions): preserve transcript fixture semantics

* feat(plugin-sdk): add command transcript targets

* fix(sessions): serialize transcript rewrites

* fix(sessions): validate legacy successor identity

* fix(sessions): normalize compaction ownership

* fix(sessions): validate successor identity before adoption

* fix(sessions): preserve plugin transcript ownership

* fix(sessions): carry transcript identity through commands

* fix(sessions): import legacy checkpoint artifacts into SQLite

* fix(sessions): preserve successor transcript ownership

* fix(sessions): align transcript consumers with target identity

* fix(sessions): scope transcript token estimates

* fix(sessions): retain agent identity across lifecycle hooks

* fix(sessions): resolve scoped SQLite targets

* fix(sessions): isolate lifecycle transcript targets

* fix(sessions): validate compaction agent ownership

* fix(sessions): preserve reset and cleanup lifecycle

* fix(sessions): serialize prompt cleanup lifecycle

* fix(sessions): remove stale lock import

* fix(sessions): preserve reset target context

* fix(sessions): fence prompt reload takeover

* fix(sessions): unblock abort and default lifecycle reads

* fix(sessions): validate legacy successor scope

* fix(sessions): reject metadata-only runtime rows

* fix(sessions): propagate custom transcript stores

* fix(sessions): preserve adopted retry targets

* fix(sessions): allow unkeyed usage reads

* fix(sessions): harden runtime target boundaries

* fix(sessions): serialize retry transcript writes

* fix(sessions): bound prompt reload disposal

* fix(sessions): complete retry marker identity

* fix(sessions): keep legacy marker identity minimal

* test(sessions): tighten teardown fixture types

* fix(sessions): preserve compatibility target identity

* test(sessions): persist post-checkpoint boundary turn

* test(sessions): align runtime store mock contracts

* style(sessions): simplify persisted identity guard

* fix(sessions): prefer complete typed targets

* fix(sessions): recover legacy marker targets

* test(sessions): align marker lookup fixture scope

* fix(sessions): validate partial transcript targets

* fix(sessions): reconcile partial transcript identities

* fix(sessions): canonicalize compatibility identities

* test(sessions): cover compatibility aliases

* fix(sessions): adopt legacy successor identity

* fix(sessions): preserve usage read identity

* fix(sessions): preserve partial marker compatibility

* fix(sessions): validate legacy successor mappings

* fix(sessions): reconcile marker store mappings

* fix(sessions): preserve legacy fallback identity

* fix(sessions): harden marker alias resolution

* fix(sessions): prefer verified successor aliases

* fix(sessions): resolve preferred marker aliases

* fix(sessions): serialize cleanup admission

* fix(sessions): align marker lookup scopes

* fix(codex): type marker alias summaries

* style(sessions): satisfy changed lint

* test(sessions): align structured target assertions

* fix(sessions): reconcile latest identity contracts

* fix(sessions): validate transcript identity boundaries

* docs(sessions): explain stable registry keys

* fix(sessions): harden compatibility target round trips

* fix(sessions): port usage identity to split modules

* test(sessions): align subagent transcript identity

* fix(sessions): finish transcript identity migration

* fix(agents): route subagent completion capture through transcript targets

* fix(agents): settle SQLite prompt handoff during cleanup

* chore: shrink max-lines baseline after teardown

* fix(sessions): port teardown across split runtime owners

* fix(sessions): carry transcript targets through split owners

* test(agents): use SQLite compaction target in abort coverage

* chore: retain unrelated max-lines suppressions

* chore: shrink max-lines baseline after main splits

* style(agents): const compaction checkpoint locals

* fix(sessions): harden SQLite teardown boundaries

* test(sessions): use typed metadata in predicate isolation fixture

* test(agents): cover malformed settlement rejections lint-safely

* fix(sessions): close remaining SQLite identity races

* fix(agents): fail closed on incomplete successor targets

* fix(sessions): preserve transcript identity fallbacks

* fix(agents): preserve session-key abort admission

* fix(trajectory): validate incomplete export targets

* test(sessions): drop retired pricing cache imports

* fix(sessions): validate partial transcript identities

* fix(sessions): close transcript identity edge cases

* fix(plugins): reserve retired transcript locator slot

* fix(sessions): scope transcript locks by target

* style(sessions): simplify SDK initialization error

* fix(sessions): preserve initialized transcript state

* fix(codex): verify mirrored history session keys

* fix(sessions): reject stale transcript ownership

* fix(sessions): anchor asynchronous transcript ownership

* fix(sessions): measure active transcript state

* fix(sessions): preserve scoped transcript compaction

* fix(sessions): harden transcript identity and lifecycle

* fix(sessions): resolve scoped command transcript stores

* fix(sessions): make transcript appends failure-atomic

* fix(sessions): enforce scoped transcript ownership

* fix(sessions): reject cross-owner transcript handoffs

* fix(sessions): fence cleanup transcript ownership

* fix(sessions): retire stale write ownership contexts

* fix(sessions): preserve pending session migration state

* fix(sessions): validate migrated transcript ownership

* fix(sessions): validate usage transcript targets

* fix(sessions): clear predecessor transcript metadata

* fix(sessions): align durable session event targets

* fix(sessions): fence late prompt handoffs

* fix(sessions): fence lifecycle transcript fallbacks

* fix(sessions): bound zero-length memory capture

* fix(sessions): preserve transcript teardown ownership

* fix(sessions): reject duplicate cleanup ownership

* fix(sessions): serialize runtime writes with sqlite leases

* fix(sessions): close sqlite teardown concurrency gaps

* fix(sessions): preserve nested lifecycle failures

* fix(sessions): canonicalize sqlite transcript ownership

* fix(sessions): settle disposed prompt handoffs

* fix(sessions): resolve canonical attempt lock targets

* test(sessions): align canonical target fixtures

* test(sessions): retire redundant jsonl parser coverage

* refactor(sessions): split active transcript cursors

* test(memory): retire legacy marker fixture

* fix(sessions): preserve canonical transcript access after rebase

* fix(sessions): fence prompt lease and return transcript targets

* fix(sessions): colocate transcript leases with target store

* fix(sessions): canonicalize transcript lease and worker targets

* fix(sessions): preserve plugin and fork identity markers

* fix(sessions): complete sqlite transcript target migration

* fix(sessions): integrate canonical followup identity

* fix(sessions): preserve bounded transcript topology

* fix(sessions): validate transcript identity boundaries

* fix(context): separate caller and successor targets

* test(sessions): split persistence compatibility coverage

* test(sessions): preserve fixture topology efficiently

* chore(sdk): refresh plugin api baseline

* test(agents): align compaction lock target mocks

* test(sessions): seed malformed transcript fixtures directly

* fix(agents): canonicalize transcript compatibility inputs

* fix(agents): type optional tool result ids

* test(ci): stabilize loaded process timing

* test(tui): wait for collect queue admission
2026-07-27 22:33:24 -04:00

195 lines
7.7 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 { loadCombinedSessionStoreForGateway as loadGatewaySessionStore } from "../config/sessions/combined-store-gateway.js";
import type { SessionEntry } from "../config/sessions/types.js";
import type { OpenClawConfig } from "../config/types.openclaw.js";
import { isIncognitoSessionKey, 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";
/** Loads the cross-session plugin view without process-only incognito rows. */
export function loadCombinedSessionStoreForGateway(
cfg: OpenClawConfig,
opts: { agentId?: string; configuredAgentsOnly?: boolean } = {},
) {
const result = loadGatewaySessionStore(cfg, { ...opts, includeIncognito: false });
return {
storePath: result.storePath,
// Plugin search hits can be re-persisted into durable transcripts, so the
// SDK cross-session view must never expose incognito content.
store: Object.fromEntries(
Object.entries(result.store).filter(([sessionKey]) => !isIncognitoSessionKey(sessionKey)),
),
};
}
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)) {
if (isIncognitoSessionKey(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)) {
if (isIncognitoSessionKey(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);
if (!archivedOwnerAgentId) {
return [];
}
const fallbackKey = `agent:${normalizeAgentId(archivedOwnerAgentId)}:${params.stem}`;
return isIncognitoSessionKey(fallbackKey) ? [] : [fallbackKey];
}