Files
openclaw/scripts/lib/sqlite-session-schema-baseline.ts
Peter Steinberger 55ce95fac8 feat(sessions): three-layer session ownership — agent attribution, assignable owner, participants (#125057)
* feat(sessions): stamp agent identity on spawned sessions and return spawn receipts

Agent-spawned sessions recorded the requesting session key as createdActor.id,
so the Control UI creator chip rendered an opaque key. Spawn producers now stamp
the canonical requester agent id; parent-authority validation moves to a new
trusted requesterSessionKey field. projectSessionActor enriches agent actors
with configured identity name/avatar at read time, and visible sessions_spawn
returns a sessionUrl + owner receipt with URL-first acknowledgement guidance.

* feat(sessions): assignable session ownership with owner facet and menus

GitHub-assignee-style ownership: sessions get a mutable owner (defaulting to
the immutable createdActor) stored in additive bare-nullable SQLite columns
with first-use lazy ensure. New operator.write sessions.assignOwner validates
targets, requires an identified caller, authorizes by session visibility, and
records assignedBy/assignedAt inside the write transaction. The sessions agent
tool gains assign_owner; the Control UI adds Assign-to-me/Assign-to menus in
sidebar rows and chat headers, renders the effective owner chip, and the
creator facet/filter now keys on effective owner. Sharing authority stays
anchored on createdActor.

* feat(sessions): record session participants and stack them in the owner chip

Records every distinct external prompter (human profile/channel sender, or a
requesting agent) per session in an additive session_participants table at the
turn-admission boundary — best-effort, deferred, never blocking the turn; the
session's own agent and viewers are never recorded, capped at 32 per session.
The session row projects a bounded participants list (owner excluded) plus a
total count with the same actor enrichment as owner/createdActor. The sidebar
chip becomes a pair-stack when others have prompted (owner front, one peeking
participant or +N behind), the chat header shows the full facepile, and an
authenticated involvingMe list filter adds an Involving-me sidebar predicate.
Participant projection is excluded from logical-session CAS equality so display
history never invalidates session writes.

* fix(sessions): identify built-in agent tool callers for owner assignment

The sessions tool's assign_owner dispatched through the in-process synthetic
client, which carries neither a signed agent-runtime identity nor a human
profile, so agent-initiated reassignment always failed with FORBIDDEN. The
tool now captures its trusted requester agent identity and carries it across
in-process dispatch as internal client state (never wire params); the handler
derives assignedBy as signed runtime identity, then trusted agent-tool caller,
then authenticated human. Live-verified end-to-end on a dev gateway.

* fix(ci): split oversized session modules and refresh prompt snapshots

Split the max-lines offenders at concept boundaries for session equality, tool overrides, and protocol owner schemas. Remove the redundant Number conversion from the node:sqlite participant count. Refresh prompt snapshots after drift from the sessions and sessions_spawn tool description updates.

* fix(ci): restore solo-mode chip suppression and conform new method descriptors

Solo-mode root cause: owner-assignment submenu options reused the permanent owner-chip custom element, so hidden menu avatars were counted as attribution chrome. Menus now use viewer avatars while gateway-gated owner chips remain exclusive to collaborative sessions.

Conform sessions.assignOwner to the 2026.8 descriptor and append-only advertised-method inventories, and regenerate the Swift and Kotlin protocol surfaces.

Keep historical v15/v14 fixtures frozen by stripping the new owner columns; the existing range already excludes the participant table. Replace the new raw SQLite schema probes with synchronous Kysely queries.

Clear max-lines by splitting the organizer host contract, pure agent-navigation projections, and ownership/filtering sidebar cases at their concept boundaries.

* fix(ci): integrate ownership series with latest main surfaces

Wire the sessions-page assign-owner action, merge capability imports, narrow the navigation export scope, and apply sessions-create formatting.

The owner-presence regression came from hidden assign-owner menu avatars emitting data-viewer-id, so owner and menu chrome now opt out of presence markers while real facepiles retain them.

* fix(sessions): scope the involving-me filter to profile-backed participants

Session participant history mixed channel-native sender ids with authenticated Gateway profile ids, so involving-me missed real sessions and could accept numeric collisions.

Record the actor_source namespace at each producer, carry it through the internal SQLite projection, and match authenticated viewers only against profile-backed human participants. Legacy NULL sources fail closed for filtering, while channel ids remain available for display.

* build(ui): raise startup budget baseline for session ownership surfaces

Ownership chips, assignment menus, and the participant stack add ~0.7 KiB
gzip to the startup path; CI compression landed just over the previous
baseline+tolerance. Hard cap (350 KiB) unchanged.

* refactor(sessions): drop raw NULL projection for the lazy actor_source column

The Kysely guardrail rejects typed raw sql snippets outside allowlisted
boundaries; select the lazily-ensured column only when present and let the
row projection treat its absence as unknown/legacy.

* build(ui): refresh combined startup baseline
2026-08-17 02:35:20 -07:00

155 lines
5.3 KiB
TypeScript

// Builds the SQLite sessions/transcripts schema baseline used by CI drift checks.
import { createHash } from "node:crypto";
import fs from "node:fs/promises";
import path from "node:path";
import { expectDefined } from "../../packages/normalization-core/src/expect.js";
/** Rendered baseline artifact for the sessions/transcripts SQLite schema. */
type SqliteSessionSchemaBaselineRender = {
/** Normalized SQL for the session, conversation, and transcript schema objects. */
sql: string;
};
/** Result returned after writing or checking SQLite schema baseline artifacts. */
type SqliteSessionSchemaBaselineWriteResult = {
/** True when generated artifact content differs from disk. */
changed: boolean;
/** True when changed artifacts were actually written. */
wrote: boolean;
/** Local inspection SQL artifact path. */
sqlPath: string;
/** SHA-256 hash artifact path. */
hashPath: string;
};
const DEFAULT_SCHEMA_INPUT = "src/state/openclaw-agent-schema.sql";
const DEFAULT_SQL_OUTPUT = ".artifacts/sqlite-session-transcript-schema-baseline.sql";
const DEFAULT_HASH_OUTPUT = "docs/.generated/sqlite-session-transcript-schema-baseline.sha256";
const TARGET_TABLES = new Set([
"session_nodes",
"session_participants",
"session_windows",
"session_members",
"conversations",
"session_conversations",
"transcript_events",
"transcript_rewrite_watermarks",
"transcript_event_identities",
"session_transcript_index_state",
"session_transcript_active_events",
"session_transcript_archives",
]);
function sha256(value: string): string {
return createHash("sha256").update(value).digest("hex");
}
function normalizeIdentifier(value: string): string {
return value.replace(/^"|"$/g, "").toLowerCase();
}
function splitSqlStatements(sourceSql: string): string[] {
return sourceSql
.split(/;\s*(?:\r?\n|$)/u)
.map((statement) => statement.trim())
.filter(Boolean);
}
function normalizeStatement(statement: string): string {
const lines = statement
.split(/\r?\n/u)
.map((line) => line.trimEnd())
.filter((line, index, allLines) => line.trim() !== "" || index < allLines.length - 1);
return `${lines.join("\n")};`;
}
function readCreatedTableName(statement: string): string | null {
const match = statement.match(
/^CREATE\s+TABLE\s+IF\s+NOT\s+EXISTS\s+("[^"]+"|[A-Za-z_][A-Za-z0-9_]*)\b/iu,
);
return match ? normalizeIdentifier(expectDefined(match[1], "created table name")) : null;
}
function readIndexedTableName(statement: string): string | null {
const match = statement.match(
/^CREATE\s+(?:UNIQUE\s+)?INDEX\s+IF\s+NOT\s+EXISTS\s+("[^"]+"|[A-Za-z_][A-Za-z0-9_]*)\s+ON\s+("[^"]+"|[A-Za-z_][A-Za-z0-9_]*)\b/isu,
);
return match ? normalizeIdentifier(expectDefined(match[2], "indexed table name")) : null;
}
function isTargetSessionSchemaStatement(statement: string): boolean {
const tableName = readCreatedTableName(statement);
if (tableName) {
return TARGET_TABLES.has(tableName);
}
const indexedTableName = readIndexedTableName(statement);
return indexedTableName ? TARGET_TABLES.has(indexedTableName) : false;
}
/** Render the normalized sessions/transcripts SQLite schema baseline. */
export function renderSqliteSessionSchemaBaseline(
agentSchemaSql: string,
): SqliteSessionSchemaBaselineRender {
const statements = splitSqlStatements(agentSchemaSql)
.filter(isTargetSessionSchemaStatement)
.map(normalizeStatement);
return {
sql: `${statements.join("\n\n")}\n`,
};
}
/** Build the sha256 hash file content for the sessions/transcripts SQLite schema baseline. */
export function computeSqliteSessionSchemaBaselineHashFileContent(
rendered: SqliteSessionSchemaBaselineRender,
): string {
return `${sha256(rendered.sql)} sqlite-session-transcript-schema-baseline.sql\n`;
}
async function readIfExists(filePath: string): Promise<string | null> {
try {
return await fs.readFile(filePath, "utf8");
} catch (error) {
if (error && typeof error === "object" && "code" in error && error.code === "ENOENT") {
return null;
}
throw error;
}
}
/** Write or check SQLite sessions/transcripts schema baseline artifacts. */
export async function writeSqliteSessionSchemaBaselineArtifacts(params: {
repoRoot: string;
check: boolean;
schemaInputPath?: string;
sqlOutputPath?: string;
hashOutputPath?: string;
}): Promise<SqliteSessionSchemaBaselineWriteResult> {
const schemaPath = path.resolve(params.repoRoot, params.schemaInputPath ?? DEFAULT_SCHEMA_INPUT);
const sqlPath = path.resolve(params.repoRoot, params.sqlOutputPath ?? DEFAULT_SQL_OUTPUT);
const hashPath = path.resolve(params.repoRoot, params.hashOutputPath ?? DEFAULT_HASH_OUTPUT);
const sourceSql = await fs.readFile(schemaPath, "utf8");
const rendered = renderSqliteSessionSchemaBaseline(sourceSql);
const hash = computeSqliteSessionSchemaBaselineHashFileContent(rendered);
const existingHash = await readIfExists(hashPath);
const existingSql = await readIfExists(sqlPath);
const changed = params.check
? existingHash !== hash
: existingHash !== hash || existingSql !== rendered.sql;
if (!params.check && changed) {
await fs.mkdir(path.dirname(sqlPath), { recursive: true });
await fs.writeFile(sqlPath, rendered.sql);
await fs.writeFile(hashPath, hash);
}
return {
changed,
wrote: !params.check && changed,
sqlPath,
hashPath,
};
}