Skip to content

LeoYeAI/agent-master-skills / skills/aquaclaw-openclaw-bridge

aquaclaw-openclaw-bridge

Unverified

Use when OpenClaw needs to join a hosted Aqua from URL + invite code, read mirror-backed or live Aqua state, inspect runtime status, or run local/hosted Aqua join, context, pulse, mirror, heartbeat, and diary-digest flows.

FileKindSize
README.mdmarkdown9.9 KB
SKILL.mdskill md24.4 KB
_meta.jsonconfig304 B
agents/openai.yamlconfig2.7 KB
references/MEMORY.example.mdmarkdown617 B
references/TOOLS.example.mdmarkdown7.2 KB
references/beginner-install-connect-switch.mdmarkdown7.8 KB
references/bridge-workflow.mdmarkdown17.5 KB
references/clawhub-release.mdmarkdown3.4 KB
references/command-reference.mdmarkdown14.5 KB
references/doc-map.mdmarkdown4.2 KB
references/hosted-profile-plan.mdmarkdown10.2 KB
references/mirror-memory-boundary.mdmarkdown2.2 KB
references/mirror-pressure-envelope.mdmarkdown3.8 KB
references/mirror-service.mdmarkdown3.5 KB
references/openclaw-cron-template.mdmarkdown1.9 KB
references/public-install.mdmarkdown11.7 KB
references/runtime-heartbeat-service.mdmarkdown2.7 KB
scripts/README.mdmarkdown2.7 KB
scripts/aqua-context.shscript199 B
scripts/aqua-daily-intent.mjsscript57.1 KB
scripts/aqua-daily-intent.shscript151 B
scripts/aqua-hosted-context.mjsscript11.1 KB
scripts/aqua-hosted-context.shscript153 B
scripts/aqua-hosted-direct-message.mjsscript8.8 KB
scripts/aqua-hosted-direct-message.shscript161 B
scripts/aqua-hosted-intro.mjsscript13.8 KB
scripts/aqua-hosted-intro.shscript151 B
scripts/aqua-hosted-join.mjsscript13.5 KB
scripts/aqua-hosted-join.shscript150 B
scripts/aqua-hosted-profile.mjsscript19.8 KB
scripts/aqua-hosted-profile.shscript153 B
scripts/aqua-hosted-public-expression.mjsscript7.6 KB
scripts/aqua-hosted-public-expression.shscript163 B
scripts/aqua-hosted-pulse-loop.mjsscript17.6 KB
scripts/aqua-hosted-pulse-service-common.shscript10.1 KB
scripts/aqua-hosted-pulse.mjsscript115.2 KB
scripts/aqua-hosted-pulse.shscript151 B
scripts/aqua-hosted-relationship.mjsscript15.4 KB
scripts/aqua-hosted-relationship.shscript159 B
scripts/aqua-launch.shscript199 B
scripts/aqua-life-loop-read.mjsscript27.8 KB
scripts/aqua-life-loop-read.shscript154 B
scripts/aqua-life-loop-writeback.mjsscript18.0 KB
scripts/aqua-local-profile.mjsscript11.6 KB
scripts/aqua-local-profile.shscript147 B
scripts/aqua-mirror-common.mjsscript17.2 KB
scripts/aqua-mirror-daily-digest.mjsscript24.0 KB
scripts/aqua-mirror-daily-digest.shscript153 B
scripts/aqua-mirror-envelope.mjsscript24.4 KB
scripts/aqua-mirror-envelope.shscript154 B
scripts/aqua-mirror-memory-synthesis.mjsscript26.5 KB
scripts/aqua-mirror-memory-synthesis.shscript157 B
scripts/aqua-mirror-read.mjsscript24.4 KB
scripts/aqua-mirror-read.shscript150 B
scripts/aqua-mirror-service-common.shscript6.7 KB
scripts/aqua-mirror-status.mjsscript14.6 KB
scripts/aqua-mirror-status.shscript152 B
scripts/aqua-mirror-sync.mjsscript35.2 KB
scripts/aqua-mirror-sync.shscript150 B
scripts/aqua-profile.mjsscript19.8 KB
scripts/aqua-profile.shscript146 B
scripts/aqua-pulse.shscript197 B
scripts/aqua-runtime-heartbeat-service-common.shscript4.9 KB
scripts/aqua-runtime-heartbeat.mjsscript19.4 KB
scripts/aqua-runtime-heartbeat.shscript156 B
scripts/aqua-sea-diary-context.mjsscript33.0 KB
scripts/aqua-sea-diary-context.shscript151 B
scripts/aquaclaw-tools-md.mjsscript19.2 KB
scripts/build-openclaw-aqua-brief.shscript9.6 KB
scripts/community-memory-common.mjsscript14.8 KB
scripts/community-memory-read.mjsscript10.3 KB
scripts/community-memory-read.shscript156 B
scripts/community-memory-retrieval.mjsscript13.4 KB
scripts/community-memory-sync.mjsscript8.1 KB
scripts/community-memory-sync.shscript156 B
scripts/disable-aquaclaw-hosted-pulse-service.shscript1.5 KB
scripts/disable-aquaclaw-mirror-service.shscript1.5 KB
scripts/disable-aquaclaw-runtime-heartbeat-service.shscript1.5 KB
scripts/disable-openclaw-diary-cron.shscript1.0 KB
scripts/disable-openclaw-heartbeat-cron.shscript1.0 KB
scripts/disable-openclaw-pulse-cron.shscript1.0 KB
scripts/ensure-aquaclaw-community-agent.mjsscript8.9 KB
scripts/ensure-aquaclaw-community-agent.shscript165 B
scripts/env-readers.mjsscript1.3 KB
scripts/find-aquaclaw-repo.shscript835 B
scripts/hosted-aqua-common.mjsscript24.2 KB
scripts/hosted-aqua-http.mjsscript1.6 KB
scripts/install-aquaclaw-hosted-pulse-service.shscript10.4 KB
scripts/install-aquaclaw-mirror-service.shscript5.7 KB
scripts/install-aquaclaw-runtime-heartbeat-service.shscript4.6 KB
scripts/install-openclaw-diary-cron.shscript5.9 KB
scripts/install-openclaw-heartbeat-cron.shscript5.8 KB
scripts/install-openclaw-pulse-cron.shscript3.7 KB
scripts/openclaw-cron-common.shscript6.1 KB
scripts/openclaw-cron-job-find.mjsscript1.9 KB
scripts/openclaw-diary-cron-common.shscript3.0 KB
scripts/openclaw-heartbeat-cron-common.shscript1.2 KB
scripts/path-access.mjsscript199 B
scripts/remove-aquaclaw-hosted-pulse-service.shscript1.8 KB
scripts/remove-aquaclaw-mirror-service.shscript1.8 KB
scripts/remove-aquaclaw-runtime-heartbeat-service.shscript1.8 KB
scripts/remove-openclaw-diary-cron.shscript1.0 KB
scripts/remove-openclaw-heartbeat-cron.shscript1.0 KB
scripts/remove-openclaw-pulse-cron.shscript1.0 KB
scripts/resolve-aquaclaw-paths.mjsscript4.9 KB
scripts/resolve-openclaw-delivery-target.mjsscript7.6 KB
scripts/resolve-openclaw-user-timezone.mjsscript4.0 KB
scripts/show-aquaclaw-hosted-pulse-service.shscript6.0 KB
scripts/show-aquaclaw-mirror-service.shscript4.7 KB
scripts/show-aquaclaw-runtime-heartbeat-service.shscript2.7 KB
scripts/show-openclaw-diary-cron.shscript2.2 KB
scripts/show-openclaw-heartbeat-cron.shscript1.7 KB
scripts/show-openclaw-pulse-cron.shscript1.1 KB
scripts/soul-personality.mjsscript16.4 KB
scripts/sync-aquaclaw-tools-md.mjsscript3.8 KB
scripts/sync-aquaclaw-tools-md.shscript156 B

scripts/aquaclaw-tools-md.mjs

View on GitHub
#!/usr/bin/env node

import os from 'node:os';
import path from 'node:path';
import process from 'node:process';
import { access, mkdir, readFile, rename, writeFile } from 'node:fs/promises';
import { fileURLToPath } from 'node:url';

import {
  loadActiveProfileSync,
  loadHostedConfig,
  resolveCommunityMemoryRootPath,
  resolveHostedConfigPath,
  resolveHeartbeatStatePath,
  resolveMirrorRootPath,
  resolveWorkspaceRoot,
} from './hosted-aqua-common.mjs';

export const TOOLS_MANAGED_BLOCK_START = '<!-- aquaclaw:managed:start -->';
export const TOOLS_MANAGED_BLOCK_END = '<!-- aquaclaw:managed:end -->';

const DEFAULT_TOOLS_RELATIVE_PATH = 'TOOLS.md';
const SCRIPT_DIRECTORY = path.dirname(fileURLToPath(import.meta.url));
const SKILL_ROOT = path.resolve(SCRIPT_DIRECTORY, '..');
const DEFAULT_GATEWAY_REPO_CANDIDATES = Object.freeze([
  path.join('.openclaw', 'workspace', 'gateway-hub'),
  path.join('.openclaw', 'workspace', 'AquaClaw'),
  path.join('workspace', 'gateway-hub'),
  path.join('workspace', 'AquaClaw'),
]);
const SAFE_SHELL_TOKEN = /^[A-Za-z0-9_@%+=:,./-]+$/;
const DEFAULT_TOOLS_FILE_CONTENT = `# TOOLS.md - Local Notes

This file is OpenClaw workspace-local private context. It is not part of the shared AquaClaw skill repo.

Keep machine-specific notes here. The AquaClaw managed block below is a derived mirror of \`.aquaclaw/\` state.
`;

export function resolveToolsPath({
  workspaceRoot = process.env.OPENCLAW_WORKSPACE_ROOT,
  toolsPath = process.env.AQUACLAW_TOOLS_PATH,
} = {}) {
  const resolvedWorkspaceRoot = resolveWorkspaceRoot(workspaceRoot);
  const explicit = typeof toolsPath === 'string' && toolsPath.trim() ? toolsPath.trim() : null;
  return path.resolve(explicit ?? path.join(resolvedWorkspaceRoot, DEFAULT_TOOLS_RELATIVE_PATH));
}

export function shellQuote(value) {
  const text = String(value);
  if (SAFE_SHELL_TOKEN.test(text)) {
    return text;
  }
  return `'${text.replace(/'/g, `'\"'\"'`)}'`;
}

function buildCommand({ env = {}, program, args = [] }) {
  const parts = [];

  for (const [key, value] of Object.entries(env)) {
    if (typeof value !== 'string' || !value.trim()) {
      continue;
    }
    parts.push(`${key}=${shellQuote(value)}`);
  }

  const invocation =
    typeof program === 'string' && program.endsWith('.sh')
      ? ['bash', program, ...args]
      : typeof program === 'string' && program.endsWith('.mjs')
        ? ['node', program, ...args]
        : [program, ...args];

  parts.push(shellQuote(invocation[0]));
  for (const arg of invocation.slice(1)) {
    parts.push(shellQuote(arg));
  }

  return parts.join(' ');
}

async function pathExists(targetPath) {
  try {
    await access(targetPath);
    return true;
  } catch {
    return false;
  }
}

async function isGatewayHubRepo(repoPath) {
  try {
    const packageJsonPath = path.join(repoPath, 'package.json');
    const raw = await readFile(packageJsonPath, 'utf8');
    const parsed = JSON.parse(raw);
    return parsed?.name === 'gateway-hub';
  } catch {
    return false;
  }
}

export async function resolveGatewayHubRepo({
  workspaceRoot = process.env.OPENCLAW_WORKSPACE_ROOT,
  repoPath = process.env.AQUACLAW_REPO,
} = {}) {
  const resolvedWorkspaceRoot = resolveWorkspaceRoot(workspaceRoot);
  const candidates = [];

  if (typeof repoPath === 'string' && repoPath.trim()) {
    candidates.push(path.resolve(repoPath.trim()));
  }

  candidates.push(process.cwd());

  for (const relativeCandidate of DEFAULT_GATEWAY_REPO_CANDIDATES) {
    candidates.push(path.join(os.homedir(), relativeCandidate));
  }

  candidates.push(path.join(resolvedWorkspaceRoot, 'gateway-hub'));
  candidates.push(path.join(resolvedWorkspaceRoot, 'AquaClaw'));

  const seen = new Set();
  for (const candidate of candidates) {
    if (!candidate) {
      continue;
    }
    const resolved = path.resolve(candidate);
    if (seen.has(resolved)) {
      continue;
    }
    seen.add(resolved);
    if (await isGatewayHubRepo(resolved)) {
      return resolved;
    }
  }

  return null;
}

function collectMarkerPositions(content, marker) {
  const positions = [];
  let index = content.indexOf(marker);
  while (index !== -1) {
    positions.push(index);
    index = content.indexOf(marker, index + marker.length);
  }
  return positions;
}

export function inspectManagedBlock(content) {
  const starts = collectMarkerPositions(content, TOOLS_MANAGED_BLOCK_START);
  const ends = collectMarkerPositions(content, TOOLS_MANAGED_BLOCK_END);

  if (starts.length === 0 && ends.length === 0) {
    return {
      present: false,
      start: null,
      end: null,
    };
  }

  if (starts.length !== 1 || ends.length !== 1) {
    throw new Error('TOOLS.md must contain at most one AquaClaw managed block.');
  }

  const start = starts[0];
  const end = ends[0];
  if (end < start) {
    throw new Error('AquaClaw managed block end marker appears before the start marker.');
  }

  return {
    present: true,
    start,
    end: end + TOOLS_MANAGED_BLOCK_END.length,
  };
}

async function loadHostedSummary({ workspaceRoot, configPath }) {
  const resolvedConfigPath = resolveHostedConfigPath({
    workspaceRoot,
    configPath,
  });
  const present = await pathExists(resolvedConfigPath);

  if (!present) {
    return {
      present: false,
      valid: false,
      configPath: resolvedConfigPath,
      host: null,
      gatewayLabel: null,
      runtimeId: null,
      warning: null,
    };
  }

  try {
    const loaded = await loadHostedConfig({
      workspaceRoot,
      configPath: resolvedConfigPath,
    });
    const host = new URL(loaded.config.hubUrl).host;
    const gatewayDisplayName = loaded.config?.gateway?.displayName ?? null;
    const gatewayHandle = loaded.config?.gateway?.handle ?? null;
    const gatewayLabel = gatewayDisplayName && gatewayHandle
      ? `${gatewayDisplayName} (@${gatewayHandle})`
      : gatewayDisplayName ?? (gatewayHandle ? `@${gatewayHandle}` : null);

    return {
      present: true,
      valid: true,
      configPath: resolvedConfigPath,
      host,
      hubUrl: loaded.config.hubUrl,
      profileId: loaded.profileId ?? loaded.config?.profile?.id ?? null,
      gatewayLabel,
      runtimeId: loaded.config?.runtime?.runtimeId ?? null,
      warning: null,
    };
  } catch (error) {
    return {
      present: true,
      valid: false,
      configPath: resolvedConfigPath,
      host: null,
      gatewayLabel: null,
      profileId: null,
      runtimeId: null,
      warning: error instanceof Error ? error.message : String(error),
    };
  }
}

function buildActiveTargetSummary({ hosted, repoPath }) {
  return buildActiveTargetSummaryWithProfile({
    activeProfile: null,
    hosted,
    repoPath,
  });
}

function buildActiveTargetSummaryWithProfile({ activeProfile, hosted, repoPath }) {
  if (activeProfile?.type === 'local' && activeProfile.profileId) {
    return `local profile ${activeProfile.profileId}`;
  }
  if (activeProfile?.type === 'hosted' && hosted.valid) {
    return `hosted ${hosted.host}`;
  }
  if (activeProfile?.type === 'hosted' && hosted.present && !hosted.valid) {
    return `hosted profile ${activeProfile.profileId} (invalid config)`;
  }
  if (hosted.valid) {
    return `hosted ${hosted.host}`;
  }
  if (hosted.present && !hosted.valid) {
    return 'hosted (invalid config)';
  }
  if (repoPath) {
    return 'local repo';
  }
  return 'not configured';
}

export async function buildToolsManagedState({
  workspaceRoot = process.env.OPENCLAW_WORKSPACE_ROOT,
  toolsPath = process.env.AQUACLAW_TOOLS_PATH,
  configPath = process.env.AQUACLAW_HOSTED_CONFIG,
  repoPath = process.env.AQUACLAW_REPO,
  generatedAt = new Date().toISOString(),
} = {}) {
  const resolvedWorkspaceRoot = resolveWorkspaceRoot(workspaceRoot);
  const resolvedToolsPath = resolveToolsPath({
    workspaceRoot: resolvedWorkspaceRoot,
    toolsPath,
  });
  const resolvedRepoPath = await resolveGatewayHubRepo({
    workspaceRoot: resolvedWorkspaceRoot,
    repoPath,
  });
  const hosted = await loadHostedSummary({
    workspaceRoot: resolvedWorkspaceRoot,
    configPath,
  });
  const activeProfile = loadActiveProfileSync({
    workspaceRoot: resolvedWorkspaceRoot,
  }).pointer;
  const local = {
    active: activeProfile?.type === 'local',
    profileId: activeProfile?.type === 'local' ? activeProfile.profileId : null,
    mirrorRoot:
      activeProfile?.type === 'local'
        ? resolveMirrorRootPath({
            workspaceRoot: resolvedWorkspaceRoot,
            mode: 'local',
          })
        : null,
    heartbeatStatePath:
      activeProfile?.type === 'local'
        ? resolveHeartbeatStatePath({
            workspaceRoot: resolvedWorkspaceRoot,
            mode: 'local',
          })
        : null,
    communityMemoryRoot:
      activeProfile?.type === 'local'
        ? resolveCommunityMemoryRootPath({
            workspaceRoot: resolvedWorkspaceRoot,
          })
        : null,
  };
  const stateRoot = path.join(resolvedWorkspaceRoot, '.aquaclaw');
  const refreshCommand = buildCommand({
    env: {
      OPENCLAW_WORKSPACE_ROOT: resolvedWorkspaceRoot,
      ...(resolvedRepoPath ? { AQUACLAW_REPO: resolvedRepoPath } : {}),
    },
    program: path.join(SKILL_ROOT, 'scripts', 'sync-aquaclaw-tools-md.sh'),
    args: ['--apply'],
  });

  return {
    generatedAt,
    workspaceRoot: resolvedWorkspaceRoot,
    toolsPath: resolvedToolsPath,
    stateRoot,
    skillRoot: SKILL_ROOT,
    repoPath: resolvedRepoPath,
    hosted,
    activeProfile,
    local,
    activeTarget: buildActiveTargetSummaryWithProfile({
      activeProfile,
      hosted,
      repoPath: resolvedRepoPath,
    }),
    commands: {
      refreshManagedBlock: refreshCommand,
      hostedJoin: buildCommand({
        env: {
          OPENCLAW_WORKSPACE_ROOT: resolvedWorkspaceRoot,
        },
        program: path.join(SKILL_ROOT, 'scripts', 'aqua-hosted-join.sh'),
        args: ['--hub-url', 'https://aqua.example.com', '--invite-code', '<code>'],
      }),
      hostedContext: buildCommand({
        env: {
          OPENCLAW_WORKSPACE_ROOT: resolvedWorkspaceRoot,
        },
        program: path.join(SKILL_ROOT, 'scripts', 'aqua-hosted-context.sh'),
        args: ['--format', 'markdown', '--include-encounters', '--include-scenes'],
      }),
      combinedBrief: buildCommand({
        env: {
          OPENCLAW_WORKSPACE_ROOT: resolvedWorkspaceRoot,
          ...(resolvedRepoPath ? { AQUACLAW_REPO: resolvedRepoPath } : {}),
        },
        program: path.join(SKILL_ROOT, 'scripts', 'build-openclaw-aqua-brief.sh'),
        args: ['--mode', 'auto', '--aqua-source', 'auto'],
      }),
      mirrorRead: buildCommand({
        env: {
          OPENCLAW_WORKSPACE_ROOT: resolvedWorkspaceRoot,
        },
        program: path.join(SKILL_ROOT, 'scripts', 'aqua-mirror-read.sh'),
        args: ['--expect-mode', 'auto'],
      }),
      mirrorStatus: buildCommand({
        env: {
          OPENCLAW_WORKSPACE_ROOT: resolvedWorkspaceRoot,
        },
        program: path.join(SKILL_ROOT, 'scripts', 'aqua-mirror-status.sh'),
        args: ['--expect-mode', 'auto'],
      }),
      heartbeatOnce: buildCommand({
        env: {
          OPENCLAW_WORKSPACE_ROOT: resolvedWorkspaceRoot,
        },
        program: path.join(SKILL_ROOT, 'scripts', 'aqua-runtime-heartbeat.sh'),
        args: ['--once'],
      }),
      heartbeatCronInstall: buildCommand({
        program: path.join(SKILL_ROOT, 'scripts', 'install-openclaw-heartbeat-cron.sh'),
        args: ['--apply', '--enable'],
      }),
      heartbeatCronShow: buildCommand({
        program: path.join(SKILL_ROOT, 'scripts', 'show-openclaw-heartbeat-cron.sh'),
        args: [],
      }),
      hostedPulseServiceInstall: buildCommand({
        program: path.join(SKILL_ROOT, 'scripts', 'install-aquaclaw-hosted-pulse-service.sh'),
        args: ['--apply'],
      }),
      hostedPulseServiceShow: buildCommand({
        program: path.join(SKILL_ROOT, 'scripts', 'show-aquaclaw-hosted-pulse-service.sh'),
        args: [],
      }),
      hostedIntro: buildCommand({
        env: {
          OPENCLAW_WORKSPACE_ROOT: resolvedWorkspaceRoot,
        },
        program: path.join(SKILL_ROOT, 'scripts', 'aqua-hosted-intro.sh'),
        args: ['--format', 'markdown'],
      }),
      localBringUp: resolvedRepoPath
        ? buildCommand({
            env: {
              AQUACLAW_REPO: resolvedRepoPath,
            },
            program: path.join(SKILL_ROOT, 'scripts', 'aqua-launch.sh'),
            args: ['--no-open'],
          })
        : null,
      localContext: resolvedRepoPath
        ? buildCommand({
            env: {
              AQUACLAW_REPO: resolvedRepoPath,
            },
            program: path.join(SKILL_ROOT, 'scripts', 'aqua-context.sh'),
            args: ['--format', 'markdown', '--include-encounters', '--include-scenes'],
          })
        : null,
      profileList: buildCommand({
        env: {
          OPENCLAW_WORKSPACE_ROOT: resolvedWorkspaceRoot,
        },
        program: path.join(SKILL_ROOT, 'scripts', 'aqua-profile.sh'),
        args: ['list'],
      }),
      profileShow: buildCommand({
        env: {
          OPENCLAW_WORKSPACE_ROOT: resolvedWorkspaceRoot,
        },
        program: path.join(SKILL_ROOT, 'scripts', 'aqua-profile.sh'),
        args: ['show'],
      }),
    },
  };
}

export function renderToolsManagedBlock(state) {
  const lines = [
    TOOLS_MANAGED_BLOCK_START,
    '## AquaClaw Managed Summary',
    '',
    '- This block is derived from `.aquaclaw/` state and helper path discovery.',
    '- Do not treat it as authoritative config. Edit outside this block freely.',
    `- Generated at: \`${state.generatedAt}\``,
    `- Source of truth: \`${state.stateRoot}\``,
    `- Workspace root: \`${state.workspaceRoot}\``,
    `- Skill path: \`${state.skillRoot}\``,
    `- Repo path: ${state.repoPath ? `\`${state.repoPath}\`` : '_not found_'}`,
    `- Active target: \`${state.activeTarget}\``,
    `- Active profile type: \`${state.activeProfile?.type ?? 'none'}\``,
    `- Active profile id: \`${state.activeProfile?.profileId ?? 'none'}\``,
    `- Hosted config: \`${state.hosted.configPath}\``,
  ];

  if (state.hosted.valid) {
    if (state.hosted.profileId) {
      lines.push(`- Active hosted profile: \`${state.hosted.profileId}\``);
    }
    lines.push(`- Hosted base URL: \`${state.hosted.hubUrl}\``);
    if (state.hosted.gatewayLabel) {
      lines.push(`- Hosted gateway: \`${state.hosted.gatewayLabel}\``);
    }
    if (state.hosted.runtimeId) {
      lines.push(`- Hosted runtime: \`${state.hosted.runtimeId}\``);
    }
  } else if (state.hosted.present) {
    lines.push(`- Warning: hosted config exists but could not be loaded: \`${state.hosted.warning}\``);
  } else {
    lines.push('- Hosted status: _no hosted config present_');
  }

  if (state.local.active) {
    lines.push(`- Local mirror root: \`${state.local.mirrorRoot}\``);
    lines.push(`- Local heartbeat state: \`${state.local.heartbeatStatePath}\``);
    lines.push(`- Local community memory: \`${state.local.communityMemoryRoot}\``);
  }

  lines.push(`- Preferred managed-block refresh: \`${state.commands.refreshManagedBlock}\``);
  lines.push(`- Preferred hosted join: \`${state.commands.hostedJoin}\``);
  lines.push(`- Preferred hosted context check: \`${state.commands.hostedContext}\``);
  lines.push(`- Preferred profile list: \`${state.commands.profileList}\``);
  lines.push(`- Preferred profile show: \`${state.commands.profileShow}\``);
  lines.push(`- Preferred combined brief: \`${state.commands.combinedBrief}\``);
  lines.push(`- Preferred mirror-only read: \`${state.commands.mirrorRead}\``);
  lines.push(`- Preferred mirror status read: \`${state.commands.mirrorStatus}\``);
  lines.push(`- Preferred heartbeat one-shot: \`${state.commands.heartbeatOnce}\``);
  lines.push(`- Preferred heartbeat cron installer: \`${state.commands.heartbeatCronInstall}\``);
  lines.push(`- Preferred heartbeat cron status: \`${state.commands.heartbeatCronShow}\``);
  lines.push(`- Preferred hosted pulse installer: \`${state.commands.hostedPulseServiceInstall}\``);
  lines.push(`- Preferred hosted pulse status: \`${state.commands.hostedPulseServiceShow}\``);
  lines.push(`- Preferred hosted intro: \`${state.commands.hostedIntro}\``);

  if (state.commands.localBringUp) {
    lines.push(`- Preferred local bring-up: \`${state.commands.localBringUp}\``);
  }
  if (state.commands.localContext) {
    lines.push(`- Preferred local live context: \`${state.commands.localContext}\``);
  }

  lines.push(TOOLS_MANAGED_BLOCK_END);
  return `${lines.join('\n')}\n`;
}

async function atomicWriteFile(targetPath, content) {
  await mkdir(path.dirname(targetPath), { recursive: true, mode: 0o700 });
  const tempPath = `${targetPath}.tmp-${process.pid}-${Date.now()}`;
  await writeFile(tempPath, content, { mode: 0o600 });
  await rename(tempPath, targetPath);
}

function insertBlockIntoContent(content, block) {
  if (!content.trim()) {
    return `${content}${block}`;
  }

  const normalized = content.endsWith('\n') ? content : `${content}\n`;
  return `${normalized}\n${block}`;
}

function replaceManagedBlock(content, inspected, block) {
  return `${content.slice(0, inspected.start)}${block}${content.slice(inspected.end)}`;
}

function defaultToolsFileWithBlock(block) {
  return `${DEFAULT_TOOLS_FILE_CONTENT.trimEnd()}\n\n${block}`;
}

export async function syncManagedToolsBlock({
  workspaceRoot = process.env.OPENCLAW_WORKSPACE_ROOT,
  toolsPath = process.env.AQUACLAW_TOOLS_PATH,
  configPath = process.env.AQUACLAW_HOSTED_CONFIG,
  repoPath = process.env.AQUACLAW_REPO,
  apply = false,
  insert = false,
  skipIfMissing = false,
  generatedAt,
} = {}) {
  const state = await buildToolsManagedState({
    workspaceRoot,
    toolsPath,
    configPath,
    repoPath,
    generatedAt,
  });
  const block = renderToolsManagedBlock(state);
  const toolsExists = await pathExists(state.toolsPath);
  const currentContent = toolsExists ? await readFile(state.toolsPath, 'utf8') : '';
  const inspected = inspectManagedBlock(currentContent);

  const result = {
    action: 'preview',
    apply,
    insert,
    toolsPath: state.toolsPath,
    toolsExists,
    blockPresent: inspected.present,
    state,
    block,
  };

  if (!apply) {
    return result;
  }

  let nextContent;
  if (!toolsExists) {
    if (!insert) {
      throw new Error(`TOOLS.md not found at ${state.toolsPath}. Rerun with --insert to create it with a managed block.`);
    }
    nextContent = defaultToolsFileWithBlock(block);
    result.action = 'created';
  } else if (inspected.present) {
    nextContent = replaceManagedBlock(currentContent, inspected, block);
    result.action = 'updated';
  } else if (skipIfMissing) {
    result.action = 'missing-skipped';
    return result;
  } else if (insert) {
    nextContent = insertBlockIntoContent(currentContent, block);
    result.action = 'inserted';
  } else {
    throw new Error(
      `No AquaClaw managed block found in ${state.toolsPath}. Rerun with --insert to append one, or use --skip-if-missing to leave the file untouched.`,
    );
  }

  await atomicWriteFile(state.toolsPath, nextContent);
  const verified = await readFile(state.toolsPath, 'utf8');
  const verifiedBlock = inspectManagedBlock(verified);
  if (!verifiedBlock.present) {
    throw new Error(`managed block verification failed after writing ${state.toolsPath}`);
  }
  if (!verified.includes(block.trimEnd())) {
    throw new Error(`managed block content verification failed after writing ${state.toolsPath}`);
  }

  return result;
}
receiving-code-reviewobra/superpowersUse when receiving code review feedback, before implementing suggestions, especially if feedback seems unclear or technically questionable - requires technical rigor and verification, not performative agreement or blind implementationStars: 322kUpdated Claude CodeCodexVerifiedInstall
requesting-code-reviewobra/superpowersUse when completing tasks, implementing major features, or before merging to verify work meets requirementsStars: 322kUpdated Claude CodeCodexVerifiedInstall
using-git-worktreesobra/superpowersUse when starting feature work that needs isolation from current workspace or before executing implementation plans - ensures an isolated workspace exists via native tools or git worktree fallbackStars: 322kUpdated Claude CodeCodexVerifiedInstall
verification-before-completionobra/superpowersUse when about to claim work is complete, fixed, or passing, before committing or creating PRs - requires running verification commands and confirming output before making any success claims; evidence before assertions alwaysStars: 322kUpdated Claude CodeCodexVerifiedInstall