Files
openclaw/scripts/e2e/lib/plugins/assertions.mjs
Peter Steinberger f91de52f0d refactor: move runtime state to SQLite
* refactor: remove stale file-backed shims

* fix: harden sqlite state ci boundaries

* refactor: store matrix idb snapshots in sqlite

* fix: satisfy rebased CI guardrails

* refactor: store current conversation bindings in sqlite table

* refactor: store tui last sessions in sqlite table

* refactor: reset sqlite schema history

* refactor: drop unshipped sqlite table migration

* refactor: remove plugin index file rollback

* refactor: drop unshipped sqlite sidecar migrations

* refactor: remove runtime commitments kv migration

* refactor: preserve kysely sync result types

* refactor: drop unshipped sqlite schema migration table

* test: keep session usage coverage sqlite-backed

* refactor: keep sqlite migration doctor-only

* refactor: isolate device legacy imports

* refactor: isolate push voicewake legacy imports

* refactor: isolate remaining runtime legacy imports

* refactor: tighten sqlite migration guardrails

* test: cover sqlite persisted enum parsing

* refactor: isolate legacy update and tui imports

* refactor: tighten sqlite state ownership

* refactor: move legacy imports behind doctor

* refactor: remove legacy session row lookup

* refactor: canonicalize memory transcript locators

* refactor: drop transcript path scope fallbacks

* refactor: drop runtime legacy session delivery pruning

* refactor: store tts prefs only in sqlite

* refactor: remove cron store path runtime

* refactor: use cron sqlite store keys

* refactor: rename telegram message cache scope

* refactor: read memory dreaming status from sqlite

* refactor: rename cron status store key

* refactor: stop remembering transcript file paths

* test: use sqlite locators in agent fixtures

* refactor: remove file-shaped commitments and cron store surfaces

* refactor: keep compaction transcript handles out of session rows

* refactor: derive transcript handles from session identity

* refactor: derive runtime transcript handles

* refactor: remove gateway session locator reads

* refactor: remove transcript locator from session rows

* refactor: store raw stream diagnostics in sqlite

* refactor: remove file-shaped transcript rotation

* refactor: hide legacy trajectory paths from runtime

* refactor: remove runtime transcript file bridges

* refactor: repair database-first rebase fallout

* refactor: align tests with database-first state

* refactor: remove transcript file handoffs

* refactor: sync post-compaction memory by transcript scope

* refactor: run codex app-server sessions by id

* refactor: bind codex runtime state by session id

* refactor: pass memory transcripts by sqlite scope

* refactor: remove transcript locator cleanup leftovers

* test: remove stale transcript file fixtures

* refactor: remove transcript locator test helper

* test: make cron sqlite keys explicit

* test: remove cron runtime store paths

* test: remove stale session file fixtures

* test: use sqlite cron keys in diagnostics

* refactor: remove runtime delivery queue backfill

* test: drop fake export session file mocks

* refactor: rename acp session read failure flag

* refactor: rename acp row session key

* refactor: remove session store test seams

* refactor: move legacy session parser tests to doctor

* refactor: reindex managed memory in place

* refactor: drop stale session store wording

* refactor: rename session row helpers

* refactor: rename sqlite session entry modules

* refactor: remove transcript locator leftovers

* refactor: trim file-era audit wording

* refactor: clean managed media through sqlite

* fix: prefer explicit agent for exports

* fix: use prepared agent for session resets

* fix: canonicalize legacy codex binding import

* test: rename state cleanup helper

* docs: align backup docs with sqlite state

* refactor: drop legacy Pi usage auth fallback

* refactor: move legacy auth profile imports to doctor

* refactor: keep Pi model discovery auth in memory

* refactor: remove MSTeams legacy learning key fallback

* refactor: store model catalog config in sqlite

* refactor: use sqlite model catalog at runtime

* refactor: remove model json compatibility aliases

* refactor: store auth profiles in sqlite

* refactor: seed copied auth profiles in sqlite

* refactor: make auth profile runtime sqlite-addressed

* refactor: migrate hermes secrets into sqlite auth store

* refactor: move plugin install config migration to doctor

* refactor: rename plugin index audit checks

* test: drop auth file assumptions

* test: remove legacy transcript file assertions

* refactor: drop legacy cli session aliases

* refactor: store skill uploads in sqlite

* refactor: keep subagent attachments in sqlite vfs

* refactor: drop subagent attachment cleanup state

* refactor: move legacy session aliases to doctor

* refactor: require node 24 for sqlite state runtime

* refactor: move provider caches into sqlite state

* fix: harden virtual agent filesystem

* refactor: enforce database-first runtime state

* refactor: rename compaction transcript rotation setting

* test: clean sqlite refactor test types

* refactor: consolidate sqlite runtime state

* refactor: model session conversations in sqlite

* refactor: stop deriving cron delivery from session keys

* refactor: stop classifying sessions from key shape

* refactor: hydrate announce targets from typed delivery

* refactor: route heartbeat delivery from typed sqlite context

* refactor: tighten typed sqlite session routing

* refactor: remove session origin routing shadow

* refactor: drop session origin shadow fixtures

* perf: query sqlite vfs paths by prefix

* refactor: use typed conversation metadata for sessions

* refactor: prefer typed session routing metadata

* refactor: require typed session routing metadata

* refactor: resolve group tool policy from typed sessions

* refactor: delete dead session thread info bridge

* Show Codex subscription reset times in channel errors (#80456)

* feat(plugin-sdk): consolidate session workflow APIs

* fix(agents): allow read-only agent mount reads

* [codex] refresh plugin regression fixtures

* fix(agents): restore compaction gateway logs

* test: tighten gateway startup assertions

* Redact persisted secret-shaped payloads [AI] (#79006)

* test: tighten device pair notify assertions

* test: tighten hermes secret assertions

* test: assert matrix client error shapes

* test: assert config compat warnings

* fix(heartbeat): remap cron-run exec events to session keys (#80214)

* fix(codex): route btw through native side threads

* fix(auth): accept friendly OpenAI order for Codex profiles

* fix(codex): rotate auth profiles inside harness

* fix: keep browser status page probe within timeout

* test: assert agents add outputs

* test: pin cron read status

* fix(agents): avoid Pi resource discovery stalls

Co-authored-by: dataCenter430 <titan032000@gmail.com>

* fix: retire timed-out codex app-server clients

* test: tighten qa lab runtime assertions

* test: check security fix outputs

* test: verify extension runtime messages

* feat(wake): expose typed sessionKey on wake protocol + system event CLI

* fix(gateway): await session_end during shutdown drain and track channel + compaction lifecycle paths (#57790)

* test: guard talk consult call helper

* fix(codex): scale context engine projection (#80761)

* fix(codex): scale context engine projection

* fix: document Codex context projection scaling

* fix: document Codex context projection scaling

* fix: document Codex context projection scaling

* fix: document Codex context projection scaling

* chore: align Codex projection changelog

* chore: realign Codex projection changelog

* fix: isolate Codex projection patch

---------

Co-authored-by: Eva (agent) <eva+agent-78055@100yen.org>
Co-authored-by: Josh Lehman <josh@martian.engineering>

* refactor: move agent runtime state toward piless

* refactor: remove cron session reaper

* refactor: move session management to sqlite

* refactor: finish database-first state migration

* chore: refresh generated sqlite db types

* refactor: remove stale file-backed shims

* test: harden kysely type coverage

# Conflicts:
#	.agents/skills/kysely-database-access/SKILL.md
#	src/infra/kysely-sync.types.test.ts
#	src/proxy-capture/store.sqlite.test.ts
#	src/state/openclaw-agent-db.test.ts
#	src/state/openclaw-state-db.test.ts

* refactor: remove cron store path runtime

* refactor: keep compaction transcript handles out of session rows

* refactor: derive embedded transcripts from sqlite identity

* refactor: remove embedded transcript locator handoff

* refactor: remove runtime transcript file bridges

* refactor: remove transcript file handoffs

* refactor: remove MSTeams legacy learning key fallback

* refactor: store model catalog config in sqlite

* refactor: use sqlite model catalog at runtime

# Conflicts:
#	docs/cli/secrets.md
#	docs/gateway/authentication.md
#	docs/gateway/secrets.md

* fix: keep oauth sibling sync sqlite-local

# Conflicts:
#	src/commands/onboard-auth.test.ts

* refactor: remove task session store maintenance

# Conflicts:
#	src/commands/tasks.ts

* refactor: keep diagnostics in state sqlite

* refactor: enforce database-first runtime state

* refactor: consolidate sqlite runtime state

* Show Codex subscription reset times in channel errors (#80456)

* fix(codex): refresh subscription limit resets

* fix(codex): format reset times for channels

* Update CHANGELOG with latest changes and fixes

Updated CHANGELOG with recent fixes and improvements.

* fix(codex): keep command load failures on codex surface

* fix(codex): format account rate limits as rows

* fix(codex): summarize account limits as usage status

* fix(codex): simplify account limit status

* test: tighten subagent announce queue assertion

* test: tighten session delete lifecycle assertions

* test: tighten cron ops assertions

* fix: track cron execution milestones

* test: tighten hermes secret assertions

* test: assert matrix sync store payloads

* test: assert config compat warnings

* fix(codex): align btw side thread semantics

* fix(codex): honor codex fallback blocking

* fix(agents): avoid Pi resource discovery stalls

* test: tighten codex event assertions

* test: tighten cron assertions

* Fix Codex app-server OAuth harness auth

* refactor: move agent runtime state toward piless

* refactor: move device and push state to sqlite

* refactor: move runtime json state imports to doctor

* refactor: finish database-first state migration

* chore: refresh generated sqlite db types

* refactor: clarify cron sqlite store keys

* refactor: remove stale file-backed shims

* refactor: bind codex runtime state by session id

* test: expect sqlite trajectory branch export

* refactor: rename session row helpers

* fix: keep legacy device identity import in doctor

* refactor: enforce database-first runtime state

* refactor: consolidate sqlite runtime state

* build: align pi contract wrappers

* chore: repair database-first rebase

* refactor: remove session file test contracts

* test: update gateway session expectations

* refactor: stop routing from session compatibility shadows

* refactor: stop persisting session route shadows

* refactor: use typed delivery context in clients

* refactor: stop echoing session route shadows

* refactor: repair embedded runner rebase imports

# Conflicts:
#	src/agents/pi-embedded-runner/run/attempt.tool-call-argument-repair.ts

* refactor: align pi contract imports

* refactor: satisfy kysely sync helper guard

* refactor: remove file transcript bridge remnants

* refactor: remove session locator compatibility

* refactor: remove session file test contracts

* refactor: keep rebase database-first clean

* refactor: remove session file assumptions from e2e

* docs: clarify database-first goal state

* test: remove legacy store markers from sqlite runtime tests

* refactor: remove legacy store assumptions from runtime seams

* refactor: align sqlite runtime helper seams

* test: update memory recall sqlite audit mock

* refactor: align database-first runtime type seams

* test: clarify doctor cron legacy store names

* fix: preserve sqlite session route projections

* test: fix copilot token cache test syntax

* docs: update database-first proof status

* test: align database-first test fixtures

* docs: update database-first proof status

* refactor: clean extension database-first drift

* test: align agent session route proof

* test: clarify doctor legacy path fixtures

* chore: clean database-first changed checks

* chore: repair database-first rebase markers

* build: allow baileys git subdependency

* chore: repair exp-vfs rebase drift

* chore: finish exp-vfs rebase cleanup

* chore: satisfy rebase lint drift

* chore: fix qqbot rebase type seam

* chore: fix rebase drift leftovers

* fix: keep auth profile oauth secrets out of sqlite

* fix: repair rebase drift tests

* test: stabilize pairing request ordering

* test: use source manifests in plugin contract checks

* fix: restore gateway session metadata after rebase

* fix: repair database-first rebase drift

* fix: clean up database-first rebase fallout

* test: stabilize line quick reply receipt time

* fix: repair extension rebase drift

* test: keep transcript redaction tests sqlite-backed

* fix: carry injected transcript redaction through sqlite

* chore: clean database branch rebase residue

* fix: repair database branch CI drift

* fix: repair database branch CI guard drift

* fix: stabilize oauth tls preflight test

* test: align database branch fast guards

* test: repair build artifact boundary guards

* chore: clean changelog rebase markers

---------

Co-authored-by: pashpashpash <nik@vault77.ai>
Co-authored-by: Eva <eva@100yen.org>
Co-authored-by: stainlu <stainlu@newtype-ai.org>
Co-authored-by: Jason Zhou <jason.zhou.design@gmail.com>
Co-authored-by: Ruben Cuevas <hi@rubencu.com>
Co-authored-by: Pavan Kumar Gondhi <pavangondhi@gmail.com>
Co-authored-by: Shakker <shakkerdroid@gmail.com>
Co-authored-by: Kaspre <36520309+Kaspre@users.noreply.github.com>
Co-authored-by: dataCenter430 <titan032000@gmail.com>
Co-authored-by: Kaspre <kaspre@gmail.com>
Co-authored-by: pandadev66 <nova.full.stack@outlook.com>
Co-authored-by: Eva <admin@100yen.org>
Co-authored-by: Eva (agent) <eva+agent-78055@100yen.org>
Co-authored-by: Josh Lehman <josh@martian.engineering>
Co-authored-by: jeffjhunter <support@aipersonamethod.com>
2026-05-13 13:15:12 +01:00

853 lines
32 KiB
JavaScript

import fs from "node:fs";
import path from "node:path";
import {
readInstalledPluginIndex,
readInstalledPluginRecords,
writeInstalledPluginIndex,
} from "../installed-plugin-index.mjs";
const command = process.argv[2];
const readJson = (file) => JSON.parse(fs.readFileSync(file, "utf8"));
function getInstallRecords() {
const index = readInstalledPluginIndex();
if (!index.installRecords) {
throw new Error("expected modern installRecords in installed plugin index");
}
return index.installRecords;
}
function readOpenClawConfig() {
const configPath = path.join(process.env.HOME, ".openclaw", "openclaw.json");
return fs.existsSync(configPath) ? readJson(configPath) : {};
}
function assertPluginRemoved(params) {
const list = readJson(params.listFile);
if ((list.plugins || []).some((entry) => entry.id === params.pluginId)) {
throw new Error(`${params.pluginId} still listed after uninstall`);
}
const installRecords = getInstallRecords();
if (installRecords[params.pluginId]) {
throw new Error(`${params.pluginId} install record still present after uninstall`);
}
const config = readOpenClawConfig();
if (config.plugins?.entries?.[params.pluginId]) {
throw new Error(`${params.pluginId} config entry still present after uninstall`);
}
if ((config.plugins?.allow || []).includes(params.pluginId)) {
throw new Error(`${params.pluginId} allowlist entry still present after uninstall`);
}
if ((config.plugins?.deny || []).includes(params.pluginId)) {
throw new Error(`${params.pluginId} denylist entry still present after uninstall`);
}
}
function rememberPluginInstallPath(params) {
const record = getInstallRecords()[params.pluginId];
if (!record) {
throw new Error(`missing install record for ${params.pluginId}`);
}
if (params.source && record.source !== params.source) {
throw new Error(`unexpected source for ${params.pluginId}: ${record.source}`);
}
if (params.sourcePath && record.sourcePath !== params.sourcePath) {
throw new Error(
`unexpected source path for ${params.pluginId}: ${record.sourcePath}, expected ${params.sourcePath}`,
);
}
const installPath = record.installPath?.replace(/^~(?=$|\/)/u, process.env.HOME);
if (!installPath || !fs.existsSync(installPath)) {
throw new Error(`${params.pluginId} install path missing on disk: ${installPath}`);
}
fs.writeFileSync(params.installPathFile, installPath, "utf8");
if (params.sourcePathFile && params.sourcePath) {
fs.writeFileSync(params.sourcePathFile, params.sourcePath, "utf8");
}
return { installPath, record };
}
function assertManagedInstallRemoved(params) {
const installPath = fs.readFileSync(params.installPathFile, "utf8").trim();
const sourcePath =
params.sourcePathFile && fs.existsSync(params.sourcePathFile)
? fs.readFileSync(params.sourcePathFile, "utf8").trim()
: "";
assertPluginRemoved({
pluginId: params.pluginId,
listFile: params.listFile,
});
if (sourcePath && !fs.existsSync(sourcePath)) {
throw new Error(`${params.pluginId} source path was deleted during uninstall: ${sourcePath}`);
}
if (installPath !== sourcePath && fs.existsSync(installPath)) {
throw new Error(
`${params.pluginId} managed install path still exists after uninstall: ${installPath}`,
);
}
}
function recordFixturePluginTrust() {
const pluginId = process.argv[3];
const pluginRoot = process.argv[4];
const enabled = process.argv[5] === "1";
const configPath = path.join(process.env.HOME, ".openclaw", "openclaw.json");
const config = fs.existsSync(configPath) ? readJson(configPath) : {};
const plugins = (config.plugins ??= {});
const entries = (plugins.entries ??= {});
entries[pluginId] = { ...entries[pluginId], enabled };
delete plugins.installs;
plugins.allow = Array.from(new Set([...(plugins.allow ?? []), pluginId])).toSorted((a, b) =>
a.localeCompare(b),
);
fs.mkdirSync(path.dirname(configPath), { recursive: true });
fs.writeFileSync(configPath, `${JSON.stringify(config, null, 2)}\n`, "utf8");
const ledger = {
version: 1,
warning:
"DO NOT EDIT. This record is generated by OpenClaw plugin install/update/uninstall commands.",
hostContractVersion: "docker-e2e",
compatRegistryVersion: "docker-e2e",
migrationVersion: 1,
policyHash: "docker-e2e",
generatedAtMs: Date.now(),
installRecords: {},
plugins: [],
diagnostics: [],
...readInstalledPluginIndex(),
};
ledger.updatedAtMs = Date.now();
ledger.installRecords ??= ledger.records ?? {};
delete ledger.records;
ledger.installRecords[pluginId] = {
...ledger.installRecords[pluginId],
source: "path",
installPath: pluginRoot,
sourcePath: pluginRoot,
};
writeInstalledPluginIndex(ledger);
}
function assertDemoPlugin() {
const data = readJson("/tmp/plugins.json");
const inspect = readJson("/tmp/plugins-inspect.json");
const plugin = (data.plugins || []).find((entry) => entry.id === "demo-plugin");
if (!plugin) {
throw new Error("plugin not found");
}
if (plugin.status !== "loaded") {
throw new Error(`unexpected status: ${plugin.status}`);
}
const assertIncludes = (list, value, label) => {
if (!Array.isArray(list) || !list.includes(value)) {
throw new Error(`${label} missing: ${value}`);
}
};
const inspectToolNames = Array.isArray(inspect.tools)
? inspect.tools.flatMap((entry) => (Array.isArray(entry?.names) ? entry.names : []))
: [];
assertIncludes(inspectToolNames, "demo_tool", "tool");
assertIncludes(inspect.gatewayMethods, "demo.ping", "gateway method");
assertIncludes(inspect.cliCommands, "demo", "cli command");
assertIncludes(inspect.services, "demo-service", "service");
const diagErrors = (data.diagnostics || []).filter((diag) => diag.level === "error");
if (diagErrors.length > 0) {
throw new Error(`diagnostics errors: ${diagErrors.map((diag) => diag.message).join("; ")}`);
}
}
function assertSimplePlugin(jsonFile, inspectFile, pluginId, method) {
const data = readJson(jsonFile);
const inspect = readJson(inspectFile);
const plugin = (data.plugins || []).find((entry) => entry.id === pluginId);
if (!plugin) {
throw new Error(`${pluginId} plugin not found`);
}
if (plugin.status !== "loaded") {
throw new Error(`unexpected status: ${plugin.status}`);
}
if (!Array.isArray(inspect.gatewayMethods) || !inspect.gatewayMethods.includes(method)) {
throw new Error(`expected gateway method ${method}`);
}
}
function assertUpdateOutput(logFile, expectedSnippet) {
const output = fs.readFileSync(logFile, "utf8");
if (!output.includes(expectedSnippet)) {
throw new Error(
`expected update output to include ${JSON.stringify(expectedSnippet)}:\n${output}`,
);
}
}
function assertClaudeBundleDisabled() {
const data = readJson("/tmp/plugins-bundle-disabled.json");
const plugin = (data.plugins || []).find((entry) => entry.id === "claude-bundle-e2e");
if (!plugin) {
throw new Error("Claude bundle plugin not found");
}
if (plugin.status !== "disabled") {
throw new Error(`expected disabled bundle before enable, got ${plugin.status}`);
}
}
function assertClaudeBundleInspect() {
const inspect = readJson("/tmp/plugins-bundle-inspect.json");
if (inspect.plugin?.bundleFormat !== "claude") {
throw new Error(`expected Claude bundle format, got ${inspect.plugin?.bundleFormat}`);
}
if (inspect.plugin?.enabled !== true || inspect.plugin?.status !== "loaded") {
throw new Error(
`expected enabled loaded Claude bundle, got enabled=${inspect.plugin?.enabled} status=${inspect.plugin?.status}`,
);
}
}
function assertSlashInstall() {
const inspect = readJson("/tmp/plugin-command-install-show.json");
if (inspect.plugin?.status !== "loaded") {
throw new Error(`expected loaded status after install, got ${inspect.plugin?.status}`);
}
if (inspect.plugin?.enabled !== true) {
throw new Error(`expected enabled status after install, got ${inspect.plugin?.enabled}`);
}
if (!inspect.gatewayMethods.includes("demo.slash.install")) {
throw new Error(`expected installed gateway method, got ${inspect.gatewayMethods.join(", ")}`);
}
}
function parseClawHubPackageName(rawSpec) {
const value = rawSpec.slice("clawhub:".length).trim();
const slashIndex = value.lastIndexOf("/");
const atIndex = value.lastIndexOf("@");
return atIndex > 0 && atIndex > slashIndex ? value.slice(0, atIndex) : value;
}
function assertMarketplaceList() {
const data = readJson("/tmp/marketplace-list.json");
const names = (data.plugins || []).map((entry) => entry.name).toSorted();
if (data.name !== "Fixture Marketplace") {
throw new Error(`unexpected marketplace name: ${data.name}`);
}
if (!names.includes("marketplace-shortcut") || !names.includes("marketplace-direct")) {
throw new Error(`unexpected marketplace plugins: ${names.join(", ")}`);
}
}
function assertMarketplaceInstalled() {
const data = readJson("/tmp/plugins-marketplace.json");
const shortcutInspect = readJson("/tmp/plugins-marketplace-shortcut-inspect.json");
const directInspect = readJson("/tmp/plugins-marketplace-direct-inspect.json");
const getPlugin = (id) => {
const plugin = (data.plugins || []).find((entry) => entry.id === id);
if (!plugin) {
throw new Error(`plugin not found: ${id}`);
}
if (plugin.status !== "loaded") {
throw new Error(`unexpected status for ${id}: ${plugin.status}`);
}
return plugin;
};
const shortcut = getPlugin("marketplace-shortcut");
const direct = getPlugin("marketplace-direct");
if (shortcut.version !== "0.0.1") {
throw new Error(`unexpected shortcut version: ${shortcut.version}`);
}
if (direct.version !== "0.0.1") {
throw new Error(`unexpected direct version: ${direct.version}`);
}
if (!shortcutInspect.gatewayMethods.includes("demo.marketplace.shortcut.v1")) {
throw new Error("expected marketplace shortcut gateway method");
}
if (!directInspect.gatewayMethods.includes("demo.marketplace.direct.v1")) {
throw new Error("expected marketplace direct gateway method");
}
}
function assertMarketplaceRecords() {
const installRecords = getInstallRecords();
for (const id of ["marketplace-shortcut", "marketplace-direct"]) {
const record = installRecords[id];
if (!record) {
if (allowLegacyCompat) {
console.log(`legacy package did not persist marketplace install record for ${id}`);
continue;
}
throw new Error(`missing marketplace install record for ${id}`);
}
if (record.source !== "marketplace") {
throw new Error(`unexpected source for ${id}: ${record.source}`);
}
if (record.marketplaceSource !== "claude-fixtures") {
throw new Error(`unexpected marketplace source for ${id}: ${record.marketplaceSource}`);
}
if (record.marketplacePlugin !== id) {
throw new Error(`unexpected marketplace plugin for ${id}: ${record.marketplacePlugin}`);
}
}
}
function assertPluginTgz() {
assertSimplePlugin(
"/tmp/plugins2.json",
"/tmp/plugins2-inspect.json",
"demo-plugin-tgz",
"demo.tgz",
);
rememberPluginInstallPath({
pluginId: "demo-plugin-tgz",
installPathFile: "/tmp/plugins2-install-path.txt",
source: "archive",
});
}
function assertPluginTgzRemoved() {
assertManagedInstallRemoved({
pluginId: "demo-plugin-tgz",
listFile: "/tmp/plugins2-uninstalled.json",
installPathFile: "/tmp/plugins2-install-path.txt",
});
}
function assertPluginDir() {
const sourceDir = process.argv[3];
assertSimplePlugin(
"/tmp/plugins3.json",
"/tmp/plugins3-inspect.json",
"demo-plugin-dir",
"demo.dir",
);
rememberPluginInstallPath({
pluginId: "demo-plugin-dir",
installPathFile: "/tmp/plugins3-install-path.txt",
sourcePathFile: "/tmp/plugins3-source-path.txt",
source: "path",
sourcePath: sourceDir,
});
}
function assertPluginDirRemoved() {
assertManagedInstallRemoved({
pluginId: "demo-plugin-dir",
listFile: "/tmp/plugins3-uninstalled.json",
installPathFile: "/tmp/plugins3-install-path.txt",
sourcePathFile: "/tmp/plugins3-source-path.txt",
});
}
function assertGitPlugin() {
const repoUrl = process.argv[3];
const gitRef = process.argv[4];
assertSimplePlugin(
"/tmp/plugins-git.json",
"/tmp/plugins-git-inspect.json",
"demo-plugin-git",
"demo.git",
);
const inspect = readJson("/tmp/plugins-git-inspect.json");
if (!Array.isArray(inspect.cliCommands) || !inspect.cliCommands.includes("demo-git")) {
throw new Error(`expected demo-git cli command, got ${inspect.cliCommands?.join(", ")}`);
}
const cliOutput = fs.readFileSync("/tmp/plugins-git-cli.txt", "utf8");
if (!cliOutput.includes("demo-plugin-git:pong")) {
throw new Error(`unexpected git plugin cli output: ${cliOutput.trim()}`);
}
const record = getInstallRecords()["demo-plugin-git"];
if (!record) {
throw new Error("missing git install record for demo-plugin-git");
}
if (record.source !== "git") {
throw new Error(`unexpected git install source: ${record.source}`);
}
if (record.gitUrl !== repoUrl) {
throw new Error(`unexpected git url: ${record.gitUrl}, expected ${repoUrl}`);
}
if (record.gitRef !== gitRef) {
throw new Error(`unexpected git ref: ${record.gitRef}, expected ${gitRef}`);
}
if (record.gitCommit !== gitRef) {
throw new Error(`unexpected git commit: ${record.gitCommit}, expected ${gitRef}`);
}
if (record.spec !== `git:${repoUrl}@${gitRef}`) {
throw new Error(`unexpected git spec: ${record.spec}`);
}
const installPath = record.installPath?.replace(/^~(?=$|\/)/u, process.env.HOME);
if (!installPath || !fs.existsSync(installPath)) {
throw new Error(`git install path missing on disk: ${installPath}`);
}
const gitRoot = path.join(process.env.HOME, ".openclaw", "git");
if (!installPath.endsWith(`${path.sep}repo`)) {
throw new Error(`git install path should point at cloned repo root: ${installPath}`);
}
assertRealPathInside(gitRoot, installPath, "git install path");
const dependencyPackagePath = path.join(installPath, "node_modules", "is-number", "package.json");
if (!fs.existsSync(dependencyPackagePath)) {
throw new Error(`missing git plugin installed dependency: ${dependencyPackagePath}`);
}
assertRealPathInside(installPath, dependencyPackagePath, "git plugin installed dependency");
fs.writeFileSync("/tmp/plugins-git-install-path.txt", installPath, "utf8");
fs.writeFileSync("/tmp/plugins-git-install-parent.txt", path.dirname(installPath), "utf8");
}
function assertGitPluginRemoved() {
const installPath = fs.readFileSync("/tmp/plugins-git-install-path.txt", "utf8").trim();
const installParent = fs.readFileSync("/tmp/plugins-git-install-parent.txt", "utf8").trim();
assertPluginRemoved({
pluginId: "demo-plugin-git",
listFile: "/tmp/plugins-git-uninstalled.json",
});
if (fs.existsSync(installPath)) {
throw new Error(`git managed repo still exists after uninstall: ${installPath}`);
}
if (fs.existsSync(installParent)) {
throw new Error(
`empty git managed install parent still exists after uninstall: ${installParent}`,
);
}
}
function assertRealPathInside(parentPath, childPath, label) {
const parentRealPath = fs.realpathSync(parentPath);
const childRealPath = fs.realpathSync(childPath);
if (
childRealPath !== parentRealPath &&
!childRealPath.startsWith(`${parentRealPath}${path.sep}`)
) {
throw new Error(`${label} resolved outside ${parentPath}: ${childRealPath}`);
}
}
function assertClawHubExternalInstallContract(installPath) {
const openclawPeerPath = path.join(installPath, "node_modules", "openclaw");
if (!fs.existsSync(openclawPeerPath)) {
throw new Error(`missing ClawHub openclaw peer symlink: ${openclawPeerPath}`);
}
if (!fs.lstatSync(openclawPeerPath).isSymbolicLink()) {
throw new Error(`ClawHub openclaw peer is not a symlink: ${openclawPeerPath}`);
}
const hostRoot = fs.realpathSync(process.cwd());
const linkedHostRoot = fs.realpathSync(openclawPeerPath);
if (linkedHostRoot !== hostRoot) {
throw new Error(`expected ClawHub openclaw peer ${linkedHostRoot} to target ${hostRoot}`);
}
const dependencyPackagePath = path.join(installPath, "node_modules", "is-number", "package.json");
if (fs.existsSync(dependencyPackagePath)) {
assertRealPathInside(installPath, dependencyPackagePath, "ClawHub isolated dependency");
}
}
function assertClawHubArtifactMetadata(record, pluginId) {
if (record.artifactKind === "legacy-zip") {
if (record.artifactFormat !== "zip") {
throw new Error(
`missing ClawHub legacy ZIP artifact metadata for ${pluginId}: ${JSON.stringify(record)}`,
);
}
return;
}
if (record.artifactKind !== "npm-pack" || record.artifactFormat !== "tgz") {
throw new Error(`missing ClawHub artifact metadata for ${pluginId}: ${JSON.stringify(record)}`);
}
if (!record.clawpackSha256 || typeof record.clawpackSize !== "number") {
throw new Error(`missing ClawHub ClawPack metadata for ${pluginId}: ${JSON.stringify(record)}`);
}
if (!record.npmIntegrity || !record.npmShasum || !record.npmTarballName) {
throw new Error(
`missing ClawHub npm artifact metadata for ${pluginId}: ${JSON.stringify(record)}`,
);
}
}
function assertPluginDirDeps() {
const sourceDir = process.argv[3];
assertSimplePlugin(
"/tmp/plugins-dir-deps.json",
"/tmp/plugins-dir-deps-inspect.json",
"demo-plugin-dir-deps",
"demo.dir.deps",
);
const record = getInstallRecords()["demo-plugin-dir-deps"];
if (!record) {
throw new Error("missing local dependency plugin install record");
}
if (record.source !== "path") {
throw new Error(`unexpected local dependency plugin source: ${record.source}`);
}
if (record.sourcePath !== sourceDir) {
throw new Error(`unexpected local dependency plugin source path: ${record.sourcePath}`);
}
const installPath = record.installPath?.replace(/^~(?=$|\/)/u, process.env.HOME);
if (!installPath || !fs.existsSync(installPath)) {
throw new Error(`local dependency plugin install path missing on disk: ${installPath}`);
}
const dependencyPackagePath = path.join(installPath, "node_modules", "is-number", "package.json");
if (!fs.existsSync(dependencyPackagePath)) {
throw new Error(`missing copied local plugin dependency: ${dependencyPackagePath}`);
}
assertRealPathInside(installPath, dependencyPackagePath, "local plugin copied dependency");
rememberPluginInstallPath({
pluginId: "demo-plugin-dir-deps",
installPathFile: "/tmp/plugins-dir-deps-install-path.txt",
sourcePathFile: "/tmp/plugins-dir-deps-source-path.txt",
source: "path",
sourcePath: sourceDir,
});
}
function assertPluginDirDepsRemoved() {
assertManagedInstallRemoved({
pluginId: "demo-plugin-dir-deps",
listFile: "/tmp/plugins-dir-deps-uninstalled.json",
installPathFile: "/tmp/plugins-dir-deps-install-path.txt",
sourcePathFile: "/tmp/plugins-dir-deps-source-path.txt",
});
}
function assertLocalPathUpdateSkipped() {
assertUpdateOutput("/tmp/plugins-dir-update.log", 'Skipping "demo-plugin-dir" (source: path).');
}
function assertNpmPlugin() {
assertSimplePlugin(
"/tmp/plugins-npm.json",
"/tmp/plugins-npm-inspect.json",
"demo-plugin-npm",
"demo.npm",
);
const inspect = readJson("/tmp/plugins-npm-inspect.json");
if (!Array.isArray(inspect.cliCommands) || !inspect.cliCommands.includes("demo-npm")) {
throw new Error(`expected demo-npm cli command, got ${inspect.cliCommands?.join(", ")}`);
}
const cliOutput = fs.readFileSync("/tmp/plugins-npm-cli.txt", "utf8");
if (!cliOutput.includes("demo-plugin-npm:pong")) {
throw new Error(`unexpected npm plugin cli output: ${cliOutput.trim()}`);
}
const record = getInstallRecords()["demo-plugin-npm"];
if (!record) {
throw new Error("missing npm install record for demo-plugin-npm");
}
if (record.source !== "npm") {
throw new Error(`unexpected npm install source: ${record.source}`);
}
if (record.spec !== "@openclaw/demo-plugin-npm@0.0.1") {
throw new Error(`unexpected npm spec: ${record.spec}`);
}
if (record.resolvedName !== "@openclaw/demo-plugin-npm") {
throw new Error(`unexpected npm resolved name: ${record.resolvedName}`);
}
if (record.resolvedVersion !== "0.0.1") {
throw new Error(`unexpected npm resolved version: ${record.resolvedVersion}`);
}
const installPath = record.installPath?.replace(/^~(?=$|\/)/u, process.env.HOME);
if (!installPath || !fs.existsSync(installPath)) {
throw new Error(`npm install path missing on disk: ${installPath}`);
}
const nodeModulesRoot = path.dirname(path.dirname(installPath));
const npmRoot = path.dirname(nodeModulesRoot);
const dependencyPackagePath = path.join(nodeModulesRoot, "is-number", "package.json");
if (!fs.existsSync(dependencyPackagePath)) {
throw new Error(`missing npm plugin installed dependency: ${dependencyPackagePath}`);
}
assertRealPathInside(npmRoot, dependencyPackagePath, "npm plugin installed dependency");
fs.writeFileSync("/tmp/plugins-npm-install-path.txt", installPath, "utf8");
fs.writeFileSync("/tmp/plugins-npm-dependency-path.txt", dependencyPackagePath, "utf8");
}
function assertNpmPluginUpdateUnchanged() {
assertUpdateOutput("/tmp/plugins-npm-update.log", "demo-plugin-npm is up to date (0.0.1).");
assertNpmPlugin();
}
function assertPluginFile() {
const sourceDir = process.argv[3];
assertSimplePlugin(
"/tmp/plugins4.json",
"/tmp/plugins4-inspect.json",
"demo-plugin-file",
"demo.file",
);
rememberPluginInstallPath({
pluginId: "demo-plugin-file",
installPathFile: "/tmp/plugins4-install-path.txt",
sourcePathFile: "/tmp/plugins4-source-path.txt",
source: "path",
sourcePath: sourceDir,
});
}
function assertPluginFileRemoved() {
assertManagedInstallRemoved({
pluginId: "demo-plugin-file",
listFile: "/tmp/plugins4-uninstalled.json",
installPathFile: "/tmp/plugins4-install-path.txt",
sourcePathFile: "/tmp/plugins4-source-path.txt",
});
}
function assertNpmPluginRemoved() {
const installPath = fs.readFileSync("/tmp/plugins-npm-install-path.txt", "utf8").trim();
const dependencyPackagePath = fs
.readFileSync("/tmp/plugins-npm-dependency-path.txt", "utf8")
.trim();
assertPluginRemoved({
pluginId: "demo-plugin-npm",
listFile: "/tmp/plugins-npm-uninstalled.json",
});
if (fs.existsSync(installPath)) {
throw new Error(`npm managed package still exists after uninstall: ${installPath}`);
}
if (fs.existsSync(dependencyPackagePath)) {
throw new Error(
`npm managed dependency still exists after uninstall: ${dependencyPackagePath}`,
);
}
}
function assertMarketplaceUpdated() {
const data = readJson("/tmp/plugins-marketplace-updated.json");
const inspect = readJson("/tmp/plugins-marketplace-updated-inspect.json");
const plugin = (data.plugins || []).find((entry) => entry.id === "marketplace-shortcut");
if (!plugin) {
throw new Error("updated marketplace plugin not found");
}
if (plugin.version !== "0.0.2") {
throw new Error(`unexpected updated version: ${plugin.version}`);
}
if (!inspect.gatewayMethods.includes("demo.marketplace.shortcut.v2")) {
throw new Error(`expected updated gateway method, got ${inspect.gatewayMethods.join(", ")}`);
}
}
function assertGitPluginUpdated() {
const beforeCommit = process.argv[3];
assertSimplePlugin(
"/tmp/plugins-git-update.json",
"/tmp/plugins-git-update-inspect.json",
"demo-plugin-git-update",
"demo.git.update.v2",
);
const inspect = readJson("/tmp/plugins-git-update-inspect.json");
if (!Array.isArray(inspect.cliCommands) || !inspect.cliCommands.includes("demo-git-update")) {
throw new Error(`expected demo-git-update cli command, got ${inspect.cliCommands?.join(", ")}`);
}
const cliOutput = fs.readFileSync("/tmp/plugins-git-update-cli.txt", "utf8");
if (!cliOutput.includes("demo-plugin-git-update:pong-v2")) {
throw new Error(`unexpected updated git plugin cli output: ${cliOutput.trim()}`);
}
const record = getInstallRecords()["demo-plugin-git-update"];
if (!record) {
throw new Error("missing git update install record for demo-plugin-git-update");
}
if (record.source !== "git") {
throw new Error(`unexpected git update source: ${record.source}`);
}
if (record.gitRef !== "main") {
throw new Error(`unexpected git update ref: ${record.gitRef}`);
}
if (!record.gitCommit || record.gitCommit === beforeCommit) {
throw new Error(
`expected git update commit to advance from ${beforeCommit}, got ${record.gitCommit}`,
);
}
if (record.version !== "0.0.2") {
throw new Error(`unexpected git update version: ${record.version}`);
}
assertUpdateOutput(
"/tmp/plugins-git-update.log",
"Updated demo-plugin-git-update: 0.0.1 -> 0.0.2.",
);
}
async function assertClawHubPreflight() {
const spec = process.env.CLAWHUB_PLUGIN_SPEC;
if (!spec?.startsWith("clawhub:")) {
throw new Error(`expected clawhub: spec, got ${spec}`);
}
const packageName = parseClawHubPackageName(spec);
const baseUrl = (
process.env.OPENCLAW_CLAWHUB_URL ||
process.env.CLAWHUB_URL ||
"https://clawhub.ai"
).replace(/\/+$/, "");
const token =
process.env.OPENCLAW_CLAWHUB_TOKEN ||
process.env.CLAWHUB_TOKEN ||
process.env.CLAWHUB_AUTH_TOKEN ||
"";
const response = await fetch(`${baseUrl}/api/v1/packages/${encodeURIComponent(packageName)}`, {
headers: token ? { Authorization: `Bearer ${token}` } : undefined,
});
if (!response.ok) {
const body = await response.text().catch(() => "");
throw new Error(
`ClawHub package preflight failed for ${packageName}: ${response.status} ${body}`,
);
}
const detail = await response.json();
const family = detail.package?.family;
if (family !== "code-plugin" && family !== "bundle-plugin") {
throw new Error(`ClawHub package ${packageName} is not installable as a plugin: ${family}`);
}
if (detail.package?.runtimeId && detail.package.runtimeId !== process.env.CLAWHUB_PLUGIN_ID) {
throw new Error(
`ClawHub package ${packageName} runtimeId ${detail.package.runtimeId} does not match expected ${process.env.CLAWHUB_PLUGIN_ID}`,
);
}
console.log(`Using ClawHub package ${packageName} (${family}).`);
}
function assertClawHubInstalled() {
const pluginId = process.env.CLAWHUB_PLUGIN_ID;
const spec = process.env.CLAWHUB_PLUGIN_SPEC;
const packageName = parseClawHubPackageName(spec);
const list = readJson("/tmp/plugins-clawhub-installed.json");
const inspect = readJson("/tmp/plugins-clawhub-inspect.json");
const plugin = (list.plugins || []).find((entry) => entry.id === pluginId);
if (!plugin) {
throw new Error(`ClawHub plugin not found after install: ${pluginId}`);
}
if (plugin.status !== "loaded") {
throw new Error(`unexpected ClawHub plugin status for ${pluginId}: ${plugin.status}`);
}
if (inspect.plugin?.id !== pluginId) {
throw new Error(`unexpected ClawHub inspect plugin id: ${inspect.plugin?.id}`);
}
const index = readInstalledPluginIndex();
if (!index.installRecords) {
throw new Error("expected modern installRecords in installed plugin index");
}
const installRecords = index.installRecords;
const record = installRecords[pluginId];
if (!record) {
throw new Error(`missing ClawHub install record for ${pluginId}`);
}
if (record.source !== "clawhub") {
throw new Error(`unexpected ClawHub install source for ${pluginId}: ${record.source}`);
}
if (record.clawhubPackage !== packageName) {
throw new Error(
`unexpected ClawHub package for ${pluginId}: ${record.clawhubPackage}, expected ${packageName}`,
);
}
if (record.clawhubFamily !== "code-plugin" && record.clawhubFamily !== "bundle-plugin") {
throw new Error(`unexpected ClawHub family for ${pluginId}: ${record.clawhubFamily}`);
}
if (typeof record.installPath !== "string" || record.installPath.length === 0) {
throw new Error(`missing ClawHub install path for ${pluginId}`);
}
assertClawHubArtifactMetadata(record, pluginId);
const installPath = record.installPath.replace(/^~(?=$|\/)/u, process.env.HOME);
const extensionsRoot = path.join(process.env.HOME, ".openclaw", "extensions");
if (!installPath.startsWith(`${extensionsRoot}${path.sep}`)) {
throw new Error(`ClawHub install path is outside managed extensions root: ${installPath}`);
}
if (!fs.existsSync(installPath)) {
throw new Error(`ClawHub install path missing on disk: ${installPath}`);
}
if (record.artifactKind === "npm-pack") {
assertClawHubExternalInstallContract(installPath);
}
fs.writeFileSync("/tmp/plugins-clawhub-install-path.txt", installPath, "utf8");
}
function assertClawHubRemoved() {
const pluginId = process.env.CLAWHUB_PLUGIN_ID;
const installPath = fs.readFileSync("/tmp/plugins-clawhub-install-path.txt", "utf8").trim();
const list = readJson("/tmp/plugins-clawhub-uninstalled.json");
if ((list.plugins || []).some((entry) => entry.id === pluginId)) {
throw new Error(`ClawHub plugin still listed after uninstall: ${pluginId}`);
}
const installRecords = readInstalledPluginRecords();
if (installRecords[pluginId]) {
throw new Error(`ClawHub install record still present after uninstall: ${pluginId}`);
}
const configAfterUninstallPath = path.join(process.env.HOME, ".openclaw", "openclaw.json");
const configAfterUninstall = fs.existsSync(configAfterUninstallPath)
? readJson(configAfterUninstallPath)
: {};
if (configAfterUninstall.plugins?.entries?.[pluginId]) {
throw new Error(`ClawHub config entry still present after uninstall: ${pluginId}`);
}
if ((configAfterUninstall.plugins?.allow || []).includes(pluginId)) {
throw new Error(`ClawHub allowlist entry still present after uninstall: ${pluginId}`);
}
if ((configAfterUninstall.plugins?.deny || []).includes(pluginId)) {
throw new Error(`ClawHub denylist entry still present after uninstall: ${pluginId}`);
}
if (fs.existsSync(installPath)) {
throw new Error(
`ClawHub managed install directory still exists after uninstall: ${installPath}`,
);
}
}
function assertClawHubUpdated() {
const output = fs.readFileSync("/tmp/plugins-clawhub-update.log", "utf8");
if (!output.includes(`${process.env.CLAWHUB_PLUGIN_ID} already at `)) {
throw new Error(`expected ClawHub update to report already-at version:\n${output}`);
}
assertClawHubInstalled();
}
const commands = {
"record-fixture-plugin-trust": recordFixturePluginTrust,
"demo-plugin": assertDemoPlugin,
"plugin-tgz": assertPluginTgz,
"plugin-tgz-removed": assertPluginTgzRemoved,
"plugin-dir": assertPluginDir,
"plugin-dir-removed": assertPluginDirRemoved,
"plugin-dir-update-skipped": assertLocalPathUpdateSkipped,
"plugin-dir-deps": assertPluginDirDeps,
"plugin-dir-deps-removed": assertPluginDirDepsRemoved,
"plugin-file": assertPluginFile,
"plugin-file-removed": assertPluginFileRemoved,
"plugin-npm": assertNpmPlugin,
"plugin-npm-update": assertNpmPluginUpdateUnchanged,
"plugin-npm-removed": assertNpmPluginRemoved,
"bundle-disabled": assertClaudeBundleDisabled,
"bundle-inspect": assertClaudeBundleInspect,
"slash-install": assertSlashInstall,
"plugin-git": assertGitPlugin,
"plugin-git-removed": assertGitPluginRemoved,
"plugin-git-updated": assertGitPluginUpdated,
"marketplace-list": assertMarketplaceList,
"marketplace-installed": assertMarketplaceInstalled,
"marketplace-records": assertMarketplaceRecords,
"marketplace-updated": assertMarketplaceUpdated,
"clawhub-preflight": assertClawHubPreflight,
"clawhub-installed": assertClawHubInstalled,
"clawhub-updated": assertClawHubUpdated,
"clawhub-removed": assertClawHubRemoved,
};
const fn = commands[command];
if (!fn) {
throw new Error(`unknown plugins assertion command: ${command}`);
}
await fn();