Files
openclaw/scripts/lib/workspace-bootstrap-smoke.mjs
Peter Steinberger 3e2b3ea4d5 feat(cron): database-backed heartbeat monitor scratch replaces HEARTBEAT.md (#112967)
* feat(cron): move heartbeat context into database-backed per-job cron scratch

- new additive cron_job_scratch SQLite table (revision tombstones keep
  compare-and-swap monotonic across unset/recreate; 256KiB cap)
- heartbeat runner reads monitor scratch instead of workspace HEARTBEAT.md;
  heartbeat_respond gains a private scratch replacement parameter
- openclaw doctor --fix migrates HEARTBEAT.md into scratch (hash-verified,
  archived under state backups, idempotent, symlink-contained)
- gateway cron.scratch.get/set admin RPCs + openclaw cron scratch CLI
- workspace bootstrap no longer seeds HEARTBEAT.md; Codex heartbeat file
  guidance removed; docs and prompt snapshots updated

* fix(cron): review round 2 — shared-workspace heartbeat migration and non-default agent monitors

- doctor migration groups agents by heartbeat source file and imports into
  every monitor before archiving/removing the shared file once
- exempt heartbeat payloads from the main-session default-agent restriction:
  monitors only poke the wake bus, so non-default agents converge again
- document why disabled monitors retain their last cadence (config default
  already resolves before the fallback)

* fix(cron): honor configured cron store, legacy heartbeat fallback, and safer doctor claim

* fix(cron): claim HEARTBEAT.md before committing scratch and restore without clobbering

* fix(cron): pin migration CAS to precondition revision, re-verify claim on release, archive first, report scratch as pending

* docs(heartbeat): remove retired config options

* fix(cron): crash-recoverable migration claims, partial-import rollback, latest-response scratch pairing

* test(heartbeat): keep latest scratch proposal paired

* fix(cron): roll back committed scratch on changed-claim release and restore no-row state

* fix(cron): revision-guarded rollback delete and recreated-file detection on claim release

* fix(cron): treat every failed claim re-verification as a migration conflict

* test(heartbeat): rename ack test after ackMaxChars retirement

* fix(heartbeat): keep monitor scratch out of bypass-scope runs

* fix(cron): resolve claimed symlinks on release and gate legacy fallback on proven scratch state

* fix(cron): strict claim-name recovery and per-entry migration grouping

* fix(ci): heartbeat scratch gate repairs — lint causes, dead exports, since-train, inventory path, prompt snapshot, regenerated docs map, SDK baseline, protocol bindings

* fix(cron): live-owner claim guard and canonical entry-key migration grouping

* fix(cron): archive claimed inode on release and flag orphan claims beside recreated files

* docs(cron): document process-global state-db invariant for scratch service ops

* chore(i18n): refresh native inventory line numbers after protocol binding regen
2026-07-23 11:10:49 -07:00

163 lines
4.9 KiB
JavaScript

// Verifies installed packages can bootstrap the default OpenClaw workspace files.
import { execFileSync } from "node:child_process";
import { existsSync, mkdtempSync, mkdirSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
/**
* Template pack files that must be present in installed packages.
*/
export const WORKSPACE_TEMPLATE_PACK_PATHS = [
"docs/reference/templates/AGENTS.md",
"docs/reference/templates/SOUL.md",
"docs/reference/templates/TOOLS.md",
"docs/reference/templates/IDENTITY.md",
"docs/reference/templates/USER.md",
"src/agents/templates/HEARTBEAT.md",
"docs/reference/templates/BOOTSTRAP.md",
];
// HEARTBEAT.md ships in the template pack for docs/doctor context but is no
// longer seeded into new workspaces; heartbeat context lives in cron scratch.
const REQUIRED_BOOTSTRAP_WORKSPACE_FILES = [
"AGENTS.md",
"SOUL.md",
"TOOLS.md",
"IDENTITY.md",
"USER.md",
"BOOTSTRAP.md",
];
const WORKSPACE_BOOTSTRAP_SMOKE_TIMEOUT_MS = 15_000;
const SAFE_UNIX_SMOKE_PATH = "/usr/bin:/bin";
/**
* Creates a minimal isolated environment for workspace bootstrap smoke runs.
*/
export function createWorkspaceBootstrapSmokeEnv(env, homeDir, overrides = {}) {
const allowlistedEnvEntries = [
"TMPDIR",
"TMP",
"TEMP",
"SystemRoot",
"ComSpec",
"PATHEXT",
"WINDIR",
];
const windowsRoot = env.SystemRoot ?? env.WINDIR ?? "C:\\Windows";
const nodeBinDir = dirname(process.execPath);
const safePath =
process.platform === "win32"
? `${nodeBinDir};${windowsRoot}\\System32;${windowsRoot}`
: `${nodeBinDir}:${SAFE_UNIX_SMOKE_PATH}`;
return {
...Object.fromEntries(
allowlistedEnvEntries.flatMap((key) => {
const value = env[key];
return typeof value === "string" && value.length > 0 ? [[key, value]] : [];
}),
),
PATH: safePath,
HOME: homeDir,
USERPROFILE: homeDir,
OPENCLAW_HOME: homeDir,
OPENCLAW_NO_ONBOARD: "1",
OPENCLAW_SUPPRESS_NOTES: "1",
OPENCLAW_DISABLE_BUNDLED_PLUGINS: "1",
OPENCLAW_DISABLE_BUNDLED_ENTRY_SOURCE_FALLBACK: "1",
AWS_EC2_METADATA_DISABLED: "true",
AWS_SHARED_CREDENTIALS_FILE: join(homeDir, ".aws", "credentials"),
AWS_CONFIG_FILE: join(homeDir, ".aws", "config"),
...overrides,
};
}
function collectMissingBootstrapWorkspaceFiles(workspaceDir) {
return REQUIRED_BOOTSTRAP_WORKSPACE_FILES.filter(
(filename) => !existsSync(join(workspaceDir, filename)),
);
}
function describeExecFailure(error) {
if (!(error instanceof Error)) {
return String(error);
}
const stdout =
typeof error.stdout === "string"
? error.stdout.trim()
: error.stdout instanceof Uint8Array
? Buffer.from(error.stdout).toString("utf8").trim()
: "";
const stderr =
typeof error.stderr === "string"
? error.stderr.trim()
: error.stderr instanceof Uint8Array
? Buffer.from(error.stderr).toString("utf8").trim()
: "";
return [error.message, stdout, stderr].filter(Boolean).join(" | ");
}
/**
* Runs the installed CLI workspace bootstrap smoke and validates created files.
*/
export function runInstalledWorkspaceBootstrapSmoke(params) {
const tempRoot = mkdtempSync(join(tmpdir(), "openclaw-workspace-bootstrap-smoke-"));
const homeDir = join(tempRoot, "home");
const cwd = join(tempRoot, "cwd");
mkdirSync(homeDir, { recursive: true });
mkdirSync(cwd, { recursive: true });
let combinedOutput = "";
try {
try {
execFileSync(
process.execPath,
[
join(params.packageRoot, "openclaw.mjs"),
"agent",
"--message",
"workspace bootstrap smoke",
"--session-id",
"workspace-bootstrap-smoke",
"--local",
"--timeout",
"1",
"--json",
],
{
cwd,
encoding: "utf8",
maxBuffer: 1024 * 1024 * 16,
stdio: ["ignore", "pipe", "pipe"],
timeout: WORKSPACE_BOOTSTRAP_SMOKE_TIMEOUT_MS,
env: createWorkspaceBootstrapSmokeEnv(process.env, homeDir),
},
);
} catch (error) {
combinedOutput = describeExecFailure(error);
}
if (combinedOutput.includes("Missing workspace template:")) {
throw new Error(
`installed workspace bootstrap failed before agent execution: ${combinedOutput}`,
);
}
const workspaceDir = join(homeDir, ".openclaw", "workspace");
const missingFiles = collectMissingBootstrapWorkspaceFiles(workspaceDir);
if (missingFiles.length > 0) {
const outputDetails = combinedOutput.length > 0 ? `\nCommand output:\n${combinedOutput}` : "";
throw new Error(
`installed workspace bootstrap did not create required files in ${workspaceDir}: ${missingFiles.join(", ")}${outputDetails}`,
);
}
} finally {
try {
rmSync(tempRoot, { force: true, recursive: true });
} catch {
// best effort cleanup only
}
}
}