UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

4,520 lines • 178 kB
import { l as normalizeOptionalString, o as normalizeLowercaseStringOrEmpty, t as hasNonEmptyString } from "./string-coerce-CCIiB4H7.mjs";
import { t as asBoolean } from "./boolean-2vRuVafy.mjs";
import { l as isRecord, t as asNonArrayRecord, u as isStringArray } from "./record-coerce-CVPuDqcc.mjs";
import { b as uniqueStrings, f as normalizeStringEntries, p as normalizeStringEntriesLower } from "./string-normalization-DLmfYZXI.mjs";
import { a as coerceSecretRef } from "./types.secrets-BmNLLnHp.mjs";
import { r as normalizeProviderId } from "./provider-id-b5XGSf9C.mjs";
import { n as normalizeAgentId } from "./agent-id-CQjtp2ft.mjs";
import { n as normalizeAccountId } from "./account-id-BqKT3GuY.mjs";
import { u as resolveExecApprovalsDisplayPath } from "./exec-approvals-config-BBzEUJlE.mjs";
import { u as resolveExecModePolicy } from "./exec-approvals-core-puBAw1bE.mjs";
import { a as splitSandboxBindSpec } from "./host-paths-CAIcciVP.mjs";
import "./string-coerce-runtime-BwAZZDf5.mjs";
import { o as resolveAgentRoute } from "./resolve-route-DBnTWpM6.mjs";
import { i as hasConfiguredAccountValue } from "./account-helpers-2ZndtV_R.mjs";
import "./routing-DmgGYTrU.mjs";
import "./secret-input-CpgOwFAi.mjs";
import "./provider-model-shared-Dg70R9-2.mjs";
import { r as readExecApprovalsSnapshotForPlugin } from "./exec-approvals-runtime-CvHjZPmq.mjs";
import { g as toolPolicy } from "./agent-harness-runtime-BCklzcv7.mjs";
import "./account-helpers-DlavPc2B.mjs";
import { basename, isAbsolute, resolve } from "node:path";
import { createHash } from "node:crypto";
import JSON5 from "json5";
//#region extensions/policy/src/doctor/check-ids.ts
const CHECK_IDS = {
	policyMissingFile: "policy/policy-jsonc-missing",
	policyInvalidFile: "policy/policy-jsonc-invalid",
	policyUnmigratedToolsFile: "policy/tools-md-migration-required",
	policyHashMismatch: "policy/policy-hash-mismatch",
	policyAttestationMismatch: "policy/attestation-hash-mismatch",
	policyDeniedChannelProvider: "policy/channels-denied-provider",
	policyDeniedMcpServer: "policy/mcp-denied-server",
	policyUnapprovedMcpServer: "policy/mcp-unapproved-server",
	policyDeniedModelProvider: "policy/models-denied-provider",
	policyUnapprovedModelProvider: "policy/models-unapproved-provider",
	policyPrivateNetworkAccess: "policy/network-private-access-enabled",
	policyRoutingBindingsRequired: "policy/routing-bindings-required",
	policyRoutingBindingChannelUnconfigured: "policy/routing-binding-channel-unconfigured",
	policyRoutingAgentMismatch: "policy/routing-agent-mismatch",
	policyRoutingMatchKindMismatch: "policy/routing-match-kind-mismatch",
	policyIngressDmPolicyUnapproved: "policy/ingress-dm-policy-unapproved",
	policyIngressDmScopeUnapproved: "policy/ingress-dm-scope-unapproved",
	policyIngressOpenGroupsDenied: "policy/ingress-open-groups-denied",
	policyIngressGroupMentionRequired: "policy/ingress-group-mention-required",
	policyGatewayNonLoopbackBind: "policy/gateway-non-loopback-bind",
	policyGatewayAuthDisabled: "policy/gateway-auth-disabled",
	policyGatewayRateLimitMissing: "policy/gateway-rate-limit-missing",
	policyGatewayControlUiInsecure: "policy/gateway-control-ui-insecure",
	policyGatewayTailscaleFunnel: "policy/gateway-tailscale-funnel",
	policyGatewayRemoteEnabled: "policy/gateway-remote-enabled",
	policyGatewayHttpEndpointEnabled: "policy/gateway-http-endpoint-enabled",
	policyGatewayHttpUrlFetchUnrestricted: "policy/gateway-http-url-fetch-unrestricted",
	policyGatewayNodeCommandDenied: "policy/gateway-node-command-denied",
	policyAgentsWorkspaceAccessDenied: "policy/agents-workspace-access-denied",
	policyAgentsToolNotDenied: "policy/agents-tool-not-denied",
	policyToolsProfileUnapproved: "policy/tools-profile-unapproved",
	policyToolsFsWorkspaceOnlyRequired: "policy/tools-fs-workspace-only-required",
	policyToolsExecSecurityUnapproved: "policy/tools-exec-security-unapproved",
	policyToolsExecAskUnapproved: "policy/tools-exec-ask-unapproved",
	policyToolsExecHostUnapproved: "policy/tools-exec-host-unapproved",
	policyToolsElevatedEnabled: "policy/tools-elevated-enabled",
	policyToolsAlsoAllowMissing: "policy/tools-also-allow-missing",
	policyToolsAlsoAllowUnexpected: "policy/tools-also-allow-unexpected",
	policyToolsRequiredDenyMissing: "policy/tools-required-deny-missing",
	policySandboxModeUnapproved: "policy/sandbox-mode-unapproved",
	policySandboxBackendUnapproved: "policy/sandbox-backend-unapproved",
	policySandboxContainerPostureUnobservable: "policy/sandbox-container-posture-unobservable",
	policySandboxContainerHostNetworkDenied: "policy/sandbox-container-host-network-denied",
	policySandboxContainerNamespaceJoinDenied: "policy/sandbox-container-namespace-join-denied",
	policySandboxContainerMountModeRequired: "policy/sandbox-container-mount-mode-required",
	policySandboxContainerRuntimeSocketMount: "policy/sandbox-container-runtime-socket-mount",
	policySandboxContainerUnconfinedProfile: "policy/sandbox-container-unconfined-profile",
	policySandboxBrowserCdpSourceRangeMissing: "policy/sandbox-browser-cdp-source-range-missing",
	policyDataHandlingTelemetryContentCapture: "policy/data-handling-telemetry-content-capture",
	policyDataHandlingSessionRetentionNotEnforced: "policy/data-handling-session-retention-not-enforced",
	policyDataHandlingSessionTranscriptMemory: "policy/data-handling-session-transcript-memory-enabled",
	policySecretsUnmanagedProvider: "policy/secrets-unmanaged-provider",
	policySecretsDeniedProviderSource: "policy/secrets-denied-provider-source",
	policySecretsInsecureProvider: "policy/secrets-insecure-provider",
	policyAuthProfileInvalidMetadata: "policy/auth-profile-invalid-metadata",
	policyAuthProfileUnapprovedMode: "policy/auth-profile-unapproved-mode",
	policyExecApprovalsMissing: "policy/exec-approvals-missing",
	policyExecApprovalsInvalid: "policy/exec-approvals-invalid",
	policyExecApprovalsDefaultSecurityUnapproved: "policy/exec-approvals-default-security-unapproved",
	policyExecApprovalsAgentSecurityUnapproved: "policy/exec-approvals-agent-security-unapproved",
	policyExecApprovalsAutoAllowSkillsEnabled: "policy/exec-approvals-auto-allow-skills-enabled",
	policyExecApprovalsAllowlistMissing: "policy/exec-approvals-allowlist-missing",
	policyExecApprovalsAllowlistUnexpected: "policy/exec-approvals-allowlist-unexpected",
	policyMissingToolRisk: "policy/tools-missing-risk-level",
	policyUnknownToolRisk: "policy/tools-unknown-risk-level",
	policyMissingToolSensitivity: "policy/tools-missing-sensitivity-token",
	policyMissingToolOwner: "policy/tools-missing-owner",
	policyUnknownToolSensitivity: "policy/tools-unknown-sensitivity-token"
};
const POLICY_CHECK_IDS = Object.values(CHECK_IDS);
//#endregion
//#region extensions/policy/src/exec-approvals-uri.ts
const EXEC_APPROVALS_POLICY_URI = "oc://exec-approvals.json";
const EXEC_APPROVALS_POLICY_DOCUMENT_NAME = EXEC_APPROVALS_POLICY_URI.slice(5);
function execApprovalsPolicyUri(e) {
	return e ? `${EXEC_APPROVALS_POLICY_URI}/${e}` : EXEC_APPROVALS_POLICY_URI;
}
//#endregion
//#region extensions/policy/src/doctor/metadata.ts
function booleanRule(e, t, n, r = {}) {
	return {
		policyPath: e.split("."),
		strictness: n ? "requires-true" : "requires-false",
		valueType: "boolean",
		checkIds: [t],
		...r
	};
}
function allowlistRule(e, t, n = {}) {
	return {
		policyPath: e.split("."),
		strictness: "allowlist-subset",
		valueType: "string-list",
		checkIds: [t],
		emptyList: "disabled",
		...n
	};
}
function denylistRule(e, t, n = {}) {
	return {
		policyPath: e.split("."),
		strictness: "denylist-superset",
		valueType: "string-list",
		checkIds: [t],
		...n
	};
}
const SANDBOX_CONTAINER_POLICY_RULES = [
	{
		key: "denyHostNetwork",
		label: "host network posture",
		checkIds: [CHECK_IDS.policySandboxContainerHostNetworkDenied]
	},
	{
		key: "denyContainerNamespaceJoin",
		label: "container namespace posture",
		checkIds: [CHECK_IDS.policySandboxContainerNamespaceJoinDenied]
	},
	{
		key: "requireReadOnlyMounts",
		label: "container mount mode posture",
		checkIds: [CHECK_IDS.policySandboxContainerMountModeRequired]
	},
	{
		key: "denyContainerRuntimeSocketMounts",
		label: "container runtime socket mount posture",
		checkIds: [CHECK_IDS.policySandboxContainerRuntimeSocketMount]
	},
	{
		key: "denyUnconfinedProfiles",
		label: "container security profile posture",
		checkIds: [CHECK_IDS.policySandboxContainerUnconfinedProfile]
	}
];
const SANDBOX_POLICY_RULE_METADATA = [
	allowlistRule("sandbox.requireMode", CHECK_IDS.policySandboxModeUnapproved, {
		allowedValues: [
			"off",
			"non-main",
			"all"
		],
		scopeSelectors: ["agentIds"]
	}),
	allowlistRule("sandbox.allowBackends", CHECK_IDS.policySandboxBackendUnapproved, { scopeSelectors: ["agentIds"] }),
	...SANDBOX_CONTAINER_POLICY_RULES.map((e) => ({
		policyPath: [
			"sandbox",
			"containers",
			e.key
		],
		strictness: "requires-true",
		valueType: "boolean",
		checkIds: e.checkIds,
		scopeSelectors: ["agentIds"]
	})),
	booleanRule("sandbox.browser.requireCdpSourceRange", CHECK_IDS.policySandboxBrowserCdpSourceRangeMissing, true, { scopeSelectors: ["agentIds"] })
];
const POLICY_RULE_METADATA = [
	{
		policyPath: ["channels", "denyRules"],
		strictness: "denylist-superset",
		valueType: "channel-provider-deny-rules",
		checkIds: [CHECK_IDS.policyDeniedChannelProvider],
		emptyList: "meaningful",
		caseSensitive: true
	},
	allowlistRule("mcp.servers.allow", CHECK_IDS.policyUnapprovedMcpServer, { caseSensitive: true }),
	denylistRule("mcp.servers.deny", CHECK_IDS.policyDeniedMcpServer, { caseSensitive: true }),
	allowlistRule("models.providers.allow", CHECK_IDS.policyUnapprovedModelProvider, { normalizeValues: "model-provider" }),
	denylistRule("models.providers.deny", CHECK_IDS.policyDeniedModelProvider, { normalizeValues: "model-provider" }),
	booleanRule("network.privateNetwork.allow", CHECK_IDS.policyPrivateNetworkAccess, false),
	booleanRule("routing.requireBindings", CHECK_IDS.policyRoutingBindingsRequired, true),
	booleanRule("routing.requireConfiguredChannels", CHECK_IDS.policyRoutingBindingChannelUnconfigured, true),
	{
		policyPath: ["routing", "probes"],
		strictness: "routing-probes",
		valueType: "routing-probes",
		checkIds: [CHECK_IDS.policyRoutingAgentMismatch, CHECK_IDS.policyRoutingMatchKindMismatch]
	},
	{
		policyPath: [
			"ingress",
			"session",
			"requireDmScope"
		],
		strictness: "ordered-string",
		valueType: "string",
		orderedValues: [
			"main",
			"per-peer",
			"per-channel-peer",
			"per-account-channel-peer"
		],
		checkIds: [CHECK_IDS.policyIngressDmScopeUnapproved]
	},
	booleanRule("gateway.exposure.allowNonLoopbackBind", CHECK_IDS.policyGatewayNonLoopbackBind, false),
	booleanRule("gateway.exposure.allowTailscaleFunnel", CHECK_IDS.policyGatewayTailscaleFunnel, false),
	booleanRule("gateway.auth.requireAuth", CHECK_IDS.policyGatewayAuthDisabled, true),
	booleanRule("gateway.auth.requireExplicitRateLimit", CHECK_IDS.policyGatewayRateLimitMissing, true),
	booleanRule("gateway.controlUi.allowInsecure", CHECK_IDS.policyGatewayControlUiInsecure, false),
	booleanRule("gateway.remote.allow", CHECK_IDS.policyGatewayRemoteEnabled, false),
	denylistRule("gateway.http.denyEndpoints", CHECK_IDS.policyGatewayHttpEndpointEnabled, {
		allowedValues: ["chatCompletions", "responses"],
		caseSensitive: true
	}),
	booleanRule("gateway.http.requireUrlAllowlists", CHECK_IDS.policyGatewayHttpUrlFetchUnrestricted, true),
	denylistRule("gateway.nodes.denyCommands", CHECK_IDS.policyGatewayNodeCommandDenied, { caseSensitive: true }),
	allowlistRule("agents.workspace.allowedAccess", CHECK_IDS.policyAgentsWorkspaceAccessDenied, {
		allowedValues: [
			"none",
			"ro",
			"rw"
		],
		scopeSelectors: ["agentIds"]
	}),
	denylistRule("agents.workspace.denyTools", CHECK_IDS.policyAgentsToolNotDenied, {
		allowedValues: [
			"exec",
			"process",
			"write",
			"edit",
			"apply_patch"
		],
		scopeSelectors: ["agentIds"]
	}),
	allowlistRule("tools.profiles.allow", CHECK_IDS.policyToolsProfileUnapproved, {
		allowedValues: [
			"minimal",
			"coding",
			"messaging",
			"full"
		],
		scopeSelectors: ["agentIds"]
	}),
	booleanRule("tools.fs.requireWorkspaceOnly", CHECK_IDS.policyToolsFsWorkspaceOnlyRequired, true, { scopeSelectors: ["agentIds"] }),
	allowlistRule("tools.exec.allowSecurity", CHECK_IDS.policyToolsExecSecurityUnapproved, {
		allowedValues: [
			"deny",
			"allowlist",
			"full"
		],
		scopeSelectors: ["agentIds"]
	}),
	allowlistRule("tools.exec.requireAsk", CHECK_IDS.policyToolsExecAskUnapproved, {
		allowedValues: [
			"off",
			"on-miss",
			"always"
		],
		scopeSelectors: ["agentIds"]
	}),
	allowlistRule("tools.exec.allowHosts", CHECK_IDS.policyToolsExecHostUnapproved, {
		allowedValues: [
			"auto",
			"sandbox",
			"gateway",
			"node"
		],
		scopeSelectors: ["agentIds"]
	}),
	booleanRule("tools.elevated.allow", CHECK_IDS.policyToolsElevatedEnabled, false, { scopeSelectors: ["agentIds"] }),
	{
		policyPath: [
			"tools",
			"alsoAllow",
			"expected"
		],
		strictness: "exact-list",
		valueType: "string-list",
		checkIds: [CHECK_IDS.policyToolsAlsoAllowMissing, CHECK_IDS.policyToolsAlsoAllowUnexpected],
		emptyList: "meaningful",
		scopeSelectors: ["agentIds"]
	},
	denylistRule("tools.denyTools", CHECK_IDS.policyToolsRequiredDenyMissing, { scopeSelectors: ["agentIds"] }),
	{
		policyPath: ["tools", "requireMetadata"],
		strictness: "denylist-superset",
		valueType: "string-list",
		checkIds: [
			CHECK_IDS.policyUnmigratedToolsFile,
			CHECK_IDS.policyMissingToolRisk,
			CHECK_IDS.policyMissingToolSensitivity,
			CHECK_IDS.policyMissingToolOwner
		],
		allowedValues: [
			"risk",
			"sensitivity",
			"owner"
		]
	},
	...SANDBOX_POLICY_RULE_METADATA,
	allowlistRule("ingress.channels.allowDmPolicies", CHECK_IDS.policyIngressDmPolicyUnapproved, {
		allowedValues: [
			"pairing",
			"allowlist",
			"open",
			"disabled"
		],
		scopeSelectors: ["channelIds"]
	}),
	booleanRule("ingress.channels.denyOpenGroups", CHECK_IDS.policyIngressOpenGroupsDenied, true, { scopeSelectors: ["channelIds"] }),
	booleanRule("ingress.channels.requireMentionInGroups", CHECK_IDS.policyIngressGroupMentionRequired, true, { scopeSelectors: ["channelIds"] }),
	{
		policyPath: [
			"dataHandling",
			"sensitiveLogging",
			"requireRedaction"
		],
		strictness: "requires-true",
		valueType: "boolean",
		checkIds: []
	},
	booleanRule("dataHandling.telemetry.denyContentCapture", CHECK_IDS.policyDataHandlingTelemetryContentCapture, true),
	booleanRule("dataHandling.retention.requireSessionMaintenance", CHECK_IDS.policyDataHandlingSessionRetentionNotEnforced, true),
	booleanRule("dataHandling.memory.denySessionTranscriptIndexing", CHECK_IDS.policyDataHandlingSessionTranscriptMemory, true, { scopeSelectors: ["agentIds"] }),
	booleanRule("secrets.requireManagedProviders", CHECK_IDS.policySecretsUnmanagedProvider, true),
	denylistRule("secrets.denySources", CHECK_IDS.policySecretsDeniedProviderSource),
	booleanRule("secrets.allowInsecureProviders", CHECK_IDS.policySecretsInsecureProvider, false),
	booleanRule("execApprovals.requireFile", CHECK_IDS.policyExecApprovalsMissing, true),
	allowlistRule("execApprovals.defaults.allowSecurity", CHECK_IDS.policyExecApprovalsDefaultSecurityUnapproved, { allowedValues: [
		"deny",
		"allowlist",
		"full"
	] }),
	allowlistRule("execApprovals.agents.allowSecurity", CHECK_IDS.policyExecApprovalsAgentSecurityUnapproved, {
		allowedValues: [
			"deny",
			"allowlist",
			"full"
		],
		scopeSelectors: ["agentIds"]
	}),
	booleanRule("execApprovals.agents.allowAutoAllowSkills", CHECK_IDS.policyExecApprovalsAutoAllowSkillsEnabled, false, { scopeSelectors: ["agentIds"] }),
	{
		policyPath: [
			"execApprovals",
			"agents",
			"allowlist",
			"expected"
		],
		strictness: "exact-list",
		valueType: "string-list",
		checkIds: [CHECK_IDS.policyExecApprovalsAllowlistMissing, CHECK_IDS.policyExecApprovalsAllowlistUnexpected],
		emptyList: "meaningful",
		caseSensitive: true,
		scopeSelectors: ["agentIds"]
	},
	denylistRule("auth.profiles.requireMetadata", CHECK_IDS.policyAuthProfileInvalidMetadata, { allowedValues: ["provider", "mode"] }),
	allowlistRule("auth.profiles.allowModes", CHECK_IDS.policyAuthProfileUnapprovedMode, { allowedValues: [
		"api_key",
		"aws-sdk",
		"oauth",
		"token"
	] })
];
//#endregion
//#region extensions/policy/src/doctor/fix-metadata.ts
const defineCheck = (e, t, n, r, i, a = POLICY_RULE_METADATA.find((t) => t.checkIds.includes(e))?.policyPath) => {
	return {
		description: t,
		fix: {
			checkId: e,
			fixClass: n,
			summary: r,
			...a === void 0 ? {} : { policyPath: a },
			...i === void 0 ? {} : { configTargets: i }
		}
	};
};
const POLICY_CHECK_METADATA = [
	defineCheck(CHECK_IDS.policyMissingFile, "The enabled Policy plugin has a policy file to verify.", "manual", "Restore or author the approved policy artifact."),
	defineCheck(CHECK_IDS.policyInvalidFile, "The enabled policy file parses before policy checks run.", "manual", "Repair the policy JSONC syntax or schema."),
	defineCheck(CHECK_IDS.policyHashMismatch, "The policy file matches the configured expected hash.", "manual", "Restore the approved artifact or update the expected hash after review.", ["plugins.entries.policy.config.expectedHash"]),
	defineCheck(CHECK_IDS.policyAttestationMismatch, "The current policy check matches the accepted attestation.", "manual", "Review the current attestation and update accepted hashes after approval.", ["plugins.entries.policy.config.expectedAttestationHash"]),
	defineCheck(CHECK_IDS.policyDeniedChannelProvider, "Configured channels satisfy policy deny rules.", "automatic", "Disable product-managed channels matching the denied provider.", ["channels"]),
	defineCheck(CHECK_IDS.policyDeniedMcpServer, "Configured MCP servers do not match policy deny rules.", "reviewRequired", "Remove or disable the denied MCP server.", ["mcp.servers"]),
	defineCheck(CHECK_IDS.policyUnapprovedMcpServer, "Configured MCP servers do not match policy allow rules.", "reviewRequired", "Remove the unapproved MCP server or select an approved replacement.", ["mcp.servers"]),
	defineCheck(CHECK_IDS.policyDeniedModelProvider, "Configured model providers do not match policy deny rules.", "reviewRequired", "Remove the model provider or switch references to an approved provider.", ["models"]),
	defineCheck(CHECK_IDS.policyUnapprovedModelProvider, "Configured model providers do not match policy allow rules.", "reviewRequired", "Select an approved model provider.", ["models"]),
	defineCheck(CHECK_IDS.policyPrivateNetworkAccess, "Network SSRF policy settings match private-network requirements.", "reviewRequired", "Disable the concrete private-network access opt-in.", ["network"]),
	defineCheck(CHECK_IDS.policyIngressDmPolicyUnapproved, "Channel direct-message access policy matches ingress requirements.", "reviewRequired", "Set channel DM policy to an allowed value.", ["channels"]),
	defineCheck(CHECK_IDS.policyIngressDmScopeUnapproved, "Direct-message sessions use the policy-required isolation scope.", "reviewRequired", "Move session DM scope to the required or stricter ordered value.", ["ingress"]),
	defineCheck(CHECK_IDS.policyIngressOpenGroupsDenied, "Channel group access does not use open group policy when denied.", "automatic", "Disable product-managed open group ingress.", ["channels"]),
	defineCheck(CHECK_IDS.policyIngressGroupMentionRequired, "Channel group access keeps mention gates enabled when required.", "automatic", "Require mention in product-managed group channels.", ["channels"]),
	defineCheck(CHECK_IDS.policyRoutingBindingsRequired, "Routing policy has at least one channel route binding when required.", "reviewRequired", "Add an intentional channel route binding or revise the policy after review.", ["bindings"]),
	defineCheck(CHECK_IDS.policyRoutingBindingChannelUnconfigured, "Route bindings name channels present in configuration.", "reviewRequired", "Correct the binding channel or configure the intended channel after review.", ["bindings", "channels"]),
	defineCheck(CHECK_IDS.policyRoutingAgentMismatch, "Authored routing checks resolve to their expected agents.", "reviewRequired", "Review binding precedence and the expected agent before changing message delivery.", ["bindings"]),
	defineCheck(CHECK_IDS.policyRoutingMatchKindMismatch, "Authored routing checks match at their expected specificity.", "reviewRequired", "Restore the intended binding specificity or approve the new match kind.", ["bindings"]),
	defineCheck(CHECK_IDS.policyGatewayNonLoopbackBind, "Gateway bind posture matches policy exposure requirements.", "reviewRequired", "Set gateway bind address to loopback when remote exposure is not intended.", ["gateway.bind"]),
	defineCheck(CHECK_IDS.policyGatewayAuthDisabled, "Gateway authentication remains enabled when required by policy.", "manual", "Configure token, password, or trusted-proxy auth.", ["gateway.auth"]),
	defineCheck(CHECK_IDS.policyGatewayRateLimitMissing, "Gateway authentication rate-limit posture is explicit when required by policy.", "reviewRequired", "Add explicit gateway auth rate limits from product defaults.", ["gateway.auth.rateLimit"]),
	defineCheck(CHECK_IDS.policyGatewayControlUiInsecure, "Gateway Control UI insecure exposure toggles remain disabled by policy.", "automatic", "Disable the insecure Control UI toggle.", ["gateway.controlUi"]),
	defineCheck(CHECK_IDS.policyGatewayTailscaleFunnel, "Gateway Tailscale Funnel exposure matches policy.", "reviewRequired", "Disable Tailscale funnel or serve exposure.", ["tailscale"]),
	defineCheck(CHECK_IDS.policyGatewayRemoteEnabled, "Remote gateway mode matches policy.", "automatic", "Disable product-managed remote gateway mode.", ["gateway.remote"]),
	defineCheck(CHECK_IDS.policyGatewayHttpEndpointEnabled, "Gateway HTTP API endpoints match policy.", "automatic", "Disable denied Gateway HTTP endpoints.", ["gateway.http"]),
	defineCheck(CHECK_IDS.policyGatewayHttpUrlFetchUnrestricted, "Gateway HTTP URL-fetch inputs have allowlists when required by policy.", "manual", "Add URL allowlists for each URL-fetch input.", ["gateway.http"]),
	defineCheck(CHECK_IDS.policyGatewayNodeCommandDenied, "Gateway node command allowlists match policy.", "reviewRequired", "Add the command to gateway node denyCommands or update policy after review.", ["gateway.nodes.commands.deny"]),
	defineCheck(CHECK_IDS.policyAgentsWorkspaceAccessDenied, "Agent sandbox workspace access matches policy.", "reviewRequired", "Set agent workspace access to an allowed mode.", ["agents"]),
	defineCheck(CHECK_IDS.policyAgentsToolNotDenied, "Agent workspace mutation/runtime tools are denied when policy requires it.", "automatic", "Merge required built-in workspace tool denies.", ["agents"]),
	defineCheck(CHECK_IDS.policyToolsProfileUnapproved, "Configured tool profiles match policy allow rules.", "reviewRequired", "Set the tool profile to an allowed profile.", ["tools.profile"]),
	defineCheck(CHECK_IDS.policyToolsFsWorkspaceOnlyRequired, "Filesystem tools use workspace-only posture when policy requires it.", "reviewRequired", "Set workspace-only filesystem posture when required assets remain readable.", ["tools.fs.workspaceOnly"]),
	defineCheck(CHECK_IDS.policyToolsExecSecurityUnapproved, "Exec tool security mode matches policy allow rules.", "reviewRequired", "Set exec security to an allowed value.", ["tools.exec.security"]),
	defineCheck(CHECK_IDS.policyToolsExecAskUnapproved, "Exec tool ask mode matches policy allow rules.", "reviewRequired", "Set exec ask mode to an allowed value.", ["tools.exec.ask"]),
	defineCheck(CHECK_IDS.policyToolsExecHostUnapproved, "Exec tool host routing matches policy allow rules.", "reviewRequired", "Move exec host to an allowed host mode.", ["tools.exec.host"]),
	defineCheck(CHECK_IDS.policyToolsElevatedEnabled, "Elevated tool mode remains disabled when policy requires it.", "automatic", "Set tools elevated mode to disabled.", ["tools.elevated.enabled"]),
	defineCheck(CHECK_IDS.policyToolsAlsoAllowMissing, "Configured tools.alsoAllow entries include policy expected lists.", "reviewRequired", "Add expected alsoAllow entries only when policy intentionally grants them.", ["tools.alsoAllow"]),
	defineCheck(CHECK_IDS.policyToolsAlsoAllowUnexpected, "Configured tools.alsoAllow entries match policy expected lists.", "reviewRequired", "Remove unexpected alsoAllow entries.", ["tools.alsoAllow"]),
	defineCheck(CHECK_IDS.policyToolsRequiredDenyMissing, "Configured tool deny lists include tools required by policy.", "automatic", "Merge required built-in deny tool classes.", ["tools.deny", "agents.entries.<id>.tools.deny"]),
	defineCheck(CHECK_IDS.policySandboxModeUnapproved, "Sandbox mode config satisfies policy requirements.", "reviewRequired", "Set sandbox mode to an allowed value.", ["sandbox.mode"]),
	defineCheck(CHECK_IDS.policySandboxBackendUnapproved, "Sandbox backend config satisfies policy requirements.", "reviewRequired", "Choose an approved sandbox backend that is installed.", ["sandbox.backend"]),
	defineCheck(CHECK_IDS.policySandboxContainerPostureUnobservable, "Sandbox container posture policy only targets observable container backends.", "unsupported", "Add observable container posture evidence before patching."),
	defineCheck(CHECK_IDS.policySandboxContainerHostNetworkDenied, "Sandbox container config avoids host network mode.", "reviewRequired", "Disable container host networking.", ["sandbox.containers"]),
	defineCheck(CHECK_IDS.policySandboxContainerNamespaceJoinDenied, "Sandbox container config avoids joining another container network namespace.", "reviewRequired", "Disable joining container namespaces.", ["sandbox.containers"]),
	defineCheck(CHECK_IDS.policySandboxContainerMountModeRequired, "Sandbox container mounts are read-only when policy requires it.", "reviewRequired", "Change required mounts to read-only.", ["sandbox.containers"]),
	defineCheck(CHECK_IDS.policySandboxContainerRuntimeSocketMount, "Sandbox container mounts avoid host container runtime sockets.", "reviewRequired", "Remove container runtime socket binds.", ["sandbox.containers"]),
	defineCheck(CHECK_IDS.policySandboxContainerUnconfinedProfile, "Sandbox container profile config avoids unconfined profiles.", "reviewRequired", "Remove unconfined container profiles.", ["sandbox.containers"]),
	defineCheck(CHECK_IDS.policySandboxBrowserCdpSourceRangeMissing, "Sandbox browser CDP config includes a source range when policy requires it.", "manual", "Add an explicit browser CDP source range.", ["agents.sandbox.browser"]),
	defineCheck(CHECK_IDS.policyDataHandlingTelemetryContentCapture, "Telemetry content capture remains disabled when policy denies it.", "automatic", "Disable telemetry content capture.", ["diagnostics.otel.captureContent"]),
	defineCheck(CHECK_IDS.policyDataHandlingSessionRetentionNotEnforced, "Session retention maintenance is enforced when policy requires it.", "reviewRequired", "Set session maintenance to enforced mode.", ["session.maintenance.mode"]),
	defineCheck(CHECK_IDS.policyDataHandlingSessionTranscriptMemory, "Session transcript memory indexing remains disabled when policy denies it.", "reviewRequired", "Disable transcript indexing for the affected agent scope.", ["memory"]),
	defineCheck(CHECK_IDS.policySecretsUnmanagedProvider, "OpenClaw config SecretRefs use configured secret providers when policy requires managed providers.", "manual", "Migrate the secret to a managed provider.", ["secrets"]),
	defineCheck(CHECK_IDS.policySecretsDeniedProviderSource, "OpenClaw config secret providers and SecretRefs do not use sources denied by policy.", "reviewRequired", "Move the secret out of the denied source.", ["secrets"]),
	defineCheck(CHECK_IDS.policySecretsInsecureProvider, "Configured secret providers do not opt into insecure posture unless policy allows it.", "reviewRequired", "Remove insecure provider overrides.", ["secrets"]),
	defineCheck(CHECK_IDS.policyAuthProfileInvalidMetadata, "OpenClaw config auth profiles declare required provider and mode metadata.", "manual", "Add required provider and mode metadata to auth profiles.", ["auth.profiles"]),
	defineCheck(CHECK_IDS.policyAuthProfileUnapprovedMode, "OpenClaw config auth profile modes stay within the policy allowlist.", "manual", "Change auth mode and credentials through the auth owner flow.", ["auth.profiles"]),
	defineCheck(CHECK_IDS.policyExecApprovalsMissing, "Required exec approvals artifact is present for policy conformance.", "manual", "Restore an attributable exec-approvals evidence file.", [EXEC_APPROVALS_POLICY_DOCUMENT_NAME]),
	defineCheck(CHECK_IDS.policyExecApprovalsInvalid, "Exec approvals artifact parses before policy checks run.", "manual", "Repair the exec approvals evidence artifact."),
	defineCheck(CHECK_IDS.policyExecApprovalsDefaultSecurityUnapproved, "Exec approval defaults use a policy-approved security mode.", "manual", "Update reviewed default approval evidence or policy.", [EXEC_APPROVALS_POLICY_DOCUMENT_NAME]),
	defineCheck(CHECK_IDS.policyExecApprovalsAgentSecurityUnapproved, "Per-agent exec approval settings use policy-approved security modes.", "manual", "Update reviewed agent approval evidence or policy.", [EXEC_APPROVALS_POLICY_DOCUMENT_NAME]),
	defineCheck(CHECK_IDS.policyExecApprovalsAutoAllowSkillsEnabled, "Exec approval agents do not implicitly auto-allow skill CLIs unless policy allows it.", "reviewRequired", "Disable auto-allow skills in the approval owner surface.", [EXEC_APPROVALS_POLICY_DOCUMENT_NAME]),
	defineCheck(CHECK_IDS.policyExecApprovalsAllowlistMissing, "Exec approval allowlists include every pattern required by policy.", "manual", "Add expected approval patterns through approval review.", [EXEC_APPROVALS_POLICY_DOCUMENT_NAME]),
	defineCheck(CHECK_IDS.policyExecApprovalsAllowlistUnexpected, "Exec approval allowlists do not contain patterns outside policy.", "manual", "Remove unexpected approval patterns through approval review.", [EXEC_APPROVALS_POLICY_DOCUMENT_NAME]),
	defineCheck(CHECK_IDS.policyUnmigratedToolsFile, "Governed tool declarations have been migrated from TOOLS.md into AGENTS.md.", "manual", "Run openclaw doctor --fix to migrate governed tool declarations into AGENTS.md."),
	defineCheck(CHECK_IDS.policyMissingToolRisk, "AGENTS.md tool policy entries declare explicit risk levels.", "manual", "Add tool risk metadata in the owning tool declaration.", ["tools"]),
	defineCheck(CHECK_IDS.policyUnknownToolRisk, "AGENTS.md tool policy entries use known risk levels.", "manual", "Use a supported tool risk level.", ["tools"], ["tools", "requireMetadata"]),
	defineCheck(CHECK_IDS.policyMissingToolSensitivity, "AGENTS.md tool policy entries declare default artifact sensitivity.", "manual", "Add tool sensitivity metadata in the owning tool declaration.", ["tools"]),
	defineCheck(CHECK_IDS.policyMissingToolOwner, "AGENTS.md tool policy entries declare an accountable owner.", "manual", "Add owner metadata in the owning tool declaration.", ["tools"]),
	defineCheck(CHECK_IDS.policyUnknownToolSensitivity, "AGENTS.md tool policy entries use known sensitivity levels.", "manual", "Use a supported tool sensitivity token.", ["tools"], ["tools", "requireMetadata"])
];
const POLICY_FIX_METADATA_BY_CHECK_ID = new Map(POLICY_CHECK_METADATA.toSorted((e, t) => POLICY_CHECK_IDS.indexOf(e.fix.checkId) - POLICY_CHECK_IDS.indexOf(t.fix.checkId)).map(({ fix: e }) => [e.checkId, e]));
//#endregion
//#region extensions/policy/src/doctor/policy-constants.ts
const KNOWN_RISK_LEVELS = [
	"low",
	"medium",
	"high",
	"critical"
];
const KNOWN_SENSITIVITY_LEVELS = [
	"public",
	"internal",
	"confidential",
	"restricted"
];
const SUPPORTED_TOOL_METADATA = [
	"risk",
	"sensitivity",
	"owner"
];
const SUPPORTED_AUTH_PROFILE_METADATA = ["provider", "mode"];
const SUPPORTED_AUTH_PROFILE_MODES = [
	"api_key",
	"aws-sdk",
	"oauth",
	"token"
];
const SUPPORTED_POLICY_SECTIONS = [
	"auth",
	"agents",
	"channels",
	"dataHandling",
	"execApprovals",
	"gateway",
	"ingress",
	"mcp",
	"models",
	"network",
	"routing",
	"sandbox",
	"scopes",
	"secrets",
	"tools"
];
const SUPPORTED_DM_POLICIES = [
	"pairing",
	"allowlist",
	"open",
	"disabled"
];
const SUPPORTED_DM_SCOPES = [
	"main",
	"per-peer",
	"per-channel-peer",
	"per-account-channel-peer"
];
const SUPPORTED_EXEC_APPROVAL_SECURITY = [
	"deny",
	"allowlist",
	"full"
];
//#endregion
//#region extensions/policy/src/doctor/shape-helpers.ts
function isChannelDenyRule(e) {
	return isRecord(e) && (e.id === void 0 || typeof e.id === "string") && (e.reason === void 0 || typeof e.reason === "string") && isRecord(e.when) && typeof e.when.provider === "string";
}
function policyShapeFinding(e, t, n, r) {
	return {
		checkId: CHECK_IDS.policyInvalidFile,
		severity: "error",
		message: n,
		source: "policy",
		path: e,
		target: t,
		fixHint: r
	};
}
//#endregion
//#region extensions/policy/src/policy-value.ts
function getPolicyPath(e, t) {
	let n = e;
	for (const e of t) {
		if (!isRecord(n)) return;
		n = n[e];
	}
	return n;
}
//#endregion
//#region extensions/policy/src/policy-state-helpers.ts
function ocPathSegment$1(e) {
	if (/^(?:[A-Za-z0-9_-]+|#\d+)$/.test(e)) return e;
	if (e.includes("\"") || e.includes("\\")) return e;
	return `"${e}"`;
}
function readBooleanPath(e, t) {
	const n = getPolicyPath(e, t);
	return typeof n === "boolean" ? n : void 0;
}
function collectPolicyConfiguredAgents(e) {
	const t = e.entries;
	if (Object.hasOwn(e, "entries") && t !== void 0) return isRecord(t) ? Object.entries(t).filter((e) => isRecord(e[1])).toSorted(([e], [t]) => e.localeCompare(t)).map(([e, t]) => ({
		agentId: e,
		sourceBase: `oc://openclaw.config/agents/entries/${ocPathSegment$1(e)}`,
		value: t
	})) : [];
	return Array.isArray(e.list) ? e.list.flatMap((e, t) => isRecord(e) ? [{
		agentId: typeof e.id === "string" && e.id.trim() !== "" ? e.id.trim() : `agent-${t}`,
		sourceBase: `oc://openclaw.config/agents/list/#${t}`,
		value: e
	}] : []) : [];
}
function collectPolicyAgentContexts(e, t) {
	const n = asNonArrayRecord(e.agents);
	const r = asNonArrayRecord(asNonArrayRecord(n.defaults).sandbox);
	const i = asNonArrayRecord(e.tools);
	return [{
		id: t === "global" ? "tools" : "agents-defaults",
		scope: t,
		sandbox: r,
		inheritedSandbox: {},
		tools: i,
		inheritedTools: {},
		workspaceSourceBase: "oc://openclaw.config/agents/defaults",
		toolsSourceBase: "oc://openclaw.config/tools"
	}, ...collectPolicyConfiguredAgents(n).map(({ agentId: e, sourceBase: t, value: n }) => ({
		id: e,
		scope: "agent",
		agentId: e,
		sandbox: asNonArrayRecord(n.sandbox),
		inheritedSandbox: r,
		tools: asNonArrayRecord(n.tools),
		inheritedTools: i,
		workspaceSourceBase: t,
		toolsSourceBase: `${t}/tools`
	}))];
}
function resolvePolicyValue(e, t, n) {
	return {
		value: e ?? t ?? n,
		explicit: e !== void 0 || t !== void 0,
		inherited: e === void 0 && t !== void 0
	};
}
//#endregion
//#region extensions/policy/src/doctor/utils.ts
function readPolicyStringArray(e, t, n = {}) {
	const r = getPolicyPath(e, t);
	if (!isStringArray(r)) return;
	return n.lowercase === false ? normalizeStringEntries(r) : normalizeStringEntriesLower(r);
}
function readStringList(e, t, n) {
	return readPolicyStringArray(e, t, n) ?? [];
}
function readPolicyPathString(e, t) {
	const n = getPolicyPath(e, t);
	return typeof n === "string" ? n.trim().toLowerCase() : void 0;
}
function ocPathSegment(e) {
	if (/^(?:[A-Za-z0-9_-]+|#\d+)$/.test(e)) return e;
	return JSON.stringify(e);
}
//#endregion
//#region extensions/policy/src/doctor/policy-runtime.ts
async function readPolicyFile(e) {
	const t = policyDisplayName(e);
	const n = await readWorkspaceFile(e, policyPathSetting(e));
	return n === null ? null : {
		...n,
		displayName: t,
		ocDocName: basename(t)
	};
}
async function readExecApprovalsFile() {
	const e = await readExecApprovalsSnapshotForPlugin();
	if (!e.exists || e.raw === null) return null;
	return {
		raw: e.raw,
		path: e.path,
		displayName: e.path,
		ocDocName: EXEC_APPROVALS_POLICY_DOCUMENT_NAME
	};
}
async function readWorkspaceFile(e, t) {
	const n = resolveWorkspacePath(e, t);
	try {
		return {
			raw: await (await import("node:fs/promises")).readFile(n, "utf-8"),
			path: n
		};
	} catch (e) {
		if (isNotFoundPathError(e)) return null;
		throw e;
	}
}
function resolveWorkspacePath(e, t) {
	if (isAbsolute(t)) return t;
	return resolve(e.cwd ?? process.cwd(), t);
}
function isNotFoundPathError(e) {
	return typeof e === "object" && e !== null && "code" in e && e.code === "ENOENT";
}
function parsePolicyFile(e) {
	try {
		return {
			ok: true,
			value: JSON5.parse(e)
		};
	} catch (e) {
		return {
			ok: false,
			message: e instanceof Error ? e.message : String(e)
		};
	}
}
function workspaceRepairsEnabled(e) {
	return policySettings(e).workspaceRepairs === true;
}
function readChannelDenyRules(e, t) {
	if (!isRecord(e) || !isRecord(e.channels) || !Array.isArray(e.channels.denyRules)) return [];
	return e.channels.denyRules.flatMap((e, n) => isChannelDenyRule(e) ? [{
		when: e.when,
		requirement: `oc://${t}/channels/denyRules/#${n}`,
		...e.reason === void 0 ? {} : { reason: e.reason }
	}] : []);
}
function channelIdsFromFindings(e) {
	return [...new Set(e.filter((e) => e.checkId === CHECK_IDS.policyDeniedChannelProvider).map((e) => e.ocPath?.match(/^oc:\/\/openclaw\.config\/channels\/(.+)$/)?.[1]).filter((e) => e !== void 0 && e !== ""))];
}
function disableChannels(e, t) {
	if (!isRecord(e.channels)) return {
		config: e,
		changed: []
	};
	const n = { ...e.channels };
	const r = [];
	for (const e of t) {
		const t = n[e];
		if (!isRecord(t) || t.enabled === false) continue;
		n[e] = {
			...t,
			enabled: false
		};
		r.push(e);
	}
	if (r.length === 0) return {
		config: e,
		changed: r
	};
	return {
		config: {
			...e,
			channels: n
		},
		changed: r
	};
}
function policySettings(e) {
	const t = e.cfg.plugins?.entries?.["policy"]?.config;
	if (!isRecord(t)) return {};
	return t;
}
function policyChecksEnabled(e, t) {
	const n = e.cfg.plugins?.entries?.["policy"];
	if (!isRecord(n) || n.enabled === false) return false;
	return t.enabled !== false;
}
function requiredToolMetadata(e) {
	return new Set(readPolicyStringArray(e, ["tools", "requireMetadata"]) ?? []);
}
function requiredAuthProfileMetadata(e) {
	const t = readPolicyStringArray(e, [
		"auth",
		"profiles",
		"requireMetadata"
	]) ?? [];
	return new Set(t.filter((e) => SUPPORTED_AUTH_PROFILE_METADATA.some((t) => t === e)));
}
function authProfileHasMetadata(e, t) {
	if (t === "provider") return e.provider !== void 0 && e.provider.trim() !== "";
	return SUPPORTED_AUTH_PROFILE_MODES.some((t) => t === e.mode);
}
function policyPathSetting(e) {
	const t = policySettings(e).path;
	return typeof t === "string" && t.trim() !== "" ? t.trim() : "policy.jsonc";
}
function policyDisplayName(e) {
	const t = policyPathSetting(e);
	return isAbsolute(t) ? basename(t) : t;
}
//#endregion
//#region extensions/policy/src/policy-routing.ts
const ROUTING_MATCH_KINDS = [
	"binding.peer",
	"binding.peer.parent",
	"binding.peer.wildcard",
	"binding.guild+roles",
	"binding.guild",
	"binding.team",
	"binding.account",
	"binding.channel",
	"default"
];
function validPolicyRoutingMatchKinds(e) {
	return Array.isArray(e) && e.length > 0 && e.every((e) => typeof e === "string" && ROUTING_MATCH_KINDS.some((t) => t === e)) && new Set(e).size === e.length;
}
function policyRoutingRules(e) {
	if (!isRecord(e) || !isRecord(e.routing)) return;
	return e.routing;
}
function scanPolicyRouting(e, t) {
	return {
		bindings: listPolicyRouteBindings(e),
		probes: (t.probes ?? []).map((t, n) => {
			const r = resolveAgentRoute({
				cfg: e,
				channel: t.route.channel,
				accountId: t.route.accountId,
				peer: t.route.peer,
				parentPeer: t.route.parentPeer,
				guildId: t.route.guildId,
				teamId: t.route.teamId,
				memberRoleIds: t.route.memberRoleIds === void 0 ? void 0 : [...t.route.memberRoleIds]
			});
			return {
				id: t.id,
				source: `oc://policy/routing/probes/#${n}`,
				agentId: r.agentId,
				matchedBy: r.matchedBy
			};
		})
	};
}
function listPolicyRouteBindings(e) {
	if (!Array.isArray(e.bindings)) return [];
	const t = [];
	for (const [n, r] of e.bindings.entries()) {
		if (!isRecord(r) || r.type === "acp" || !isRecord(r.match)) continue;
		if (typeof r.agentId !== "string" || typeof r.match.channel !== "string") continue;
		t.push({
			index: n,
			source: `oc://openclaw.config/bindings/#${n}`,
			channel: r.match.channel
		});
	}
	return t;
}
//#endregion
//#region extensions/policy/src/policy-state-data.ts
function scanPolicySecrets(e) {
	const t = [...scanPolicySecretProviders(e)];
	collectSecretInputs(t, e, [], secretRefDefaults(asNonArrayRecord(e.secrets).defaults));
	return t.toSorted((e, t) => e.source.localeCompare(t.source));
}
function scanPolicyAuthProfiles(e) {
	const t = asNonArrayRecord(e.auth);
	const n = asNonArrayRecord(t.profiles);
	return Object.entries(n).toSorted(([e], [t]) => e.localeCompare(t)).map(([e, t]) => {
		const n = {
			id: e,
			source: `oc://openclaw.config/auth/profiles/${ocPathSegment$1(e)}`,
			validMetadata: isValidAuthProfileMetadata(t)
		};
		if (isRecord(t)) {
			if (typeof t.provider === "string") n.provider = t.provider;
			if (typeof t.mode === "string") n.mode = t.mode;
		}
		return n;
	});
}
function scanPolicyDataHandling(e) {
	const t = [];
	t.push({
		id: "logging-redaction",
		kind: "sensitiveLoggingRedaction",
		source: "oc://openclaw.invariant/logging/redaction",
		scope: "global",
		value: true,
		explicit: true
	});
	const n = asNonArrayRecord(e.diagnostics);
	const r = asNonArrayRecord(n.otel);
	const i = n.enabled !== false && r.enabled === true;
	const a = i && r.traces !== false;
	const o = i && r.logs === true;
	const s = i && telemetryContentCaptureEnabled(r.captureContent, {
		tracesEnabled: a,
		logsEnabled: o
	});
	t.push({
		id: "diagnostics-otel-content-capture",
		kind: "telemetryContentCapture",
		source: "oc://openclaw.config/diagnostics/otel/captureContent",
		scope: "global",
		value: s,
		explicit: r.captureContent !== void 0
	});
	const c = asNonArrayRecord(e.session);
	const l = asNonArrayRecord(c.maintenance);
	const u = typeof l.mode === "string" ? l.mode : "enforce";
	t.push({
		id: "session-maintenance-mode",
		kind: "sessionRetentionMode",
		source: "oc://openclaw.config/session/maintenance/mode",
		scope: "global",
		value: u,
		explicit: l.mode !== void 0
	});
	pushMemorySessionTranscriptIndexing(t, e);
	return t.toSorted((e, t) => e.source.localeCompare(t.source));
}
function telemetryContentCaptureEnabled(e, t) {
	if (e === true) return t.tracesEnabled || t.logsEnabled;
	if (!isRecord(e) || !t.tracesEnabled || e.enabled !== true) return false;
	return e.inputMessages === true || e.outputMessages === true || e.toolInputs === true || e.toolOutputs === true || e.systemPrompt === true || e.toolDefinitions === true;
}
function pushMemorySessionTranscriptIndexing(e, t) {
	const n = readMemorySessionSettings(asNonArrayRecord(t.memory).search);
	const r = memorySearchSessionTranscriptIndexing(n);
	if (r !== void 0) e.push({
		id: "agents-defaults-memory-session-transcripts",
		kind: "memorySessionTranscriptIndexing",
		source: `oc://openclaw.config/memory/search/${n.sourceKey}`,
		scope: "global",
		value: r,
		explicit: true
	});
	const i = asNonArrayRecord(t.agents);
	collectPolicyConfiguredAgents(i).forEach((t) => {
		const { agentId: i, value: a } = t;
		const o = asNonArrayRecord(a.memory).search;
		const s = readMemorySessionSettings(o);
		const c = isRecord(o) ? memorySearchSessionTranscriptIndexing(s, n) : r;
		if (c === void 0) return;
		e.push({
			id: `${i}-memory-session-transcripts`,
			kind: "memorySessionTranscriptIndexing",
			source: s.explicit ? `${t.sourceBase}/memory/search/${s.sourceKey}` : "oc://openclaw.config/memory/search/rememberAcrossConversations",
			scope: "agent",
			agentId: normalizeAgentId(i),
			value: c,
			explicit: s.explicit
		});
	});
}
function memorySearchSessionTranscriptIndexing(e, t = e) {
	const n = e.remember ?? t.remember;
	if (n === void 0 && !e.explicit) return;
	return (e.enabled ?? t.enabled ?? true) && n === true && (e.sessions ?? t.sessions ?? false);
}
function readMemorySessionSettings(e) {
	const t = asNonArrayRecord(e);
	const n = asBoolean(t.enabled);
	const r = asBoolean(t.rememberAcrossConversations);
	const i = r === void 0 ? asBoolean(asNonArrayRecord(t.experimental).sessionMemory) : void 0;
	const a = r ?? i;
	const o = t.sources === void 0 ? void 0 : Array.isArray(t.sources) && t.sources.includes("sessions");
	return {
		enabled: n,
		remember: a,
		sessions: o,
		explicit: n !== void 0 || a !== void 0 || o !== void 0,
		sourceKey: i === void 0 ? "rememberAcrossConversations" : "experimental/sessionMemory"
	};
}
function scanPolicySecretProviders(e) {
	const t = asNonArrayRecord(e.secrets);
	const n = asNonArrayRecord(t.providers);
	return Object.entries(n).map(([e, t]) => {
		const n = {
			id: e,
			kind: "provider",
			source: `oc://openclaw.config/secrets/providers/${ocPathSegment$1(e)}`
		};
		if (isRecord(t) && typeof t.source === "string") n.providerSource = t.source;
		return n;
	});
}
function collectSecretInputs(e, t, n, r) {
	if (Array.isArray(t)) {
		t.forEach((t, i) => collectSecretInputs(e, t, [...n, `#${i}`], r));
		return;
	}
	if (!isRecord(t)) return;
	for (const [i, a] of Object.entries(t)) {
		const t = [...n, i];
		const o = `oc://openclaw.config/${t.map(ocPathSegment$1).join("/")}`;
		const s = isSecretInputPath(t) ? coerceSecretRef(a, r) : null;
		if (s !== null) {
			e.push({
				id: o,
				kind: "input",
				source: o,
				provenance: "secretRef",
				refSource: s.source,
				refProvider: s.provider
			});
			continue;
		}
		collectSecretInputs(e, a, t, r);
	}
}
function isSecretInputPath(e) {
	const t = e.at(-1);
	if (t === void 0) return false;
	if (matchesConfigPath(e, [
		"plugins",
		"entries",
		"acpx",
		"config",
		"mcpServers",
		"*",
		"env",
		"*"
	])) return true;
	if (e.at(-2) === "env") return false;
	if (isSecretInputKey(t)) return true;
	return [
		[
			"models",
			"providers",
			"*",
			"headers",
			"*"
		],
		[
			"memory",
			"search",
			"remote",
			"headers",
			"*"
		],
		[
			"agents",
			"entries",
			"*",
			"memory",
			"search",
			"remote",
			"headers",
			"*"
		],
		[
			"agents",
			"list",
			"#",
			"memory",
			"search",
			"remote",
			"headers",
			"*"
		],
		[
			"diagnostics",
			"otel",
			"headers",
			"*"
		]
	].some((t) => matchesConfigPath(e, t)) || [
		[
			"models",
			"providers",
			"*"
		],
		[
			"tools",
			"media",
			"models",
			"#"
		],
		[
			"tools",
			"media",
			"audio"
		],
		[
			"tools",
			"media",
			"image"
		],
		[
			"tools",
			"media",
			"video"
		]
	].some((t) => isConfiguredProviderRequestSecretPath(e, t));
}
function isConfiguredProviderRequestSecretPath(e, t) {
	if (!matchesConfigPathPrefix(e, t) || e[t.length] !== "request") return false;
	const n = e.slice(t.length + 1);
	if (n.length === 2) return n[0] === "headers" || n[0] === "auth" && (n[1] === "token" || n[1] === "value") || n[0] === "tls" && isConfiguredProviderTlsSecretKey(n[1]);
	return n.length === 3 && n[0] === "proxy" && n[1] === "tls" && isConfiguredProviderTlsSecretKey(n[2]);
}
function matchesConfigPathPrefix(e, t) {
	if (e.length < t.length) return false;
	return t.every((t, n) => {
		const r = e[n];
		if (t === "*") return r !== void 0 && r !== "";
		if (t === "#") return r?.startsWith("#") ?? false;
		return r === t;
	});
}
function matchesConfigPath(e, t) {
	return e.length === t.length && matchesConfigPathPrefix(e, t);
}
function isConfiguredProviderTlsSecretKey(e) {
	return e === "ca" || e === "cert" || e === "key" || e === "passphrase";
}
function isSecretInputKey(e) {
	const t = e.toLowerCase();
	return t === "keyref" || t === "tokenref" || t === "encryptkey" || t === "serviceaccount" || t === "serviceaccountref" || t === "privatekey" || t === "certificate" || t === "certificatedata" || t === "identitydata" || t === "knownhosts" || t === "knownhostsdata" || t.endsWith("apikey") || t.endsWith("token") || t.endsWith("secret") || t.endsWith("password");
}
function secretRefDefaults(e) {
	if (!isRecord(e)) return;
	const t = {};
	for (const n of [
		"env",
		"file",
		"exec",
		"store"
	]) if (typeof e[n] === "string") t[n] = e[n];
	return t;
}
function isValidAuthProfileMetadata(e) {
	if (!isRecord(e)) return false;
	return typeof e.provider === "string" && e.provider.trim() !== "" && isAuthProfileMode(e.mode);
}
function isAuthProfileMode(e) {
	return e === "api_key" || e === "aws-sdk" || e === "oauth" || e === "token";
}
//#endregion
//#region extensions/policy/src/policy-state-exec-approvals.ts
function scanPolicyExecApprovals(e) {
	const t = parseExecApprovalsFile(e);
	if (!t.ok) return [];
	const n = [];
	const r = asNonArrayRecord(t.value.defaults);
	n.push(execApprovalPostureEvidence("defaults", "defaults", r, execApprovalsPolicyUri("defaults")));
	for (const [e, r] of Object.entries(asNonArrayRecord(t.value.agents)).toSorted(([e], [t]) => e.localeCompare(t))) {
		if (!isRecord(r)) continue;
		const t = execApprovalsPolicyUri(`agents/${ocPathSegment$1(e)}`);
		n.push(execApprovalPostureEvidence(`agent:${e}`, "agent", r, t, e));
		if (!Array.isArray(r.allowlist)) continue;
		let i = 0;
		for (const [a, o] of r.allowlist.entries()) {
			if (!isRecord(o)) continue;
			const r = normalizeOptionalString(o.pattern);
			if (r === void 0) continue;
			const s = normalizeOptionalString(o.argPattern);
			const c = normalizeOptionalString(o.source) === "allow-always" ? "allow-always" : void 0;
			n.push({
				id: `agent:${e}:allowlist:${i++}`,
				kind: "allowlist",
				source: `${t}/allowlist/#${a}`,
				agentId: e,
				pattern: r,
				...s === void 0 ? {} : { argPattern: s },
				...c === void 0 ? {} : { entrySource: c }
			});
		}
	}
	return n;
}
function parseExecApprovalsFile(e) {
	try {
		const t = JSON.parse(e);
		if (!isRecord(t) || t.version !== 1) return {
			ok: false,
			message: "unsupported exec approvals version"
		};
		return {
			ok: true,
			value: t
		};
	} catch (e) {
		return {
			ok: false,
			message: e instanceof Error ? e.message : String(e)
		};
	}
}
function execApprovalPostureEvidence(e, t, n, r, i) {
	const a = readExecApprovalSecurity(n.security);
	const o = readExecApprovalAsk(n.ask);
	const s = readExecApprovalSecurity(n.askFallback);
	const c = asBoolean(n.autoAllowSkills);
	return {
		id: e,
		kind: t,
		source: r,
		...i === void 0 ? {} : { agentId: i },
		...n.security == null ? {} : { securityConfigured: true },
		...a === void 0 ? {} : { security: a },
		...o === void 0 ? {} : { ask: o },
		...s === void 0 ? {} : { askFallback: s },
		...c === void 0 ? {} : { autoAllowSkills: c }
	};
}
function readExecApprovalSecurity(e) {
	const t = normalizeOptionalString(e);
	return t === "deny" || t === "allowlist" || t === "full" ? t : void 0;
}
function readExecApprovalAsk(e) {
	const t = normalizeOptionalString(e);
	return t === "off" || t === "on-miss" || t === "always" ? t : void 0;
}
//#endregion
//#region extensions/policy/src/policy-state-gateway.ts
function scanPolicyGatewayExposure(e) {
	const t = asNonArrayRecord(e.gateway);
	const n = [];
	const r = typeof t.bind === "string" ? t.bind : void 0;
	const i = typeof t.customBindHost === "string" ? t.customBindHost : void 0;
	const a = i !== void 0 && i.trim() !== "";
	const o = asNonArrayRecord(t.tailscale);
	const s = o.mode === "serve" || o.mode === "funnel";
	n.push({
		id: r === void 0 ? "gateway-bind-default" : "gateway-bind",
		kind: "bind",
		source: "oc://openclaw.config/gateway/bind",
		value: r ?? (s ? "loopback" : "runtime-default"),
		nonLoopback: r === void 0 ? !s : r === "custom" ? false : isGatewayNonLoopbackBind(r),
		explicit: r !== void 0
	});
	if (r === "custom" && a) n.push({
		id: "gateway-custom-bind-host",
		kind: "bind",
		source: "oc://openclaw.config/gateway/customBindHost",
		value: i,
		nonLoopback: isRuntimeNonLoopbackCustomBindHost(i)
	});
	const c = asNonArrayRecord(t.auth);
	n.push({
		id: "gateway-auth-mode",
		kind: "auth",
		source: "oc://openclaw.config/gateway/auth/mode",
		value: typeof c.mode === "string" ? c.mode : "token",
		explicit: typeof c.mode === "string"
	});
	n.push({
		id: "gateway-auth-rate-limit",
		kind: "authRateLimit",
		source: "oc://openclaw.config/gateway/auth/rateLimit",
		value: isRecord(c.rateLimit),
		explicit: isRecord(c.rateLimit)
	});
	const l = asNonArrayRecord(t.controlUi);
	for (const [e, t, r] of [
		[
			"enabled",
			l.enabled,
			"oc://openclaw.config/gateway/controlUi/enabled"
		],
		[
			"insecure-auth",
			false,
			"oc://openclaw.invariant/gateway/controlUi/deviceIdentity"
		],
		[
			"device-auth-disabled",
			false,
			"oc://openclaw.invariant/gateway/controlUi/deviceIdentity"
		],
		[
			"host-origin-fallback",
			l.dangerouslyAllowHostHeaderOriginFallback,
			"oc://openclaw.config/gateway/controlUi/dangerouslyAllowHostHeaderOriginFallback"
		]
	]) if (typeof t === "boolean") n.push({
		id: `gateway-control-ui-${e}`,
		kind: "controlUi",
		source: r,
		value: t
	});
	if (typeof o.mode === "string") n.push({
		id: "gateway-tailscale-mode",
		kind: "tailscale",
		source: "oc://openclaw.config/gateway/tailscale/mode",
		value: o.mode
	});
	if (o.mode === "serve" && o.preserveFunnel === true) n.push({
		id: "gateway-tailscale-preserve-funnel",
		kind: "tailscale",
		source: "oc://openclaw.config/gateway/tailscale/preserveFunnel",
		value: "funnel"
	});
	const u = asNonArrayRecord(t.remote);
	if (t.mode === "remote") {
		n.push({
			id: "gateway-mode-remote",
			kind: "remote",
			source: "oc://openclaw.config/gateway/mode",
			value: "remote"
		});
		if (typeof u.url === "string" && u.url.trim() !== "") n.push({
			id: "gateway-remote-url",
			kind: "remote",
			source: "oc://openclaw.config/gateway/remote/url",
			value: true
		});
	}
	const d = asNonArrayRecord(t.http);
	const f = asNonArrayRecord(d.endpoints);
	pushGatewayHttpEndpointEvidence(n, f, "chatCompletions");
	pushGatewayHttpEndpointEvidence(n, f, "responses");
	pushGatewayNodeCommandEvidence(n, asNonArrayRecord(t.nodes));
	return n.toSorted((e, t) => e.source.localeCompare(t.source));
}
function pushGatewayHttpEndpointEvidence(e, t, n) {
	const r = t[n];
	if (!isRecord(r) || r.enabled !== true) return;
	const i = `oc://openclaw.config/gateway/http/endpoints/${n}`;
	e.push({
		id: `gateway-http-${n}`,
		kind: "httpEndpoint",
		source: `${i}/enabled`,
		value: true,
		endpoint: n
	});
	for (const t of n === "chatCompletions" ? ["images"] : ["files", "images"]) pushGatewayHttpUrlFetchEvidence(e, i, n, t, r[t]);
}
function pushGatewayHttpUrlFetchEvidence(e, t, n, r, i) {
	const a = isRecord(i) ? i.allowUrl : void 0;
	if (a === false || a !== true && n !== "responses") return;
	const o = isRecord(i) ? i.urlAllowlist : void 0;
	const s = Array.isArray(o) && o.some((e) => isEffectiveGatewayUrlAllowlistEntry(e));
	e.push({
		id: `gateway-http-${n}-${r}-url-fetch`,
		kind: "httpUrlFetch",
		source: `${t}/${ocPathSegment$1(r)}/allowUrl`,
		value: true,
		endpoint: n,
		explicit: a === true,
		hasAllowlist: s
	});
}
function pushGatewayNodeCommandEvidence(e, t) {
	const n = isRecord(t.commands) ? t.commands : null;
	const r = /* @__PURE__ */ new Set();
	for (const [t, i, a] of [[
		"deny",
		"nodeDenyCommand",
		"gateway-node-deny-command"
	], [
		"allow",
		"nodeCommand",
		"gateway-node-command"
	]]) {
		const o = n?.[t];
		if (!Array.isArray(o)) continue;
		o.forEach((n, o) => {
			if (typeof n !== "string") return;
			const s = n.trim();
			if (s === "" || t === "allow" && r.has(s)) return;
			if (t === "deny") r.add(s);
			e.push({
				id: `${a}-${s}`,
				kind: i,
				source: `oc://openclaw.config/gateway/nodes/commands/${t}/#${o}`,
				value: s,
				command: s
			});
		});
	}
}
function isEffectiveGatewayUrlAllowlistEntry(e) {
	if (typeof e !== "string") return false;
	const t = e.trim().toLowerCase();
	return t !== "" && t !== "*" && t !== "*.";
}
function isGatewayNonLoopbackBind(e) {
	return e === "auto" || e === "lan" || e === "tailnet";
}
function isRuntimeNonLoopbackCustomBindHost(e) {
	const t = e.trim().toLowerCase();
	return isCanonicalDottedDecimalIPv4(t) && !t.startsWith("127.");
}
function isCanonicalDottedDecimalIPv4(e) {
	return /^(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}$/.test(e);
}
//#endregion
//#region extensions/policy/src/policy-state-tool-posture.ts
function scanPolicyToolPosture(e) {
	const t = [];
	for (const n of collectPolicyAgentContexts(e, "global")) {
		pushToolPostureValue({
			suffix: "profile",
			kind: "profile",
			...resolvePolicyValue(normalizeOptionalString(n.tools.profile), normalizeOptionalString(n.inheritedTools.profile), "full")
		});
		for (const e of [
			"allow",
			"alsoAllow",
			"deny"
		]) {
			const t = n.tools[e];
			const r = n.inheritedTools[e];
			const i = readStringArray(t);
			const a = readStringArray(r);
			const o = e === "alsoAllow";
			const s = o ? Array.isArray(t) : i.length > 0;
			const c = o ? Array.isArray(r) : a.length > 0;
			const l = !s && c;
			pushToolPostureValue({
				suffix: e,
				kind: e,
				inherited: l,
				entries: o ? l ? a : i : [...a, ...i],
				explicit: s || c
			});
		}
		const e = asNonArrayRecord(n.tools.fs);
		const r = asNonArrayRecord(n.inheritedTools.fs);
		pushToolPostureValue({
			suffix: "fs/workspaceOnly",
			kind: "fsWorkspaceOnly",
			...resolvePolicyValue(asBoolean(e.workspaceOnly), asBoolean(r.workspaceOnly), false)
		});
		const i = asNonArrayRecord(n.tools.exec);
		const a = asNonArrayRecord(n.inheritedTools.exec);
		const o = resolvePolicyValue(normalizeOptionalString(i.host), normalizeOptionalString(a.host), "auto");
		const s = o.value;
		pushToolPostureValue({
			suffix: "exec/host",
			kind: "execHost",
			...o
		});
		const c = normalizeOptionalString(i.security);
		const l = normalizeOptionalString(a.security);
		const u = normalizeOptionalString(i.ask);
		const d = normalizeOptionalString(a.ask);
		const f = readExecMode(i.mode);
		const p = readExecMode(a.mode);
		const m = (normalizeOptionalString(n.sandbox.mode) ?? normalizeOptionalString(n.inheritedSandbox.mode)) === "all";
		const h = s === "sandbox" || s === "auto" && m ? "deny" : "full";
		const g = f === void 0 ? p === void 0 ? void 0 : {
			value: p,
			inherited: true
		} : {
			value: f,
			inherited: false
		};
		const _ = g === void 0 ? void 0 : {
			...g,
			...resolveExecModePolicy({
				mode: g.value,
				security: "full",
				ask: "off"
			})
		};
		for (const [e, t, n, r, i] of [[
			"security",
			"execSecurity",
			c,
			l,
			h
		], [
			"ask",
			"execAsk",
			u,
			d,
			"off"
		]]) {
			const a = _?.inherited === false || n === void 0 && _?.inherited === true;
			pushToolPostureValue({
				suffix: `exec/${e}`,
				sourceSuffix: a ? "exec/mode" : void 0,
				kind: t,
				value: _?.inherited === false ? _[e] : n ?? _?.[e] ?? r ?? i,
				explicit: _ !== void 0 || n !== void 0 || r !== void 0,
				inherited: _?.inherited === true ? n === void 0 : n === void 0 && r !== void 0
			});
		}
		const v = asNonArrayRecord(n.tools.elevated);
		const y = asNonArrayRecord(n.inheritedTools.elevated);
		const b = asBoolean(v.enabled);
		const x = asBoolean(y.enabled);
		pushToolPostureValue({
			suffix: "elevated/enabled",
			kind: "elevatedEnabled",
			value: x === false ? false : b ?? x ?? true,
			explicit: b !== void 0 || x !== void 0,
			inherited: x === false && b !== false || b === void 0 && x !== void 0
		});
		const S = asNonArrayRecord(v.allowFrom);
		const C = asNonArrayRecord(y.allowFrom);
		const w = [.../* @__PURE__ */ new Set([...Object.keys(C), ...Object.keys(S)])].toSorted((e, t) => e.localeCompare(t));
		for (const e of w) {
			const r = readStringOrNumberArray(S[e]);
			const i = readStringOrNumberArray(C[e]);
			const a = r.length === 0 && i.length > 0;
			t.push({
				id: `${n.id}-elevated-allow-from-${ocPathSegment$1(e)}`,
				kind: "elevatedAllowFrom",
				source: `${a ? "oc://openclaw.config/tools" : n.toolsSourceBase}/elevated/allowFrom/${ocPathSegment$1(e)}`,
				scope: n.scope,
				...n.agentId === void 0 ? {} : { agentId: n.agentId },
				entries: r.length > 0 ? r : i,
				explicit: r.length > 0 || i.length > 0
			});
		}
		function pushToolPostureValue(e) {
			const { suffix: r, sourceSuffix: i = r, inherited: a, value: o, ...s } = e;
			t.push({
				id: `${n.id}-${r.replaceAll("/", "-")}`,
				source: `${a ? "oc://openclaw.config/tools" : n.toolsSourceBase}/${i}`,
				scope: n.scope,
				...n.agentId === void 0 ? {} : { agentId: n.agentId },
				...o === void 0 ? {} : { value: o },
				...s
			});
		}
	}
	return t.toSorted((e, t) => e.source.localeCompare(t.source) || e.id.localeCompare(t.id));
}
function readExecMode(e) {
	const t = normalizeOptionalString(e)?.toLowerCase();
	switch (t) {
		case "deny":
		case "allowlist":
		case "ask":
		case "auto":
		case "full": return t;
		default: return;
	}
}
const AGENT_WORKSPACE_POLICY_TOOLS = [
	"exec",
	"process",
	"write",
	"edit",
	"apply_patch"
];
const IMPLICIT_DEFAULT_ACCOUNT_FIELDS = {
	discord: ["token"],
	googlechat: ["serviceAccount", "serviceAccountFile"],
	imessage: ["cliPath", "dbPath"],
	"qa-channel": ["baseUrl"],
	qqbot: [
		"appId",
		"clientSecret",
		"clientSecretFile"
	],
	signal: ["account"],
	slack: [
		"appToken",
		"botToken",
		"signingSecret"
	],
	"synology-chat": ["token"],
	telegram: ["botToken", "tokenFile"],
	tlon: ["ship"],
	twitch: ["username"],
	whatsapp: ["authDir"],
	zalo: ["botToken", "tokenFile"],
	zalouser: ["profile"]
};
function readStringArray(e) {
	if (!Array.isArray(e)) return [];
	return e.filter((e) => typeof e === "string" && e.trim() !== "");
}
function readStringOrNumberArray(e) {
	if (!Array.isArray(e)) return [];
	const t = [];
	for (const n of e) if (typeof n === "string" && n.trim() !== "") t.push(n.trim());
	else if (typeof n === "number" && Number.isFinite(n)) t.push(String(n));
	return t;
}
//#endregion
//#region extensions/policy/src/policy-state-types.ts
const RESERVED_CHANNEL_CONFIG_KEYS = /* @__PURE__ */ new Set(["defaults", "modelByChannel"]);
//#endregion
//#region extensions/policy/src/policy-state-ingress.ts
const ALLOWLIST_DEFAULT_INGRESS_GROUP_POLICY_CHANNELS = /* @__PURE__ */ new Set([
	"googlechat",
	"irc",
	"line",
	"mattermost",
	"matrix",
	"msteams",
	"nextcloud-talk",
	"signal"
]);
const OPEN_GROUPS_DEFAULT_TO_NO_MENTION_CHANNELS = /* @__PURE__ */ new Set(["feishu", "qa-channel"]);
function scanPolicyIngress(e) {
	const t = asNonArrayRecord(e.channels);
	const n = asNonArrayRecord(t.defaults);
	const r = n.groupPolicy === void 0 ? {} : { groupPolicy: n.groupPolicy };
	const i = "oc://openclaw.config/channels/defaults";
	const a = [];
	const o = asNonArrayRecord(e.session);
	const s = normalizeOptionalString(o.dmScope)?.toLowerCase();
	a.push({
		id: "session-dm-scope",
		kind: "sessionDmScope",
		source: "oc://openclaw.config/session/dmScope",
		value: s ?? "main",
		explicit: s !== void 0
	});
	for (const [e, n] of Object.entries(t)) {
		if (RESERVED_CHANNEL_CONFIG_KEYS.has(e) || !isRecord(n) || n.enabled === false) continue;
		const t = `oc://openclaw.config/channels/${ocPathSegment$1(e)}`;
		const o = asNonArrayRecord(n.accounts);
		const s = Object.entries(o).filter((e) => isRecord(e[1]));
		const c = s.filter(([, e]) => e.enabled !== false);
		if (s.length === 0 || hasImplicitDefaultAccountConfig(e, n)) pushChannelIngress(a, {
			channel: e,
			config: n,
			inheritedConfig: r,
			sourceBase: t,
			inheritedSourceBase: i,
			fallbackSourceBase: t
		});
		for (const [o, l] of c) pushChannelIngress(a, {
			channel: e,
			accountId: o,
			config: l,
			inheritedConfig: n,
			inheritNestedContainers: true,
			inheritEmptyNestedContainers: e === "telegram" && s.length <= 1,
			sourceBase: `${t}/accounts/${ocPathSegment$1(o)}`,
			inheritedSourceBase: t,
			fallbackConfig: r,
			fallbackSourceBase: i
		});
	}
	return a.toSorted((e, t) => e.source.localeCompare(t.source) || e.id.localeCompare(t.id));
}
function hasImplicitDefaultAccountConfig(e, t) {
	return (IMPLICIT_ACCOUNT_REQUIREMENTS[e] ?? (IMPLICIT_DEFAULT_ACCOUNT_FIELDS[e] ?? []).map((e) => [e])).some((e) => e.every((e) => hasConfiguredAccountValue(t[e])));
}
const IMPLICIT_ACCOUNT_REQUIREMENTS = {
	clickclack: [[
		"baseUrl",
		"workspace",
		"token"
	]],
	feishu: [["appId", "appSecret"]],
	irc: [["host", "nick"]],
	line: [["channelAccessToken"], ["tokenFile"]],
	matrix: [["homeserver", "accessToken"], [
		"homeserver",
		"userId",
		"password"
	]],
	mattermost: [["baseUrl", "botToken"]],
	"nextcloud-talk": [["baseUrl", "botSecret"], ["baseUrl", "botSecretFile"]]
};
function pushChannelIngress(e, t) {
	const n = channelDmPolicy(t.config, t.sourceBase) ?? channelDmPolicy(t.inheritedConfig, t.inheritedSourceBase) ?? channelDmPolicy(t.fallbackConfig ?? {}, t.fallbackSourceBase);
	e.push({
		id: channelIngressId(t, "dm-policy"),
		kind: "channelDmPolicy",
		source: n?.source ?? `${t.fallbackSourceBase}/dmPolicy`,
		channel: t.channel,
		...t.accountId === void 0 ? {} : { accountId: t.accountId },
		value: n?.value ?? "pairing",
		explicit: n !== void 0
	});
	const r = channelIngressValue(t, "groupPolicy", normalizeOptionalString);
	const i = channelImplicitGroupPolicy(t);
	const a = r ?? i;
	e.push({
		id: channelIngressId(t, "group-policy"),
		kind: "channelGroupPolicy",
		source: a.source,
		channel: t.channel,
		...t.accountId === void 0 ? {} : { accountId: t.accountId },
		value: a.value,
		explicit: r !== void 0
	});
	pushChannelRequireMentionIngress(e, t, a.value);
}
function channelIngressValue(e, t, n) {
	for (const [r, i] of [
		[e.config, e.sourceBase],
		[e.inheritedConfig, e.inheritedSourceBase],
		[e.fallbackConfig, e.fallbackSourceBase]
	]) {
		const e = n(r?.[t]);
		if (e !== void 0) return {
			value: e,
			source: `${i}/${t}`
		};
	}
}
function channelImplicitGroupPolicy(e) {
	const t = effectiveNestedIngressContainer(e, "groups");
	if (t !== void 0) return {
		source: `${t.sourceBase}/groups`,
		value: "allowlist"
	};
	const n = isRecord(e.fallbackConfig?.groups) ? e.fallbackConfig.groups : void 0;
	if (n !== void 0 && Object.keys(n).length > 0) return {
		source: `${e.fallbackSourceBase}/groups`,
		value: "allowlist"
	};
	return {
		source: `${e.sourceBase}/groupPolicy`,
		value: ALLOWLIST_DEFAULT_INGRESS_GROUP_POLICY_CHANNELS.has(e.channel) ? "allowlist" : "open"
	};
}
function pushChannelRequireMentionIngress(e, t, n) {
	const r = channelWildcardRequireMention(t) ?? channelIngressValue(t, "requireMention", asBoolean);
	const i = !(n === "open" && OPEN_GROUPS_DEFAULT_TO_NO_MENTION_CHANNELS.has(t.channel));
	e.push({
		id: channelIngressId(t, "require-mention"),
		kind: "channelRequireMention",
		source: r?.source ?? `${t.sourceBase}/requireMention`,
		channel: t.channel,
		...t.accountId === void 0 ? {} : { accountId: t.accountId },
		value: r?.value ?? i,
		explicit: r !== void 0
	});
	for (const n of [
		"groups",
		"guilds",
		"channels",
		"rooms",
		"teams"
	]) {
		const r = effectiveNestedIngressContainer(t, n);
		if (r === void 0) continue;
		const { container: i, sourceBase: a } = r;
		for (const [r, o] of Object.entries(i)) {
			if (!isRecord(o)) continue;
			pushNestedRequireMentionIngress(e, t, n, r, o, a);
		}
	}
}
function channelWildcardRequireMention(e) {
	for (const t of [
		"groups",
		"guilds",
		"channels",
		"rooms",
		"teams"
	]) {
		const n = effectiveNestedIngressContainer(e, t);
		const r = {
			container: asNonArrayRecord(e.fallbackConfig?.[t]),
			sourceBase: e.fallbackSourceBase
		};
		for (const e of [n, r]) {
			const n = e?.container["*"];
			if (!isRecord(n) || n.enabled === false) continue;
			const r = asBoolean(n.requireMention);
			if (r !== void 0 && e !== void 0) return {
				source: `${e.sourceBase}/${t}/${ocPathSegment$1("*")}/requireMention`,
				value: r
			};
		}
	}
}
function effectiveNestedIngressContainer(e, t) {
	const n = isRecord(e.config[t]) ? e.config[t] : void 0;
	const r = isRecord(e.inheritedConfig[t]) ? e.inheritedConfig[t] : void 0;
	if (n !== void 0 && Object.keys(n).length > 0) return {
		container: n,
		sourceBase: e.sourceBase
	};
	const i = n !== void 0 && e.inheritEmptyNestedContainers === true;
	const a = n === void 0 && e.inheritNestedContainers === true;
	if ((i || a) && r !== void 0) return {
		container: r,
		sourceBase: e.inheritedSourceBase
	};
}
function pushNestedRequireMentionIngress(e, t, n, r, i, a) {
	if (i.enabled === false) return;
	const o = `${a}/${n}/${ocPathSegment$1(r)}`;
	const s = asBoolean(i.requireMention);
	if (s !== void 0) e.push({
		id: `${channelIngressId(t, `${n}-${ocPathSegment$1(r)}`)}-require-mention`,
		kind: "channelRequireMention",
		source: `${o}/requireMention`,
		channel: t.channel,
		...t.accountId === void 0 ? {} : { accountId: t.accountId },
		groupId: r,
		value: s,
		explicit: true
	});
	for (const o of ["channels", "topics"]) {
		const s = i[o];
		if (!isRecord(s)) continue;
		for (const [i, c] of Object.entries(s)) if (isRecord(c)) pushNestedRequireMentionIngress(e, t, `${n}/${ocPathSegment$1(r)}/${o}`, i, c, a);
	}
}
function channelDmPolicy(e, t) {
	const n = asNonArrayRecord(e.dm);
	if (n.enabled === false) return {
		value: "disabled",
		source: `${t}/dm/enabled`
	};
	const r = normalizeOptionalString(e.dmPolicy);
	if (r !== void 0) return {
		value: r,
		source: `${t}/dmPolicy`
	};
	const i = normalizeOptionalString(n.policy);
	return i === void 0 ? void 0 : {
		value: i,
		source: `${t}/dm/policy`
	};
}
function channelIngressId(e, t) {
	return e.accountId === void 0 ? `${e.channel}-${t}` : `${e.channel}-${e.accountId}-${t}`;
}
//#endregion
//#region extensions/policy/src/policy-state-sandbox.ts
const DEFAULT_POLICY_SANDBOX_BROWSER_NETWORK = "openclaw-sandbox-browser";
function scanPolicySandboxPosture(e) {
	const t = [];
	for (const n of collectPolicyAgentContexts(e, "defaults")) {
		const e = n.scope === "agent" && (normalizeOptionalString(n.sandbox.scope) ?? normalizeOptionalString(n.inheritedSandbox.scope)) === "shared";
		const r = `${n.workspaceSourceBase}/sandbox`;
		pushSandboxPostureValue({
			suffix: "mode",
			kind: "mode",
			...resolvePolicyValue(normalizeOptionalString(n.sandbox.mode), normalizeOptionalString(n.inheritedSandbox.mode), "off")
		});
		const i = resolvePolicyValue(normalizeOptionalString(n.sandbox.backend), normalizeOptionalString(n.inheritedSandbox.backend), "docker");
		const a = i.value.toLowerCase();
		pushSandboxPostureValue({
			suffix: "backend",
			kind: "backend",
			...i,
			value: a
		});
		if (a === "docker" || a === "podman") {
			const t = !e ? asNonArrayRecord(n.sandbox.docker) : {};
			const r = asNonArrayRecord(n.inheritedSandbox.docker);
			pushSandboxPostureValue({
				suffix: "docker/network",
				kind: "containerNetwork",
				...resolvePolicyValue(normalizeOptionalString(t.network), normalizeOptionalString(r.network), "none"),
				networkSurface: "docker"
			});
			for (const e of ["seccomp", "apparmor"]) {
				const n = `${e}Profile`;
				const i = normalizeOptionalString(t[n]);
				const a = normalizeOptionalString(r[n]);
				const o = i === void 0 && a !== void 0;
				const s = i ?? a;
				pushSandboxPostureValue({
					suffix: `docker/${e}/profile`,
					sourceSuffix: `docker/${n}`,
					kind: "containerSecurityProfile",
					inherited: o,
					profile: e,
					value: s,
					explicit: s !== void 0
				});
			}
			pushSandboxBindPosture("docker");
		}
		function pushSandboxBindPosture(t, r = t) {
			const i = !e ? asNonArrayRecord(n.sandbox[r]) : {};
			const a = asNonArrayRecord(n.inheritedSandbox[r]);
			const o = readStringArray(a.binds);
			const s = readStringArray(i.binds);
			for (const [e, n] of [...o, ...s].entries()) {
				const i = e < o.length;
				const a = splitSandboxBindSpec(n, { allowWindowsContainerPath: true });
				const s = a?.options.split(",").some((e) => e.trim().toLowerCase() === "ro") ? "ro" : "rw";
				pushSandboxPostureValue({
					suffix: `${t}/bind/${e}`,
					kind: "containerMount",
					sourceSuffix: `${r}/binds/#${i ? e : e - o.length}`,
					inherited: i,
					bind: n,
					bindHost: a?.host,
					bindMode: s,
					bindSurface: t,
					explicit: true
				});
			}
		}
		const o = !e ? asNonArrayRecord(n.sandbox.browser) : {};
		const s = asNonArrayRecord(n.inheritedSandbox.browser);
		const c = asBoolean(o.enabled);
		const l = asBoolean(s.enabled);
		const u = c ?? l ?? false;
		if (!u && c === void 0 && l === void 0) continue;
		const d = Object.hasOwn(o, "cdpSourceRange");
		const f = normalizeOptionalString(o.cdpSourceRange);
		const p = normalizeOptionalString(s.cdpSourceRange);
		const m = u ? !d && p !== void 0 : c === void 0 && l !== void 0;
		const h = u ? d ? f : p : false;
		pushSandboxPostureValue({
			suffix: "browser/cdp-source-range",
			sourceSuffix: `browser/${u ? "cdpSourceRange" : "enabled"}`,
			kind: "browserCdpSourceRange",
			inherited: m,
			value: h,
			explicit: h !== void 0
		});
		if (!u) continue;
		pushSandboxPostureValue({
			suffix: "browser/network",
			kind: "containerNetwork",
			...resolvePolicyValue(normalizeOptionalString(o.network), normalizeOptionalString(s.network), DEFAULT_POLICY_SANDBOX_BROWSER_NETWORK),
			networkSurface: "browser"
		});
		if (s.binds !== void 0 || o.binds !== void 0) pushSandboxBindPosture("browser");
		else if (a !== "docker" && a !== "podman") pushSandboxBindPosture("browser", "docker");
		function pushSandboxPostureValue(e) {
			const { suffix: i, sourceSuffix: a = i, inherited: o, value: s, ...c } = e;
			t.push({
				id: `${n.id}-${i.replaceAll("/", "-")}`,
				source: `${o ? "oc://openclaw.config/agents/defaults/sandbox" : r}/${a}`,
				scope: n.scope,
				...n.agentId === void 0 ? {} : { agentId: n.agentId },
				...s === void 0 ? {} : { value: s },
				...c
			});
		}
	}
	return t.toSorted((e, t) => e.source.localeCompare(t.source) || e.id.localeCompare(t.id));
}
//#endregion
//#region extensions/policy/src/policy-state-tools.ts
function scanPolicyTools(e) {
	const t = markdownSectionLines(e);
	if (t.length === 0) return [];
	const n = [];
	let r;
	for (let e = 0; e < t.length; e += 1) {
		const i = t[e];
		const a = i?.text ?? "";
		const o = /^(#{1,6})\s+(.+?)\s*#*\s*$/u.exec(a);
		const s = o?.[1]?.length === (i?.sectionDepth ?? 0) + 1;
		if (a.includes("Skills provide your tools.") && a.includes("Keep local notes") && a.includes("TOOLS.md")) {
			r = "plain";
			continue;
		}
		if (s && /^Local notes\s*$/iu.test(o?.[2] ?? "")) {
			r = "plain";
			continue;
		}
		if (s && /^Local notes \(migrated from TOOLS\.md\)\s*$/iu.test(o?.[2] ?? "")) {
			r = "migrated";
			continue;
		}
		if (r && o && o[1].length <= (t[e]?.sectionDepth ?? 0) && slugify(o[2] ?? "") === "tools") {
			r = void 0;
			continue;
		}
		if (r === "plain" && s) r = void 0;
		if (r) continue;
		const c = s ? /^([^\s#]+)(.*)$/u.exec(o?.[2] ?? "") : null;
		const l = /^[-*+]\s+([^:\s][^:]*?)\s*:(.*)$/.exec(a);
		const u = c ?? l;
		const d = u?.[1];
		if (!d) continue;
		const f = slugify(d);
		if (!f) continue;
		const p = [u[2] ?? ""];
		for (let n = e + 1; n < t.length; n += 1) {
			const e = t[n];
			const r = e?.text ?? "";
			const i = /^(#{1,6})\s+(.+?)\s*#*\s*$/u.exec(r.trim());
			if (i !== null && (i[1]?.length ?? 0) <= (e?.sectionDepth ?? 0) + 1 || /^[-*+]\s+[^:\s][^:]*?\s*:/.test(r)) break;
			p.push(r);
		}
		const m = p.join("\n");
		const h = riskFromMeta(m);
		const g = /\bsensitivity\s*:\s*([a-z0-9_-]+)\b/i.exec(m)?.[1]?.toLowerCase();
		const _ = /\bowner\s*:\s*([^\s#]+)\b/i.exec(m)?.[1];
		const v = capabilityTokensFromMetaLines(p);
		n.push({
			id: f,
			source: `oc://AGENTS.md/tools/${f}`,
			line: t[e]?.line ?? e + 1,
			...h === void 0 ? {} : { risk: h },
			...g === void 0 ? {} : { sensitivity: g },
			..._ === void 0 ? {} : { owner: _ },
			...v.length === 0 ? {} : { capabilities: v }
		});
	}
	return n;
}
function markdownSectionLines(e) {
	const t = e.split(/\r?\n/);
	let n;
	let r = false;
	let i;
	const a = [];
	for (let e = 0; e < t.length; e += 1) {
		const o = t[e] ?? "";
		const s = /^\s*(`{3,}|~{3,})/.exec(o)?.[1];
		const c = /^\s*(`{3,}|~{3,})\s*$/.exec(o)?.[1];
		const l = s?.[0];
		if (l && !i) {
			i = {
				marker: l,
				length: s.length
			};
			continue;
		}
		if (c && i && c[0] === i.marker && c.length >= i.length) {
			i = void 0;
			continue;
		}
		if (i) continue;
		const u = /^(#{1,6})\s+(.+?)\s*#*\s*$/.exec(o);
		if (u !== null) {
			const t = u[1]?.length ?? 0;
			const i = slugify(u[2] ?? "");
			if (n !== void 0 && t <= n) n = void 0;
			if (n !== void 0) {
				a.push({
					line: e + 1,
					text: o,
					sectionDepth: n
				});
				continue;
			}
			if (t <= 2 && i === "tools") {
				if (r) a.push({
					line: e + 1,
					text: o,
					sectionDepth: t
				});
				r = true;
				n = t;
			}
			continue;
		}
		if (n !== void 0) a.push({
			line: e + 1,
			text: o,
			sectionDepth: n
		});
	}
	return a;
}
function slugify(e) {
	return e.toLowerCase().replace(/_/g, "-").replace(/[^a-z0-9-]+/g, "-").replace(/-+/g, "-").replace(/^-+|-+$/g, "");
}
function riskFromMeta(e) {
	const t = /\brisk\s*:\s*([a-z0-9_-]+)\b/i.exec(e)?.[1];
	if (t !== void 0) return t.toLowerCase();
	const n = /\bR([0-5])\b/.exec(e)?.[1];
	return n === void 0 ? void 0 : [
		"low",
		"low",
		"medium",
		"medium",
		"high",
		"critical"
	][Number(n)];
}
function capabilityTokensFromMetaLines(e) {
	return e.flatMap((e, t) => {
		const n = e.trim();
		if (n.length === 0) return [];
		const r = n.match(/\b[A-Z][A-Z0-9_]{2,}\b/g) ?? [];
		if (t === 0 || /\bcapabilities\s*:/i.test(n)) return r;
		const i = r.reduce((e, t) => {
			return e.replace(t, "");
		}, n);
		return /^[\s,;:[\](){}#*_-]*$/.test(i) ? r : [];
	});
}
//#endregion
//#region extensions/policy/src/tool-policy-conformance.ts
function toolListCoversTool(e, t) {
	return !toolPolicy.createToolPolicyMatcher({ deny: [...e] })(t);
}
function expandPolicyToolRequirement(e) {
	return toolPolicy.expandToolGroups([e]);
}
//#endregion
//#region extensions/policy/src/policy-state-attestation.ts
function policyDocumentHash(e) {
	return `sha256:${createHash("sha256").update(stableJson(e)).digest("hex")}`;
}
function createPolicyAttestation(e) {
	const t = policyDocumentHash(e.evidence);
	const n = policyDocumentHash(e.findings);
	return {
		checkedAt: e.checkedAt,
		...e.policyHash === void 0 ? {} : { policy: {
			path: e.policyPath,
			hash: e.policyHash
		} },
		workspace: {
			scope: "policy",
			hash: t
		},
		findingsHash: n,
		attestationHash: policyDocumentHash({
			ok: e.ok,
			policyHash: e.policyHash,
			workspaceHash: t,
			findingsHash: n
		})
	};
}
function stableJson(e) {
	if (Array.isArray(e)) return `[${e.map(stableJson).join(",")}]`;
	if (isRecord(e)) return `{${Object.entries(e).toSorted(([e], [t]) => e.localeCompare(t)).map(([e, t]) => `${JSON.stringify(e)}:${stableJson(t)}`).join(",")}}`;
	return JSON.stringify(e);
}
//#endregion
//#region extensions/policy/src/policy-state.ts
function scanPolicyAgentWorkspace(e) {
	const t = [];
	for (const n of collectPolicyAgentContexts(e, "defaults")) {
		const e = normalizeOptionalString(n.sandbox.mode);
		const r = normalizeOptionalString(n.inheritedSandbox.mode);
		const i = e ?? r ?? "off";
		const a = i === "all";
		const o = e !== void 0 ? `${n.workspaceSourceBase}/sandbox/mode` : "oc://openclaw.config/agents/defaults/sandbox/mode";
		const s = normalizeOptionalString(n.sandbox.workspaceAccess);
		const c = normalizeOptionalString(n.inheritedSandbox.workspaceAccess);
		t.push({
			id: `${n.id}-workspace-access`,
			kind: "workspaceAccess",
			source: s !== void 0 ? `${n.workspaceSourceBase}/sandbox/workspaceAccess` : "oc://openclaw.config/agents/defaults/sandbox/workspaceAccess",
			scope: n.scope,
			...n.agentId === void 0 ? {} : { agentId: n.agentId },
			value: s ?? c ?? "none",
			sandboxMode: i,
			sandboxModeSource: o,
			sandboxEnabled: a,
			explicit: s !== void 0
		});
		const l = configuredSandboxToolDenyEntries(n.tools);
		const u = configuredSandboxToolDenyEntries(n.inheritedTools);
		const d = [
			{
				entries: readStringArray(n.tools.deny),
				source: `${n.toolsSourceBase}/deny`
			},
			{
				entries: readStringArray(n.inheritedTools.deny),
				source: "oc://openclaw.config/tools/deny"
			},
			...a ? [l !== void 0 ? {
				entries: l,
				source: `${n.toolsSourceBase}/sandbox/tools/deny`
			} : {
				entries: u ?? [],
				source: "oc://openclaw.config/tools/sandbox/tools/deny"
			}] : []
		];
		for (const e of AGENT_WORKSPACE_POLICY_TOOLS) {
			const r = d.find((t) => toolListCoversTool(t.entries, e));
			t.push({
				id: `${n.id}-tool-${e}`,
				kind: "toolDeny",
				source: r?.source ?? `${n.toolsSourceBase}/deny`,
				scope: n.scope,
				...n.agentId === void 0 ? {} : { agentId: n.agentId },
				tool: e,
				denied: r !== void 0,
				explicit: r !== void 0
			});
		}
	}
	return t.toSorted((e, t) => e.source.localeCompare(t.source) || e.id.localeCompare(t.id));
}
function configuredSandboxToolDenyEntries(e) {
	const t = asNonArrayRecord(e.sandbox);
	const n = asNonArrayRecord(t.tools);
	return Array.isArray(n.deny) ? readStringArray(n.deny) : void 0;
}
function collectPolicyEvidence(e, t = {}) {
	const n = Object.entries(asNonArrayRecord(e.channels)).filter(([e]) => !RESERVED_CHANNEL_CONFIG_KEYS.has(e)).toSorted(([e], [t]) => e.localeCompare(t)).map(([e, t]) => {
		const n = {
			id: e,
			provider: e,
			source: `oc://openclaw.config/channels/${e}`
		};
		if (isRecord(t) && typeof t.enabled === "boolean") n.enabled = t.enabled;
		return n;
	});
	const r = Object.entries(asNonArrayRecord(asNonArrayRecord(e.mcp).servers)).toSorted(([e], [t]) => e.localeCompare(t)).map(([e, t]) => {
		const n = {
			id: e,
			transport: mcpServerTransport(t),
			source: `oc://openclaw.config/mcp/servers/${ocPathSegment$1(e)}`
		};
		if (isRecord(t)) {
			if (typeof t.command === "string") n.command = t.command;
			if (typeof t.url === "string") n.url = redactMcpUrlForEvidence(t.url);
		}
		return n;
	});
	const i = Object.keys(asNonArrayRecord(asNonArrayRecord(e.models).providers)).toSorted((e, t) => e.localeCompare(t)).map((e) => ({
		id: normalizeProviderId(e),
		source: `oc://openclaw.config/models/providers/${e}`
	}));
	const a = [];
	if (isRecord(e.agents)) {
		collectModelRefsFromRecord(a, e.agents, "oc://openclaw.config/agents");
		collectModelRefsFromAgentAllowlist(a, e.agents);
	}
	return {
		channels: n,
		mcpServers: r,
		modelProviders: i,
		modelRefs: a.toSorted((e, t) => e.provider.localeCompare(t.provider) || e.model.localeCompare(t.model)),
		network: [
			["browser-private-network", "browser/ssrfPolicy/dangerouslyAllowPrivateNetwork"],
			["browser-private-network-legacy", "browser/ssrfPolicy/allowPrivateNetwork"],
			["web-fetch-private-network", "tools/web/fetch/ssrfPolicy/dangerouslyAllowPrivateNetwork"],
			["web-fetch-private-network-legacy", "tools/web/fetch/ssrfPolicy/allowPrivateNetwork"],
			["web-fetch-rfc2544-benchmark-range", "tools/web/fetch/ssrfPolicy/allowRfc2544BenchmarkRange"],
			["web-fetch-ipv6-unique-local-range", "tools/web/fetch/ssrfPolicy/allowIpv6UniqueLocalRange"]
		].flatMap(([t, n]) => {
			const r = readBooleanPath(e, n.split("/"));
			return r === void 0 ? [] : [{
				id: t,
				source: `oc://openclaw.config/${n}`,
				value: r
			}];
		}),
		...t.includeIngress === false ? {} : { ingress: scanPolicyIngress(e) },
		...t.includeGatewayExposure === false ? {} : { gatewayExposure: scanPolicyGatewayExposure(e) },
		...t.includeAgentWorkspace === false ? {} : { agentWorkspace: scanPolicyAgentWorkspace(e) },
		...t.includeDataHandling === false ? {} : { dataHandling: scanPolicyDataHandling(e) },
		...t.includeToolPosture === false ? {} : { toolPosture: scanPolicyToolPosture(e) },
		...t.includeSandboxPosture === false ? {} : { sandboxPosture: scanPolicySandboxPosture(e) },
		...t.includeSecrets === false ? {} : { secrets: scanPolicySecrets(e) },
		...t.includeAuthProfiles === false ? {} : { authProfiles: scanPolicyAuthProfiles(e) },
		...t.includeExecApprovals === false || t.execApprovalsRaw === void 0 ? {} : { execApprovals: t.execApprovalsRaw === null ? [] : scanPolicyExecApprovals(t.execApprovalsRaw) },
		...t.routing === void 0 ? {} : { routing: scanPolicyRouting(e, t.routing) },
		...t.toolsRaw === void 0 ? {} : { tools: scanPolicyTools(t.toolsRaw) }
	};
}
function mcpServerTransport(e) {
	if (!isRecord(e)) return "unknown";
	if (typeof e.command === "string") return "stdio";
	if (e.transport === "sse" || e.transport === "streamable-http") return e.transport;
	if (typeof e.url === "string") return "streamable-http";
	return "unknown";
}
function redactMcpUrlForEvidence(e) {
	try {
		const t = new URL(e);
		return `${t.protocol}//${t.host}`;
	} catch {
		return "[redacted-url]";
	}
}
function collectModelRefsFromValue(e, t, n) {
	if (typeof t === "string") {
		pushModelRef(e, t, n);
		return;
	}
	if (!isRecord(t)) return;
	if (typeof t.primary === "string") pushModelRef(e, t.primary, `${n}/primary`);
	if (Array.isArray(t.fallbacks)) {
		for (const [r, i] of t.fallbacks.entries()) if (typeof i === "string") pushModelRef(e, i, `${n}/fallbacks/#${r}`);
	}
}
function collectModelRefsFromRecord(e, t, n) {
	for (const [r, i] of Object.entries(t)) {
		const t = `${n}/${r}`;
		if (isModelSettingKey(r)) {
			collectModelRefsFromValue(e, i, t);
			continue;
		}
		if (Array.isArray(i)) {
			for (const [n, r] of i.entries()) if (isRecord(r)) collectModelRefsFromRecord(e, r, `${t}/#${n}`);
			continue;
		}
		if (isRecord(i)) collectModelRefsFromRecord(e, i, t);
	}
}
function collectModelRefsFromAgentAllowlist(e, t) {
	const n = t.defaults;
	if (isRecord(n) && isRecord(n.models)) collectModelRefsFromModelMap(e, n.models, "oc://openclaw.config/agents/defaults/models");
	for (const n of collectPolicyConfiguredAgents(t)) {
		const t = n.value;
		if (!isRecord(t.models)) continue;
		collectModelRefsFromModelMap(e, t.models, `${n.sourceBase}/models`);
	}
}
function collectModelRefsFromModelMap(e, t, n) {
	for (const r of Object.keys(t)) pushModelRef(e, r, `${n}/${ocPathSegment$1(r)}`);
}
function isModelSettingKey(e) {
	return e === "model" || e.endsWith("Model");
}
function pushModelRef(e, t, n) {
	const r = t.trim();
	const i = r.indexOf("/");
	if (i <= 0 || i >= r.length - 1) return;
	e.push({
		ref: t,
		provider: normalizeProviderId(r.slice(0, i)),
		model: r.slice(i + 1),
		source: n
	});
}
//#endregion
//#region extensions/policy/src/doctor/exec-approval-rules.ts
function execApprovalAllowlistExpectedShapeFinding(e, t) {
	if (e === void 0) return;
	if (!Array.isArray(e)) return policyShapeFinding(t.policyPath, `oc://${t.policyDocName}/${t.target}`, `${t.policyPath} ${t.property} must be an array.`, `Fix ${t.policyPath} so ${t.property} is an array of exec approval allowlist entries.`);
	const n = e.findIndex((e) => execApprovalAllowlistRequirement(e) === void 0);
	if (n < 0) return;
	return policyShapeFinding(t.policyPath, `oc://${t.policyDocName}/${t.target}/#${n}`, `${t.policyPath} ${t.property}[${n}] must be a non-empty string or an object with pattern and optional argPattern strings.`, `Use entries such as "deploy" or { "pattern": "deploy", "argPattern": "^--prod$" }.`);
}
function readExecApprovalAllowlistRequirements(e, t) {
	const n = getPolicyPath(e, t);
	if (!Array.isArray(n)) return;
	const r = n.map(execApprovalAllowlistRequirement);
	return r.every((e) => e !== void 0) ? r : void 0;
}
function execApprovalAllowlistRequirement(e) {
	if (typeof e === "string") {
		const t = e.trim();
		return t === "" ? void 0 : execApprovalAllowlistRequirementFromParts(t);
	}
	if (!isRecord(e)) return;
	if (Object.keys(e).some((e) => e !== "argPattern" && e !== "pattern")) return;
	const t = typeof e.pattern === "string" ? e.pattern.trim() : "";
	if (t === "") return;
	const n = typeof e.argPattern === "string" ? e.argPattern.trim() : void 0;
	if (e.argPattern !== void 0 && n === void 0) return;
	return execApprovalAllowlistRequirementFromParts(t, n === "" ? void 0 : n);
}
function execApprovalAllowlistRequirementFromParts(e, t) {
	return {
		key: execApprovalAllowlistRequirementKey(e, t),
		pattern: e,
		...t === void 0 ? {} : { argPattern: t }
	};
}
function execApprovalAllowlistRequirementKey(e, t) {
	return `${e}\0${t ?? ""}`;
}
function execApprovalAllowlistMissingTarget(e) {
	return e === void 0 ? EXEC_APPROVALS_POLICY_URI : execApprovalsPolicyUri(`agents/${ocPathSegment(e)}/allowlist`);
}
function formatExecApprovalAllowlistEntry(e) {
	const t = e?.pattern ?? "";
	return e?.argPattern === void 0 ? t : `${t} argPattern=${e.argPattern}`;
}
function execApprovalAgentEntries(e, t, n, r) {
	const i = e.filter((e) => e.kind === "agent");
	const a = i.find((e) => e.agentId === "*");
	const hasValue = (e) => e[n] !== void 0 || n === "security" && e.securityConfigured === true;
	if (r === void 0) {
		const e = i.filter((e) => hasValue(e) || n === "security" && e.agentId === "*");
		return (n === "security" ? a === void 0 : a?.autoAllowSkills === void 0) ? [...e, t ?? syntheticExecApprovalAgentEntry("*")] : e;
	}
	const o = i.find((e) => e.agentId !== void 0 && normalizeAgentId(e.agentId) === normalizeAgentId(r));
	if (o !== void 0 && hasValue(o)) return [o];
	if (a?.[n] !== void 0) return [a];
	return [(n === "security" ? o ?? a : void 0) ?? t ?? syntheticExecApprovalAgentEntry(r)];
}
function syntheticExecApprovalAgentEntry(e) {
	return {
		id: `agent:${e}:runtime-defaults`,
		kind: "agent",
		source: EXEC_APPROVALS_POLICY_URI,
		agentId: e
	};
}
//#endregion
//#region extensions/policy/src/doctor/ordered-shape.ts
function policyRuleValueIsValid(e, t) {
	switch (e.valueType) {
		case "boolean": return typeof t === "boolean";
		case "channel-provider-deny-rules": return Array.isArray(t) && t.every((e) => isRecord(e) && isRecord(e.when) && typeof e.when.provider === "string" && e.when.provider.trim() !== "");
		case "routing-probes": return Array.isArray(t);
		case "string-list":
		case "string": {
			if (e.valueType === "string-list" && e.policyPath.join(".") === "execApprovals.agents.allowlist.expected") return readExecApprovalAllowlistRequirements(t, []) !== void 0;
			const n = e.allowedValues ?? e.orderedValues;
			return stringListIssue(e.valueType === "string" ? [t] : t, e.caseSensitive === true ? n : n?.map((e) => e.toLowerCase()), e.caseSensitive === true ? "trim" : "lower", false) === void 0;
		}
	}
	return false;
}
function firstPolicyShapeFinding(e) {
	for (const t of e) if (t !== void 0) return t;
}
function collectPolicyShapeFindings(e) {
	return Array.from(e).filter((e) => e !== void 0);
}
function stringListIssue(e, t, n = "trim", r = true) {
	if (!Array.isArray(e)) return { kind: "array" };
	const i = e.findIndex((i, a) => {
		if (!r && !(a in e)) return false;
		if (typeof i !== "string") return true;
		const o = n === "raw" ? i : n === "lower" ? i.trim().toLowerCase() : i.trim();
		return o === "" || t !== void 0 && !t.includes(o);
	});
	return i < 0 ? void 0 : {
		kind: "entry",
		index: i
	};
}
/** Executes primitive checks; callers retain their explicit first/all diagnostic schedule. */
function createOrderedPolicyShape(e, t) {
	const paths = (n) => {
		const r = n === "" ? [] : n.split(".");
		return {
			value: getPolicyPath(e, r),
			property: [t.propertyPrefix, ...r].filter((e) => e !== void 0).join("."),
			target: [t.targetPrefix, ...r.map(ocPathSegment)].filter((e) => e !== void 0).join("/"),
			hasTarget: t.targetPrefix !== void 0 || r.length > 0
		};
	};
	const diagnostic = (e, n, r = {}) => {
		const i = paths(e);
		const a = i.property;
		const o = {
			policy: t.policyPath,
			property: a,
			key: r.key ?? "",
			index: String(r.index ?? ""),
			unsupported: a + "." + (r.key ?? ""),
			valueName: r.valueName ?? "",
			allowed: r.allowed?.join(", ") ?? ""
		};
		const render = (e) => e.replace(/\{(policy|property|key|index|unsupported|valueName|allowed)\}/g, (e, t) => o[t]);
		const s = r.key !== void 0 ? "/" + ocPathSegment(r.key) : r.index !== void 0 ? "/#" + r.index : "";
		return policyShapeFinding(t.policyPath, "oc://" + t.policyDocName + (i.hasTarget ? "/" + i.target : "") + s, render(n.message), render(n.hint));
	};
	return {
		value: (e) => paths(e).value,
		finding: diagnostic,
		object(e, t = "Fix {policy} so {property} is an object.", n = false) {
			const r = paths(e).value;
			return r === void 0 && !n || isRecord(r) ? void 0 : diagnostic(e, {
				message: "{policy} {property} must be an object.",
				hint: t
			});
		},
		keys(e, t, n, r, i = "{policy} {unsupported} is not supported in " + n + " policy.") {
			const a = paths(e).value;
			if (!isRecord(a)) return;
			const o = Object.keys(a).find((e) => !t.includes(e));
			return o === void 0 ? void 0 : diagnostic(e, {
				message: i,
				hint: r
			}, { key: o });
		},
		boolean(e, t = "Set {property} to true or false.") {
			const n = paths(e).value;
			return n === void 0 || typeof n === "boolean" ? void 0 : diagnostic(e, {
				message: "{policy} {property} must be a boolean.",
				hint: t
			});
		},
		string(e, t, n = false) {
			const r = paths(e).value;
			return r === void 0 && !n || typeof r === "string" && r.trim() !== "" ? void 0 : diagnostic(e, {
				message: "{policy} {property} must be a non-empty string.",
				hint: t
			});
		},
		enum(e, t, n) {
			const r = paths(e).value;
			return r === void 0 || typeof r === "string" && t.includes(r) ? void 0 : diagnostic(e, n, { allowed: t });
		},
		list(e, t = {}) {
			const n = paths(e).value;
			if (n === void 0) return;
			const r = stringListIssue(n, t.allowed, t.normalize);
			if (r === void 0) return;
			const i = r.kind === "array" ? t.array ?? {
				message: "{policy} {property} must be an array.",
				hint: "Fix {policy} so {property} is an array of {valueName}s."
			} : t.entry ?? {
				message: "{policy} {property}[{index}] must be a supported {valueName}.",
				hint: "Use non-empty {valueName} entries." + (t.allowed === void 0 ? "" : " Supported values: {allowed}.")
			};
			return diagnostic(e, i, {
				...r.kind === "entry" ? { index: r.index } : {},
				valueName: t.valueName,
				allowed: t.allowed
			});
		}
	};
}
//#endregion
//#region extensions/policy/src/doctor/policy-evidence-finding.ts
function policyEvidenceFinding(e, t, n = { path: "openclaw config" }) {
	return {
		checkId: t.checkId,
		severity: "error",
		message: t.message,
		source: "policy",
		...n,
		ocPath: e.source,
		target: e.source,
		requirement: t.requirement,
		fixHint: t.fixHint
	};
}
function policyEvidenceRuleFindings(e, t, n, r) {
	return t.flatMap((t) => e.filter((e) => (t.kind === void 0 || e.kind === t.kind) && t.violates(e)).map((e) => policyEvidenceFinding(e, {
		checkId: t.checkId,
		message: t.message(e),
		requirement: `oc://${n}/${r}/${t.path.join("/")}`,
		fixHint: t.fixHint
	})));
}
//#endregion
//#region extensions/policy/src/doctor/strictness.ts
function isPolicyValueAtLeastAsStrict(e, t, n) {
	switch (e.strictness) {
		case "allowlist-subset":
		case "denylist-superset":
		case "exact-list": return comparePolicyStringLists(e, t, n);
		case "ordered-string": return isPolicyOrderedStringAtLeastAsStrict(e, t, n);
		case "requires-true": return n !== true || t === true;
		case "requires-false": return n !== false || t === false;
		case "routing-probes": return routingProbesAtLeastAsStrict(t, n);
	}
	return false;
}
function routingProbesAtLeastAsStrict(e, t) {
	if (!Array.isArray(e) || !Array.isArray(t)) return false;
	const n = /* @__PURE__ */ new Map();
	for (const t of e) {
		if (!isRecord(t) || !hasNonEmptyString(t.id) || n.has(t.id)) return false;
		n.set(t.id, t);
	}
	return t.every((e) => {
		if (!isRecord(e) || !hasNonEmptyString(e.id)) return false;
		const t = n.get(e.id);
		if (t === void 0) return false;
		const r = canonicalRoutingRoute(t.route);
		const i = canonicalRoutingRoute(e.route);
		if (r === void 0 || i === void 0 || r !== i || !isRecord(t.expect) || !isRecord(e.expect) || !hasNonEmptyString(t.expect.agentId) || !hasNonEmptyString(e.expect.agentId) || normalizeAgentId(t.expect.agentId) !== normalizeAgentId(e.expect.agentId)) return false;
		return routingMatchKindsAtLeastAsStrict(t.expect.matchedBy, e.expect.matchedBy);
	});
}
function routingMatchKindsAtLeastAsStrict(e, t) {
	if (t === void 0) return e === void 0 || validPolicyRoutingMatchKinds(e);
	if (!validPolicyRoutingMatchKinds(e) || !validPolicyRoutingMatchKinds(t)) return false;
	const n = new Set(t);
	return e.every((e) => n.has(e));
}
function canonicalRoutingRoute(e) {
	if (!isRecord(e) || Object.keys(e).some((e) => ![
		"accountId",
		"channel",
		"guildId",
		"memberRoleIds",
		"parentPeer",
		"peer",
		"teamId"
	].includes(e)) || !hasNonEmptyString(e.channel) || [
		e.accountId,
		e.guildId,
		e.teamId
	].some((e) => e !== void 0 && !hasNonEmptyString(e))) return;
	const t = canonicalRoutingPeer(e.peer);
	const n = canonicalRoutingPeer(e.parentPeer);
	if (t === null || n === null) return;
	const r = e.memberRoleIds;
	if (r !== void 0 && (!Array.isArray(r) || r.length === 0 || r.some((e) => !hasNonEmptyString(e)) || new Set(r).size !== r.length)) return;
	return JSON.stringify({
		channel: normalizeLowercaseStringOrEmpty(e.channel),
		accountId: normalizeAccountId(e.accountId),
		peer: t,
		parentPeer: n,
		guildId: normalizeRoutingId(e.guildId),
		teamId: normalizeRoutingId(e.teamId),
		memberRoleIds: r?.toSorted()
	});
}
function canonicalRoutingPeer(e) {
	if (e === void 0) return;
	if (!isRecord(e) || Object.keys(e).some((e) => e !== "id" && e !== "kind") || ![
		"channel",
		"direct",
		"group"
	].some((t) => t === e.kind) || !hasNonEmptyString(e.id)) return null;
	return {
		kind: e.kind,
		id: e.id.trim()
	};
}
function normalizeRoutingId(e) {
	return typeof e === "string" ? e.trim() : void 0;
}
function isPolicyOrderedStringAtLeastAsStrict(e, t, n) {
	const r = policyString(t, e);
	const i = policyString(n, e);
	if (r === void 0 || i === void 0 || e.orderedValues === void 0) return false;
	const a = e.orderedValues.map((t) => e.caseSensitive === true ? t : t.toLowerCase());
	const o = a.indexOf(r);
	const s = a.indexOf(i);
	return o >= 0 && s >= 0 && o >= s;
}
function comparePolicyStringLists(e, t, n) {
	const r = policyStringList(t, e);
	const i = policyStringList(n, e);
	if (r === void 0 || i === void 0) return false;
	if (e.strictness === "allowlist-subset") {
		if (e.emptyList === "disabled") {
			if (i.length === 0) return true;
			if (r.length === 0) return false;
		}
		const t = new Set(i);
		return r.every((e) => t.has(e));
	}
	if (e.strictness === "denylist-superset") {
		if (e.policyPath.join(".") === "tools.denyTools") return i.flatMap(expandPolicyToolRequirement).every((e) => toolListCoversTool(r, e));
		const t = new Set(r);
		return i.every((e) => t.has(e));
	}
	const a = r.toSorted();
	const o = i.toSorted();
	return a.length === o.length && a.every((e, t) => e === o[t]);
}
function policyStringList(e, t) {
	if (t.valueType === "channel-provider-deny-rules") return channelProviderDenyRuleList(e, t);
	if (!Array.isArray(e)) return;
	if (t.policyPath.join(".") === "execApprovals.agents.allowlist.expected") return readExecApprovalAllowlistRequirements(e, [])?.map((e) => e.key);
	if (!e.every((e) => typeof e === "string")) return;
	return e.map((e) => e.trim()).filter(Boolean).map((e) => normalizePolicyStringListEntry(e, t));
}
function normalizePolicyStringListEntry(e, t) {
	if (t.normalizeValues === "model-provider") return normalizeProviderId(e);
	return t.caseSensitive === true ? e : e.toLowerCase();
}
function channelProviderDenyRuleList(e, t) {
	if (!Array.isArray(e)) return;
	const n = [];
	for (const r of e) {
		if (!isChannelDenyRule(r)) return;
		const e = r.when.provider.trim();
		if (e !== "") n.push(t.caseSensitive === true ? e : e.toLowerCase());
	}
	return n;
}
function policyString(e, t) {
	if (typeof e !== "string" || e.trim() === "") return;
	const n = e.trim();
	return t.caseSensitive === true ? n : n.toLowerCase();
}
//#endregion
//#region extensions/policy/src/doctor/policy-scope.ts
function scopedAgentEvidenceMatches(e, t, n, r) {
	return scopedAgentIdMatches(e.agentId, t) || r && !n.some((n) => n.scope === "agent" && n.kind === e.kind && scopedAgentIdMatches(n.agentId, t));
}
function scopedAgentIdMatches(e, t) {
	return e !== void 0 && normalizeAgentId(e) === normalizeAgentId(t);
}
function policyHasRules(e, t) {
	if (!isRecord(e)) return false;
	const hasRules = (e) => {
		if (t === "execApprovals") {
			const t = e.execApprovals;
			return isRecord(t) && (t.requireFile !== void 0 || isRecord(t.defaults) || isRecord(t.agents));
		}
		return POLICY_RULE_METADATA.some((n) => n.policyPath[0] === t && (t !== "tools" || n.policyPath[1] !== "requireMetadata") && getPolicyPath(e, n.policyPath) !== void 0);
	};
	return hasRules(e) || t !== "auth" && t !== "gateway" && t !== "secrets" && scopedPolicyOverlays(e).some(([, e]) => hasRules(e));
}
function scopedPolicyOverlays(e) {
	if (!isRecord(e) || !isRecord(e.scopes)) return [];
	return Object.entries(e.scopes).filter((e) => isRecord(e[1]));
}
function agentScopedPolicyTargets(e) {
	return scopedPolicyOverlays(e).flatMap(([e, t]) => normalizePolicySelectorValues(t.agentIds, "agentIds").map((n) => ({
		scopeName: e,
		agentId: n,
		overlay: t
	})));
}
function normalizePolicySelectorValues(e, t) {
	return Array.isArray(e) ? e.filter((e) => typeof e === "string" && e.trim() !== "").map(t === "agentIds" ? normalizeAgentId : normalizeLowercaseStringOrEmpty) : [];
}
function duplicateScopedPolicyFieldFinding(e, t) {
	return duplicateScopedFieldFinding(e, {
		...t,
		selector: "agentIds",
		selectorLabel: "agent"
	}) ?? duplicateScopedFieldFinding(e, {
		...t,
		selector: "channelIds",
		selectorLabel: "channel"
	});
}
function duplicateScopedFieldFinding(e, t) {
	const n = /* @__PURE__ */ new Map();
	for (const [r, i] of Object.entries(e)) {
		if (!isRecord(i)) continue;
		const e = scopedPolicyFields(r, i, t.selector);
		for (const a of normalizePolicySelectorValues(i[t.selector], t.selector)) for (const i of e) {
			const e = getPolicyPath(t.policy, i.metadata.policyPath);
			if (e !== void 0 && !isPolicyValueAtLeastAsStrict(i.metadata, i.value, e)) return policyShapeFinding(t.policyPath, `oc://${t.policyDocName}/${i.targetPath}`, `${t.policyPath} scopes.${r}.${i.propertyPath} is weaker than the top-level ${i.propertyPath} policy.`, `Use an equally or more restrictive scoped value, or remove the scoped override.`);
			const o = `${a}\0${i.propertyPath}`;
			const s = n.get(o);
			if (s !== void 0 && !isPolicyValueAtLeastAsStrict(i.metadata, i.value, s.field.value)) return policyShapeFinding(t.policyPath, `oc://${t.policyDocName}/${i.targetPath}`, `${t.policyPath} scopes.${r}.${i.propertyPath} is not an equally or more restrictive override of ${s.propertyPath} for ${t.selectorLabel} '${a}'.`, `Use one effective scoped value per ${t.selectorLabel}, or make later scoped values stricter according to policy metadata.`);
			n.set(o, {
				propertyPath: `scopes.${r}.${i.propertyPath}`,
				field: i
			});
		}
	}
}
function scopedPolicyFields(e, t, n) {
	const r = `scopes/${ocPathSegment(e)}`;
	return POLICY_RULE_METADATA.filter((e) => e.scopeSelectors?.includes(n) === true).map((e) => ({
		rule: e,
		value: getPolicyPath(t, e.policyPath)
	})).filter((e) => e.value !== void 0).map(({ rule: e, value: t }) => ({
		propertyPath: e.policyPath.join("."),
		targetPath: `${r}/${e.policyPath.map(ocPathSegment).join("/")}`,
		metadata: e,
		value: t
	}));
}
//#endregion
//#region extensions/policy/src/doctor/data-auth-findings.ts
function secretAuthProvenanceFindings(e, t, n, r) {
	function secretPolicyShapeFindings() {
		if (!isRecord(e) || !isRecord(e.secrets)) return [];
		const r = createOrderedPolicyShape(e, {
			policyPath: t,
			policyDocName: n
		});
		function* findings() {
			yield r.boolean("secrets.requireManagedProviders");
			yield r.boolean("secrets.allowInsecureProviders");
			yield r.list("secrets.denySources", {
				array: {
					message: "{policy} {property} must be an array of source names.",
					hint: "Use an array such as [\"exec\"] or remove secrets.denySources."
				},
				entry: {
					message: "{policy} {property}[{index}] must be a non-empty source name.",
					hint: "Use non-empty source names such as env, file, exec, or openclaw."
				}
			});
		}
		return collectPolicyShapeFindings(findings());
	}
	const i = secretPolicyShapeFindings();
	function authProfileAllowModesShapeFindings() {
		const r = createOrderedPolicyShape(e, {
			policyPath: t,
			policyDocName: n
		}).list("auth.profiles.allowModes", {
			allowed: SUPPORTED_AUTH_PROFILE_MODES,
			normalize: "lower",
			array: {
				message: "{policy} {property} must be an array of auth modes.",
				hint: "Use supported auth modes: {allowed}."
			},
			entry: {
				message: "{policy} {property}[{index}] must be a supported auth mode.",
				hint: "Use supported auth modes: {allowed}."
			}
		});
		return r === void 0 ? [] : [r];
	}
	const a = authProfileAllowModesShapeFindings();
	return [...i.length > 0 ? i : [...secretManagedProviderFindings(e, n, r), ...secretDeniedSourceFindings(e, n, r)], ...a.length > 0 ? a : [...authProfileMetadataFindings(e, n, r), ...authProfileModeFindings(e, n, r)]];
}
function dataHandlingFindings(e, t, n, r) {
	function dataHandlingPolicyShapeFindings() {
		if (!isRecord(e) || !isRecord(e.dataHandling)) return [];
		const r = createOrderedPolicyShape(e, {
			policyPath: t,
			policyDocName: n
		});
		const i = [
			["sensitiveLogging", "requireRedaction"],
			["telemetry", "denyContentCapture"],
			["retention", "requireSessionMaintenance"],
			["memory", "denySessionTranscriptIndexing"]
		];
		function* sectionRules(e, t) {
			yield r.keys("dataHandling." + e, [t], "data-handling", "Remove {unsupported} or use {property}." + t + ".");
			yield r.boolean("dataHandling." + e + "." + t);
		}
		function* shapeRules() {
			yield r.keys("dataHandling", [
				"memory",
				"retention",
				"sensitiveLogging",
				"telemetry"
			], "data-handling", "Remove {unsupported} or use a supported data-handling policy rule.");
			for (const [e] of i) yield r.object("dataHandling." + e, "Fix {property} so it contains boolean policy rules.");
			for (const [e, t] of i) yield firstPolicyShapeFinding(sectionRules(e, t));
		}
		return collectPolicyShapeFindings(shapeRules());
	}
	const i = dataHandlingPolicyShapeFindings();
	if (i.length > 0) return i;
	const a = [];
	a.push(...dataHandlingFindingsForRule(e, n, "dataHandling", r, () => true));
	for (const t of agentScopedPolicyTargets(e)) {
		if (!policyHasRules(t.overlay, "dataHandling")) continue;
		a.push(...dataHandlingFindingsForRule(t.overlay, n, `scopes/${ocPathSegment(t.scopeName)}/dataHandling`, r, (e) => e.kind !== "memorySessionTranscriptIndexing" || scopedAgentEvidenceMatches(e, t.agentId, r.dataHandling ?? [], e.id === "agents-defaults-memory-session-transcripts")));
	}
	return a;
}
function dataHandlingFindingsForRule(e, t, n, r, i) {
	const a = isRecord(e) ? e.dataHandling : void 0;
	if (!isRecord(a)) return [];
	const o = [
		{
			path: ["telemetry", "denyContentCapture"],
			kind: "telemetryContentCapture",
			violates: (e) => e.value === true,
			checkId: CHECK_IDS.policyDataHandlingTelemetryContentCapture,
			message: () => "Telemetry content capture is enabled.",
			fixHint: "Disable diagnostics.otel.captureContent or update policy after review."
		},
		{
			path: ["retention", "requireSessionMaintenance"],
			kind: "sessionRetentionMode",
			violates: (e) => e.value !== "enforce",
			checkId: CHECK_IDS.policyDataHandlingSessionRetentionNotEnforced,
			message: (e) => `Session retention maintenance mode is '${e.value ?? "unknown"}'.`,
			fixHint: "Set session.maintenance.mode to enforce or update policy after review."
		},
		{
			path: ["memory", "denySessionTranscriptIndexing"],
			kind: "memorySessionTranscriptIndexing",
			violates: (e) => e.value === true,
			checkId: CHECK_IDS.policyDataHandlingSessionTranscriptMemory,
			message: (e) => `${dataHandlingLabel(e)} enables session transcript memory indexing.`,
			fixHint: "Disable session transcript memory indexing for the matching config surface or update policy after review."
		}
	];
	return policyEvidenceRuleFindings((r.dataHandling ?? []).filter(i), o.filter((e) => readBooleanPath(a, e.path) === true), t, n);
}
function secretManagedProviderFindings(e, t, n) {
	if (readBooleanPath(e, ["secrets", "requireManagedProviders"]) !== true) return [];
	const r = n.secrets ?? [];
	const i = new Set(r.filter((e) => e.kind === "provider" && e.providerSource !== void 0).map((e) => `${e.providerSource}:${e.id}`));
	return r.filter((e) => e.kind === "input" && e.provenance === "secretRef" && (e.refProvider === void 0 || e.refSource === void 0 || !i.has(`${e.refSource}:${e.refProvider}`))).map((e) => {
		return policyEvidenceFinding(e, {
			checkId: CHECK_IDS.policySecretsUnmanagedProvider,
			message: `SecretRef uses unmanaged provider '${e.refProvider ?? "default"}'.`,
			requirement: `oc://${t}/secrets/requireManagedProviders`,
			fixHint: "Declare the referenced provider under secrets.providers or update policy after review."
		});
	});
}
function secretDeniedSourceFindings(e, t, n) {
	const r = new Set(readStringList(e, ["secrets", "denySources"]));
	if (r.size === 0) return [];
	return (n.secrets ?? []).filter((e) => {
		const t = e.kind === "provider" ? e.providerSource : e.refSource;
		return t !== void 0 && r.has(t);
	}).map((e) => {
		const n = e.kind === "provider" ? e.providerSource : e.refSource;
		return policyEvidenceFinding(e, {
			checkId: CHECK_IDS.policySecretsDeniedProviderSource,
			message: `Secret ${e.kind} '${e.id}' uses denied source '${n}'.`,
			requirement: `oc://${t}/secrets/denySources`,
			fixHint: "Move this secret to an approved source or update policy after review."
		});
	});
}
function authProfileMetadataFindings(e, t, n) {
	const r = requiredAuthProfileMetadata(e);
	if (r.size === 0) return [];
	return (n.authProfiles ?? []).flatMap((e) => {
		const n = [...r].filter((t) => !authProfileHasMetadata(e, t));
		if (n.length === 0) return [];
		return [policyEvidenceFinding(e, {
			checkId: CHECK_IDS.policyAuthProfileInvalidMetadata,
			message: `Auth profile '${e.id}' is missing required metadata: ${n.join(", ")}.`,
			requirement: `oc://${t}/auth/profiles/requireMetadata`,
			fixHint: "Set auth.profiles.<id>.provider and a supported auth profile mode."
		})];
	});
}
function authProfileModeFindings(e, t, n) {
	const r = new Set(readStringList(e, [
		"auth",
		"profiles",
		"allowModes"
	]));
	if (r.size === 0) return [];
	return (n.authProfiles ?? []).filter((e) => e.mode !== void 0 && !r.has(e.mode)).map((e) => {
		return policyEvidenceFinding(e, {
			checkId: CHECK_IDS.policyAuthProfileUnapprovedMode,
			message: `Auth profile '${e.id}' uses mode '${e.mode}' outside the policy allowlist.`,
			requirement: `oc://${t}/auth/profiles/allowModes`,
			fixHint: "Change the auth profile mode or update policy after review."
		});
	});
}
function dataHandlingLabel(e) {
	return e.agentId === void 0 ? "Global data handling config" : "agent '" + e.agentId + "'";
}
//#endregion
//#region extensions/policy/src/doctor/access-shapes.ts
function ingressPolicyShapeFinding(e, t) {
	if (e === void 0) return;
	const n = {
		...t,
		propertyPrefix: t.propertyPrefix ?? "ingress",
		targetPrefix: t.targetPrefix ?? "ingress"
	};
	const r = createOrderedPolicyShape(e, n);
	function* findings() {
		yield r.object("");
		if (t.allowSession === false && r.value("session") !== void 0) yield r.finding("session", {
			message: "{policy} {property} is not supported by the channelIds selector.",
			hint: "Move session ingress rules to top-level ingress; scoped ingress currently supports ingress.channels.*."
		});
		yield r.keys("", ["channels", "session"], "ingress", "Remove {unsupported} or use ingress.session or ingress.channels.");
		yield r.object("session");
		yield r.object("channels");
		yield r.keys("session", ["requireDmScope"], "ingress", "Remove {unsupported} or use {property}.requireDmScope.");
		yield r.enum("session.requireDmScope", SUPPORTED_DM_SCOPES, {
			message: "{policy} {property} must be a supported DM scope.",
			hint: "Use supported DM scopes: {allowed}."
		});
		yield r.keys("channels", [
			"allowDmPolicies",
			"denyOpenGroups",
			"requireMentionInGroups"
		], "ingress", "Remove {unsupported} or use a supported ingress channel policy rule.");
		yield r.list("channels.allowDmPolicies", {
			allowed: SUPPORTED_DM_POLICIES,
			valueName: "DM policy"
		});
		yield r.boolean("channels.denyOpenGroups");
		yield r.boolean("channels.requireMentionInGroups");
	}
	return firstPolicyShapeFinding(findings());
}
function execApprovalsPolicyShapeFinding(e, t) {
	if (e === void 0) return;
	const n = {
		...t,
		propertyPrefix: t.propertyPrefix ?? "execApprovals",
		targetPrefix: t.targetPrefix ?? "execApprovals"
	};
	const r = createOrderedPolicyShape(e, n);
	const i = t.allowDefaults ?? true;
	function* findings() {
		yield r.object("");
		yield r.keys("", i ? [
			"agents",
			"defaults",
			"requireFile"
		] : ["agents"], "exec approvals", "Remove {unsupported} or use a supported execApprovals rule.");
		yield r.boolean("requireFile", "Set execApprovals.requireFile to true or false.");
		for (const e of i ? ["defaults", "agents"] : ["agents"]) yield r.object(e);
		if (i) {
			yield r.keys("defaults", ["allowSecurity"], "exec approvals", "Use execApprovals.defaults.allowSecurity or remove the unsupported rule.");
			yield r.list("defaults.allowSecurity", {
				allowed: SUPPORTED_EXEC_APPROVAL_SECURITY,
				valueName: "exec approval security mode"
			});
		}
		yield r.keys("agents", [
			"allowAutoAllowSkills",
			"allowSecurity",
			"allowlist"
		], "exec approvals", "Use execApprovals.agents.allowSecurity, execApprovals.agents.allowAutoAllowSkills, or execApprovals.agents.allowlist.expected.");
		yield r.list("agents.allowSecurity", {
			allowed: SUPPORTED_EXEC_APPROVAL_SECURITY,
			valueName: "exec approval security mode"
		});
		yield r.boolean("agents.allowAutoAllowSkills", "Set execApprovals.agents.allowAutoAllowSkills to true or false.");
		yield r.object("agents.allowlist");
		yield r.keys("agents.allowlist", ["expected"], "exec approvals", "Use execApprovals.agents.allowlist.expected or remove the unsupported rule.");
		yield execApprovalAllowlistExpectedShapeFinding(r.value("agents.allowlist.expected"), {
			policyDocName: t.policyDocName,
			policyPath: t.policyPath,
			property: n.propertyPrefix + ".agents.allowlist.expected",
			target: n.targetPrefix + "/agents/allowlist/expected"
		});
	}
	return firstPolicyShapeFinding(findings());
}
function scopedDataHandlingPolicyShapeFinding(e, t) {
	const n = createOrderedPolicyShape(e, {
		...t,
		propertyPrefix: "scopes." + t.scopeName + ".dataHandling",
		targetPrefix: t.targetPrefix + "/dataHandling"
	});
	function* findings() {
		yield n.keys("", ["memory"], "", "Move global data-handling rules to top-level dataHandling, or use dataHandling.memory with agentIds.", "{policy} {unsupported} is not a supported scoped policy section.");
		yield n.object("memory", "Fix {policy} so the scoped dataHandling.memory policy section is an object.");
		yield n.keys("memory", ["denySessionTranscriptIndexing"], "", "Use dataHandling.memory.denySessionTranscriptIndexing or remove the unsupported rule.", "{policy} {unsupported} is not a supported scoped policy rule.");
		yield n.boolean("memory.denySessionTranscriptIndexing", "Set dataHandling.memory.denySessionTranscriptIndexing to true or false.");
	}
	return firstPolicyShapeFinding(findings());
}
//#endregion
//#region extensions/policy/src/doctor/posture-shapes.ts
function object(e) {
	return {
		kind: "object",
		path: e.split(".")
	};
}
function keys(e, t, n, r = false) {
	const i = e.split(".");
	const a = /* @__PURE__ */ new Set();
	for (const e of POLICY_RULE_METADATA) if (i.every((t, n) => e.policyPath[n] === t) && (!r || e.scopeSelectors?.includes("agentIds"))) {
		const t = e.policyPath[i.length];
		if (t !== void 0) a.add(t);
	}
	return {
		kind: "keys",
		path: i,
		allowed: [...a],
		section: t,
		hint: n,
		scoped: r
	};
}
function rule(e, t = "", n) {
	const r = POLICY_RULE_METADATA.find((t) => t.policyPath.join(".") === e);
	if (r === void 0 || r.valueType !== "boolean" && r.valueType !== "string-list") throw new Error(`Unsupported posture shape rule: ${e}`);
	let i;
	if (n === "node-commands") i = { kind: n };
	else if (n !== void 0) {
		if (r.allowedValues === void 0) throw new Error(`Missing posture shape enum values: ${e}`);
		i = {
			kind: n,
			allowed: r.allowedValues
		};
	}
	return {
		kind: "rule",
		path: r.policyPath,
		metadata: r,
		valueName: t,
		style: i
	};
}
const workspace = [
	object("agents.workspace"),
	keys("agents.workspace", "agent workspace", "a supported agent workspace policy rule"),
	rule("agents.workspace.allowedAccess", "", "workspace-access"),
	rule("agents.workspace.denyTools", "", "workspace-tools")
];
const tools = [
	keys("tools", "tools", "a supported tools policy rule"),
	...[
		"profiles",
		"fs",
		"exec",
		"elevated",
		"alsoAllow"
	].map((e) => object(`tools.${e}`)),
	keys("tools.profiles", "tools", { key: "allow" }),
	rule("tools.profiles.allow", "tool profile id"),
	keys("tools.fs", "tools", { key: "requireWorkspaceOnly" }),
	rule("tools.fs.requireWorkspaceOnly"),
	keys("tools.exec", "tools", "a supported tools exec policy rule"),
	rule("tools.exec.allowSecurity", "exec security mode"),
	rule("tools.exec.requireAsk", "exec ask mode"),
	rule("tools.exec.allowHosts", "exec host"),
	keys("tools.elevated", "tools", { key: "allow" }),
	rule("tools.elevated.allow"),
	keys("tools.alsoAllow", "tools", { key: "expected" }),
	rule("tools.alsoAllow.expected", "tool id"),
	rule("tools.denyTools", "tool id or group")
];
const gatewaySections = [
	"exposure",
	"auth",
	"controlUi",
	"remote",
	"http",
	"nodes"
];
const shapes = {
	agents: [
		object("agents"),
		keys("agents", "agents", { key: "workspace" }),
		...workspace
	],
	workspace,
	tools,
	"scoped-tools": [
		keys("tools", "agent-scoped tools", "", true),
		...[
			"profiles",
			"fs",
			"exec",
			"elevated",
			"alsoAllow"
		].map((e) => keys(`tools.${e}`, "agent-scoped tools", "", true)),
		...tools
	],
	sandbox: [
		object("sandbox"),
		keys("sandbox", "sandbox", "a supported sandbox posture rule"),
		rule("sandbox.requireMode", "sandbox mode"),
		rule("sandbox.allowBackends", "sandbox backend id"),
		object("sandbox.containers"),
		object("sandbox.browser"),
		keys("sandbox.containers", "sandbox", "a supported sandbox container posture rule"),
		...POLICY_RULE_METADATA.filter((e) => e.policyPath[0] === "sandbox" && e.policyPath[1] === "containers").map((e) => rule(e.policyPath.join("."))),
		keys("sandbox.browser", "sandbox", "a supported sandbox browser posture rule"),
		rule("sandbox.browser.requireCdpSourceRange")
	],
	gateway: [
		object("gateway"),
		...gatewaySections.map((e) => object(`gateway.${e}`)),
		keys("gateway", "Gateway", "a supported Gateway policy section"),
		...gatewaySections.map((e) => keys(`gateway.${e}`, "Gateway", "a supported Gateway policy rule")),
		rule("gateway.exposure.allowNonLoopbackBind"),
		rule("gateway.exposure.allowTailscaleFunnel"),
		rule("gateway.auth.requireAuth"),
		rule("gateway.auth.requireExplicitRateLimit"),
		rule("gateway.controlUi.allowInsecure"),
		rule("gateway.remote.allow"),
		rule("gateway.http.requireUrlAllowlists"),
		rule("gateway.http.denyEndpoints", "", "http-endpoints"),
		rule("gateway.nodes.denyCommands", "", "node-commands")
	]
};
function posturePolicyShapeFinding(e, t, n) {
	if (t === void 0) return;
	const r = e === "workspace" ? "agents.workspace" : e === "scoped-tools" ? "tools" : e;
	const i = r.split(".").length;
	const a = createOrderedPolicyShape(t, {
		...n,
		propertyPrefix: n.propertyPrefix ?? r,
		targetPrefix: n.targetPrefix ?? r.replaceAll(".", "/")
	});
	function* findings() {
		for (const t of shapes[e]) {
			const n = t.path.slice(i).join(".");
			if (t.kind === "object") yield a.object(n);
			else if (t.kind === "keys") {
				const e = typeof t.hint === "string" ? t.hint : "{property}." + t.hint.key;
				yield a.keys(n, t.allowed, t.section, t.scoped ? "Move {unsupported} to top-level tools or use a supported scoped tools posture rule." : "Remove {unsupported} or use " + e + ".");
			} else if (t.metadata.valueType === "boolean") yield a.boolean(n, e === "gateway" ? "Fix {policy} so {property} is true or false." : void 0);
			else if (t.style === void 0) yield a.list(n, {
				allowed: t.metadata.allowedValues,
				valueName: t.valueName
			});
			else yield customListShapeFinding(a, n, t.style);
		}
	}
	return firstPolicyShapeFinding(findings());
}
function customListShapeFinding(e, t, n) {
	let r;
	let i;
	let a;
	switch (n.kind) {
		case "workspace-access":
			r = "Use workspace access values such as [\"none\", \"ro\"].";
			i = r;
			a = "must be none, ro, or rw.";
			break;
		case "workspace-tools":
			r = "Use tool ids such as [\"exec\", \"process\", \"write\", \"edit\", \"apply_patch\"].";
			i = "Use supported tool ids: {allowed}.";
			a = "must be a supported agent workspace tool id.";
			break;
		case "http-endpoints":
			r = "Use an array of endpoint ids such as [\"responses\"] or remove gateway.http.denyEndpoints.";
			i = "Use supported endpoint ids: {allowed}.";
			a = "must be a supported endpoint id.";
			break;
		case "node-commands":
			r = "Use an array of node command ids such as [\"system.run\"] or remove gateway.nodes.denyCommands.";
			i = "Use non-empty node command ids.";
			a = "must be a non-empty node command id.";
	}
	return e.list(t, {
		allowed: n.kind === "node-commands" ? void 0 : n.allowed,
		normalize: n.kind === "workspace-access" ? "raw" : "trim",
		array: {
			message: "{policy} {property} must be an array.",
			hint: r
		},
		entry: {
			message: "{policy} {property}[{index}] " + a,
			hint: i
		}
	});
}
//#endregion
//#region extensions/policy/src/doctor/scoped-policy-shape.ts
function scopedPolicyShapeFinding(e, t) {
	if (e === void 0) return;
	const n = createOrderedPolicyShape(e, {
		...t,
		propertyPrefix: "scopes",
		targetPrefix: "scopes"
	});
	if (!isRecord(e)) return n.object("", "Fix {policy} so scopes maps scope names to policy overlays with selectors such as agentIds.");
	const r = e;
	function* findings() {
		for (const [e, n] of Object.entries(r)) {
			const r = "scopes/" + ocPathSegment(e);
			const i = "scopes." + e;
			const a = createOrderedPolicyShape(n, {
				...t,
				propertyPrefix: i,
				targetPrefix: r
			});
			yield a.object("", "Fix {policy} so the named policy scope is an object.", true);
			const o = a.value("agentIds") !== void 0;
			const s = a.value("channelIds") !== void 0;
			if (!o && !s) yield a.finding("", {
				message: "{policy} {property} must define at least one selector.",
				hint: "List agentIds for agent-scoped policy or channelIds for channel-scoped ingress policy."
			});
			yield scopedSelectorShapeFinding(a, "agentIds", "agent");
			yield scopedSelectorShapeFinding(a, "channelIds", "channel");
			if (a.value("ingress") !== void 0 && !s) yield a.finding("ingress", {
				message: "{policy} {property} requires the channelIds selector.",
				hint: "Move global ingress rules to top-level ingress, or list channelIds for channel-scoped ingress policy."
			});
			if ([
				"agents",
				"dataHandling",
				"execApprovals",
				"tools",
				"sandbox"
			].some((e) => a.value(e) !== void 0) && !o) yield a.finding("", {
				message: "{policy} {property} uses agent-scoped sections without agentIds.",
				hint: "List agentIds for agents.workspace, dataHandling.memory, tools, or sandbox policy sections."
			});
			yield a.keys("", [
				"agentIds",
				"channelIds",
				"agents",
				"dataHandling",
				"execApprovals",
				"tools",
				"sandbox",
				"ingress"
			], "", "Use agentIds with agents.workspace, dataHandling.memory, execApprovals, tools, or sandbox, and channelIds with ingress.channels.", "{policy} {unsupported} is not a supported scoped policy section.");
			yield a.object("dataHandling", "Fix {policy} so the scoped dataHandling policy section is an object.");
			const c = a.value("dataHandling");
			if (isRecord(c)) yield scopedDataHandlingPolicyShapeFinding(c, {
				...t,
				targetPrefix: r,
				scopeName: e
			});
			yield a.object("agents", "Fix {policy} so the scoped agents policy section is an object.");
			yield a.keys("agents", ["workspace"], "", "Move the rule under agents.workspace or a supported scoped top-level section.", "{policy} {unsupported} is not supported by the agentIds selector.");
			const sectionParams = (e) => ({
				...t,
				targetPrefix: r + "/" + e.replaceAll(".", "/"),
				propertyPrefix: i + "." + e
			});
			yield posturePolicyShapeFinding("workspace", a.value("agents.workspace"), sectionParams("agents.workspace"));
			yield execApprovalsPolicyShapeFinding(a.value("execApprovals"), {
				...sectionParams("execApprovals"),
				allowDefaults: false
			});
			yield a.object("tools", "Fix {policy} so the scoped tools policy overlay is an object.");
			yield posturePolicyShapeFinding("scoped-tools", a.value("tools"), sectionParams("tools"));
			yield posturePolicyShapeFinding("sandbox", a.value("sandbox"), sectionParams("sandbox"));
			yield ingressPolicyShapeFinding(a.value("ingress"), {
				...sectionParams("ingress"),
				allowSession: false
			});
		}
		yield duplicateScopedPolicyFieldFinding(r, t);
	}
	return firstPolicyShapeFinding(findings());
}
function scopedSelectorShapeFinding(e, t, n) {
	const r = n + " id";
	const i = e.list(t, { valueName: r });
	if (i !== void 0) return i;
	const a = e.value(t);
	if (!Array.isArray(a)) return;
	if (a.length === 0) return e.finding(t, {
		message: "{policy} {property} must include at least one {valueName}.",
		hint: "Add one or more {valueName}s to {policy} {property}."
	}, { valueName: r });
	const o = /* @__PURE__ */ new Map();
	for (const [i, s] of a.entries()) {
		if (typeof s !== "string") continue;
		const a = n === "agent" ? normalizeAgentId(s) : normalizeLowercaseStringOrEmpty(s);
		const c = o.get(a);
		if (c !== void 0) return e.finding(t, {
			message: "{policy} {property}[{index}] duplicates {property}[" + c + "] after normalization.",
			hint: "List each {valueName} only once per named policy scope."
		}, {
			index: i,
			valueName: r
		});
		o.set(a, i);
	}
}
function hasValidScopedPolicy(e, t, n) {
	return isRecord(e) && scopedPolicyShapeFinding(e.scopes, {
		policyDocName: n,
		policyPath: t,
		policy: e
	}) === void 0;
}
//#endregion
//#region extensions/policy/src/doctor/exec-approval-findings.ts
function execApprovalsFindings(e, t, n, r, i, a) {
	if (!isRecord(e)) return [];
	const o = [];
	const s = r.execApprovals ?? [];
	const c = s.find((e) => e.kind === "defaults");
	const l = c?.security ?? "full";
	if (isRecord(e.execApprovals)) {
		const r = execApprovalsPolicyShapeFinding(e.execApprovals, {
			policyDocName: n,
			policyPath: t
		});
		if (r !== void 0) return [r];
		const u = execApprovalsFileFindings(e.execApprovals, {
			policyDocName: n,
			file: i,
			displayName: a,
			requirementBase: "execApprovals"
		});
		o.push(...u);
		if (u.length > 0) return o;
		o.push(...execApprovalsRuleFindings(e.execApprovals, {
			entries: s,
			defaultSecurity: l,
			defaults: c,
			displayName: a,
			fileDisplayName: i?.displayName,
			policyDocName: n,
			requirementBase: "execApprovals"
		}));
	}
	if (!hasValidScopedPolicy(e, t, n)) return o;
	const u = /* @__PURE__ */ new Set();
	for (const t of agentScopedPolicyTargets(e)) {
		if (!isRecord(t.overlay.execApprovals)) continue;
		const e = `scopes/${ocPathSegment(t.scopeName)}/execApprovals`;
		const r = execApprovalsFileFindings(t.overlay.execApprovals, {
			policyDocName: n,
			file: i,
			displayName: a,
			requirementBase: e
		});
		if (r.length > 0) {
			if (!u.has(t.scopeName)) {
				o.push(...r);
				u.add(t.scopeName);
			}
			continue;
		}
		o.push(...execApprovalsRuleFindings(t.overlay.execApprovals, {
			entries: s,
			defaultSecurity: l,
			defaults: c,
			displayName: a,
			fileDisplayName: i?.displayName,
			policyDocName: n,
			requirementBase: e,
			targetAgentId: t.agentId
		}));
	}
	return o;
}
function execApprovalsFileFindings(e, t) {
	const n = readBooleanPath(e, ["requireFile"]) === true;
	const r = n || execApprovalsPolicyNeedsArtifactEvidence(e);
	if (r && t.file === null) return [{
		checkId: CHECK_IDS.policyExecApprovalsMissing,
		severity: "error",
		message: `${EXEC_APPROVALS_POLICY_DOCUMENT_NAME} evidence is required by policy but was not found.`,
		source: "policy",
		path: t.displayName,
		target: EXEC_APPROVALS_POLICY_URI,
		requirement: `oc://${t.policyDocName}/${n ? `${t.requirementBase}/requireFile` : t.requirementBase}`,
		fixHint: "Restore the approved exec approvals artifact or update policy after review."
	}];
	if (t.file === null || t.file === void 0) return [];
	const i = parseExecApprovalsFile(t.file.raw);
	if (i.ok || !r) return [];
	return [{
		checkId: CHECK_IDS.policyExecApprovalsInvalid,
		severity: "error",
		message: `${t.file.displayName} could not be parsed: ${i.message}`,
		source: "policy",
		path: t.file.displayName,
		target: `oc://${t.file.ocDocName}`,
		requirement: `oc://${t.policyDocName}/${t.requirementBase}`,
		fixHint: `Fix ${EXEC_APPROVALS_POLICY_DOCUMENT_NAME} so it is valid JSON.`
	}];
}
function execApprovalsPolicyNeedsArtifactEvidence(e) {
	return isRecord(e.defaults) || isRecord(e.agents);
}
function execApprovalsRuleFindings(e, t) {
	const n = [];
	const r = new Set(readStringList(e, ["defaults", "allowSecurity"]));
	if (t.targetAgentId === void 0 && r.size > 0 && !r.has(t.defaultSecurity.toLowerCase())) n.push(execApprovalFinding(t.defaults, {
		checkId: CHECK_IDS.policyExecApprovalsDefaultSecurityUnapproved,
		message: `exec approvals defaults use unapproved security mode '${t.defaultSecurity}'.`,
		requirement: `oc://${t.policyDocName}/${t.requirementBase}/defaults/allowSecurity`,
		fixHint: "Set defaults.security to an approved mode or update policy after review."
	}));
	const i = new Set(readStringList(e, ["agents", "allowSecurity"]));
	if (i.size > 0) {
		const e = execApprovalAgentEntries(t.entries, t.defaults, "security", t.targetAgentId);
		for (const r of e) {
			const e = r.security ?? t.defaultSecurity;
			if (i.has(e.toLowerCase())) continue;
			n.push(execApprovalFinding(r, {
				checkId: CHECK_IDS.policyExecApprovalsAgentSecurityUnapproved,
				message: `exec approvals agent '${r.agentId ?? t.targetAgentId ?? "inherited defaults"}' uses unapproved security mode '${e}'.`,
				requirement: `oc://${t.policyDocName}/${t.requirementBase}/agents/allowSecurity`,
				fixHint: "Set the agent approval security mode to an approved value or update policy after review."
			}));
		}
	}
	if (readBooleanPath(e, ["agents", "allowAutoAllowSkills"]) === false) {
		const e = execApprovalAgentEntries(t.entries, t.defaults, "autoAllowSkills", t.targetAgentId);
		for (const r of e) {
			if (r.autoAllowSkills !== true) continue;
			n.push(execApprovalFinding(r, {
				checkId: CHECK_IDS.policyExecApprovalsAutoAllowSkillsEnabled,
				message: `exec approvals agent '${r.agentId ?? t.targetAgentId ?? "inherited defaults"}' enables autoAllowSkills outside policy.`,
				requirement: `oc://${t.policyDocName}/${t.requirementBase}/agents/allowAutoAllowSkills`,
				fixHint: "Set autoAllowSkills to false or update policy after reviewing implicit skill CLI trust."
			}));
		}
	}
	const a = readExecApprovalAllowlistRequirements(e, [
		"agents",
		"allowlist",
		"expected"
	]);
	if (a !== void 0) {
		const e = new Set(a.map((e) => e.key));
		const r = /* @__PURE__ */ new Map();
		for (const e of execApprovalAllowlistEntries(t.entries, t.targetAgentId)) {
			if (e.pattern === void 0) continue;
			const t = execApprovalAllowlistRequirementKey(e.pattern, e.argPattern);
			if (!r.has(t)) r.set(t, e);
		}
		for (const e of a.toSorted((e, t) => e.key.localeCompare(t.key))) if (!r.has(e.key)) {
			const r = `oc://${t.policyDocName}/${t.requirementBase}/agents/allowlist/expected`;
			const i = execApprovalAllowlistMissingTarget(t.targetAgentId);
			n.push({
				checkId: CHECK_IDS.policyExecApprovalsAllowlistMissing,
				severity: "error",
				message: `exec approvals allowlist is missing expected pattern '${formatExecApprovalAllowlistEntry(e)}'.`,
				source: "policy",
				path: t.fileDisplayName ?? t.displayName,
				target: i,
				requirement: r,
				fixHint: "Add the expected approval pattern or update policy after review."
			});
		}
		for (const i of [...r.keys()].toSorted()) {
			if (e.has(i)) continue;
			const a = r.get(i);
			n.push(execApprovalFinding(a, {
				checkId: CHECK_IDS.policyExecApprovalsAllowlistUnexpected,
				message: `exec approvals allowlist has unexpected pattern '${formatExecApprovalAllowlistEntry(a)}'.`,
				requirement: `oc://${t.policyDocName}/${t.requirementBase}/agents/allowlist/expected`,
				fixHint: "Remove the unexpected approval pattern or update policy after review."
			}));
		}
	}
	return n;
}
function execApprovalAllowlistEntries(e, t) {
	return e.filter((e) => e.kind === "allowlist" && (t === void 0 || e.agentId !== void 0 && (normalizeAgentId(e.agentId) === normalizeAgentId(t) || e.agentId === "*")));
}
function execApprovalFinding(e, t) {
	return policyEvidenceFinding({ source: e?.source ?? "oc://exec-approvals.json" }, t, { path: EXEC_APPROVALS_POLICY_DOCUMENT_NAME });
}
//#endregion
//#region extensions/policy/src/doctor/policy-section-targets.ts
function* policySectionTargets(e, t, n, r) {
	if (!isRecord(e)) return;
	const i = r.split("/");
	const a = getPolicyPath(e, i);
	const o = {
		policyPath: t,
		policyDocName: n
	};
	const s = r === "ingress" ? ingressPolicyShapeFinding(a, o) : posturePolicyShapeFinding(r === "agents/workspace" ? "agents" : r, r === "agents/workspace" ? e.agents : a, o);
	if (r === "agents/workspace" && s !== void 0) return;
	if (isRecord(a) && s === void 0) yield {
		policy: a,
		requirementBase: r
	};
	if (!hasValidScopedPolicy(e, t, n)) return;
	const c = r === "ingress" ? "channelIds" : "agentIds";
	for (const [t, n] of scopedPolicyOverlays(e)) {
		const e = getPolicyPath(n, i);
		if (!isRecord(e)) continue;
		for (const i of normalizePolicySelectorValues(n[c], c)) yield {
			policy: e,
			requirementBase: `scopes/${ocPathSegment(t)}/${r}`,
			selectorId: i
		};
	}
}
//#endregion
//#region extensions/policy/src/doctor/routing-shapes.ts
const ROUTING_HINT = "Fix {policy} so routing uses the documented policy syntax.";
function routingPolicyShapeFinding(e, t) {
	if (e === void 0) return;
	const n = createOrderedPolicyShape(e, {
		...t,
		propertyPrefix: "routing",
		targetPrefix: "routing"
	});
	function* findings() {
		yield n.object("", ROUTING_HINT, true);
		yield routingKeys(n, "", [
			"probes",
			"requireBindings",
			"requireConfiguredChannels"
		]);
		for (const e of ["requireBindings", "requireConfiguredChannels"]) yield n.boolean(e, ROUTING_HINT);
		const e = n.value("probes");
		if (e === void 0) return;
		if (!Array.isArray(e)) {
			yield routingFinding(n, "probes", "must be an array.");
			return;
		}
		const r = /* @__PURE__ */ new Set();
		for (const [n, i] of e.entries()) {
			const e = `routing/probes/#${n}`;
			const a = createOrderedPolicyShape(i, {
				...t,
				propertyPrefix: `routing.probes[${n}]`,
				targetPrefix: e
			});
			yield a.object("", ROUTING_HINT, true);
			yield routingKeys(a, "", [
				"expect",
				"id",
				"route"
			]);
			yield a.string("id", ROUTING_HINT, true);
			const o = a.value("id");
			if (typeof o === "string") {
				if (r.has(o.trim())) yield policyShapeFinding(t.policyPath, `oc://${t.policyDocName}/${e}/id`, `${t.policyPath} routing check id ${o.trim()} must be unique.`, `Fix ${t.policyPath} so routing uses the documented policy syntax.`);
				r.add(o.trim());
			}
			yield* routeShapeFindings(a);
			yield* expectShapeFindings(a);
		}
	}
	return firstPolicyShapeFinding(findings());
}
function* routeShapeFindings(e) {
	yield e.object("route", ROUTING_HINT, true);
	yield routingKeys(e, "route", [
		"accountId",
		"channel",
		"guildId",
		"memberRoleIds",
		"parentPeer",
		"peer",
		"teamId"
	]);
	yield e.string("route.channel", ROUTING_HINT, true);
	for (const t of [
		"accountId",
		"guildId",
		"teamId"
	]) yield e.string(`route.${t}`, ROUTING_HINT);
	for (const t of ["peer", "parentPeer"]) {
		const n = `route.${t}`;
		if (e.value(n) === void 0) continue;
		yield e.object(n, ROUTING_HINT, true);
		yield routingKeys(e, n, ["id", "kind"]);
		const r = e.value(`${n}.kind`);
		if (typeof r !== "string" || ![
			"channel",
			"direct",
			"group"
		].includes(r)) yield routingFinding(e, `${n}.kind`, "must be direct, group, or channel.");
		yield e.string(`${n}.id`, ROUTING_HINT, true);
	}
	const t = e.value("route.memberRoleIds");
	if (t !== void 0 && (!Array.isArray(t) || t.length === 0 || t.some((e) => !hasNonEmptyString(e)) || new Set(t.map((e) => String(e).trim())).size !== t.length)) yield routingFinding(e, "route.memberRoleIds", "must contain unique non-empty strings.");
}
function* expectShapeFindings(e) {
	yield e.object("expect", ROUTING_HINT, true);
	yield routingKeys(e, "expect", ["agentId", "matchedBy"]);
	yield e.string("expect.agentId", ROUTING_HINT, true);
	const t = e.value("expect.matchedBy");
	if (t !== void 0 && !validPolicyRoutingMatchKinds(t)) yield routingFinding(e, "expect.matchedBy", "must contain unique supported match kinds.");
}
function routingKeys(e, t, n) {
	return e.keys(t, n, "", ROUTING_HINT, "{policy} {unsupported} is not supported.");
}
function routingFinding(e, t, n) {
	return e.finding(t, {
		message: "{policy} {property} " + n,
		hint: ROUTING_HINT
	});
}
//#endregion
//#region extensions/policy/src/doctor/policy-shape.ts
function policyContainerShapeFindings(e, t, n) {
	if (!isRecord(e)) return [policyShapeFinding(t, "oc://" + n, t + " must contain a policy object.", "Fix " + t + " so the top-level policy is an object.")];
	const r = e;
	const i = {
		policyPath: t,
		policyDocName: n
	};
	const a = createOrderedPolicyShape(r, i);
	function* allowDeny(e, t) {
		yield a.object(e);
		yield a.keys(e, ["allow", "deny"], "", "Remove {unsupported} or use {property}.allow or {property}.deny.", "{policy} {unsupported} is not supported in policy.");
		for (const n of ["allow", "deny"]) yield a.list(e + "." + n, {
			valueName: t,
			entry: {
				message: "{policy} {property}[{index}] must be a non-empty string.",
				hint: "Fix {policy} so each {property} entry is a {valueName}."
			}
		});
	}
	function* findings() {
		yield a.keys("", SUPPORTED_POLICY_SECTIONS, "", "Remove {key} or use a supported policy section.", "{policy} {key} is not a supported policy section.");
		yield a.object("tools");
		yield posturePolicyShapeFinding("tools", r.tools, i);
		yield a.object("channels");
		yield a.keys("channels", ["denyRules"], "channel", "Remove {unsupported} or use channels.denyRules.");
		yield a.object("mcp");
		yield a.keys("mcp", ["servers"], "MCP", "Remove {unsupported} or use mcp.servers.");
		yield a.object("dataHandling");
		yield* allowDeny("mcp.servers", "MCP server id");
		yield a.object("models");
		yield a.keys("models", ["providers"], "model", "Remove {unsupported} or use models.providers.");
		yield* allowDeny("models.providers", "model provider id");
		yield a.object("network");
		yield a.keys("network", ["privateNetwork"], "network", "Remove {unsupported} or use network.privateNetwork.");
		yield a.object("network.privateNetwork");
		yield a.keys("network.privateNetwork", ["allow"], "network", "Remove {unsupported} or use network.privateNetwork.allow.");
		yield a.boolean("network.privateNetwork.allow", "Fix {policy} so {property} is true or false.");
		yield a.object("secrets");
		yield a.keys("secrets", [
			"allowInsecureProviders",
			"denySources",
			"requireManagedProviders"
		], "secrets", "Remove {unsupported} or use a supported secrets policy rule.");
		yield a.object("auth");
		yield a.keys("auth", ["profiles"], "auth", "Remove {unsupported} or use auth.profiles.");
		yield a.object("auth.profiles");
		yield a.keys("auth.profiles", ["allowModes", "requireMetadata"], "auth profile", "Remove {unsupported} or use a supported auth profile policy rule.");
		yield execApprovalsPolicyShapeFinding(r.execApprovals, i);
		yield posturePolicyShapeFinding("sandbox", r.sandbox, i);
		yield ingressPolicyShapeFinding(r.ingress, i);
		yield posturePolicyShapeFinding("gateway", r.gateway, i);
		yield routingPolicyShapeFinding(r.routing, i);
		yield posturePolicyShapeFinding("agents", r.agents, i);
		yield scopedPolicyShapeFinding(r.scopes, {
			...i,
			policy: r
		});
	}
	const o = firstPolicyShapeFinding(findings());
	return o === void 0 ? [] : [o];
}
//#endregion
//#region extensions/policy/src/doctor/routing-findings.ts
function routingFindings(e, t, n, r) {
	if (e === void 0 || r.routing === void 0) return [];
	const i = [];
	if (e.requireBindings === true && r.routing.bindings.length === 0) i.push({
		checkId: CHECK_IDS.policyRoutingBindingsRequired,
		severity: "error",
		message: "Routing policy requires at least one channel route binding, but none are configured.",
		source: "policy",
		path: t,
		target: "oc://openclaw.config/bindings",
		requirement: `oc://${n}/routing/requireBindings`,
		fixHint: "Add an intentional route binding or update the policy after review."
	});
	if (e.requireConfiguredChannels === true) {
		const e = new Set(r.channels.map((e) => e.id.toLowerCase()));
		for (const a of r.routing.bindings) {
			if (e.has(a.channel.toLowerCase())) continue;
			i.push({
				checkId: CHECK_IDS.policyRoutingBindingChannelUnconfigured,
				severity: "error",
				message: `Route binding ${a.index} names unconfigured channel ${a.channel}.`,
				source: "policy",
				path: t,
				target: `oc://openclaw.config/bindings/#${a.index}`,
				requirement: `oc://${n}/routing/requireConfiguredChannels`,
				fixHint: `Configure channels.${a.channel}, correct the binding channel, or update the policy after review.`
			});
		}
	}
	for (const a of e.probes ?? []) {
		const e = r.routing.probes.find((e) => e.id === a.id);
		if (e === void 0) continue;
		const o = `oc://policy/routing/probes/${ocPathSegment(a.id)}/result`;
		const s = `oc://${n}/routing/probes/${ocPathSegment(a.id)}/expect`;
		if (normalizeAgentId(e.agentId) !== normalizeAgentId(a.expect.agentId)) i.push({
			checkId: CHECK_IDS.policyRoutingAgentMismatch,
			severity: "error",
			message: `Routing check ${a.id} resolved to agent ${e.agentId}, not ${a.expect.agentId}.`,
			source: "policy",
			path: t,
			target: o,
			requirement: s,
			fixHint: "Review the route bindings and expected destination before changing either one."
		});
		if (a.expect.matchedBy !== void 0 && !a.expect.matchedBy.includes(e.matchedBy)) i.push({
			checkId: CHECK_IDS.policyRoutingMatchKindMismatch,
			severity: "error",
			message: `Routing check ${a.id} matched by ${e.matchedBy}, which is not an expected match kind.`,
			source: "policy",
			path: t,
			target: o,
			requirement: s,
			fixHint: "Restore the intended binding specificity or update the accepted match kinds after review."
		});
	}
	return i;
}
//#endregion
//#region extensions/policy/src/doctor/sandbox-findings.ts
function sandboxPostureFindings(e, t, n, r) {
	const i = [];
	const a = r.sandboxPosture ?? [];
	for (const r of policySectionTargets(e, t, n, "sandbox")) {
		const e = r.selectorId;
		const t = e === void 0 ? a : a.filter((t) => scopedSandboxAgentMatches(t, e, a));
		const o = r.policy;
		const s = r.requirementBase;
		const c = [{
			kind: "mode",
			key: "requireMode",
			checkId: CHECK_IDS.policySandboxModeUnapproved,
			fixHint: "Set agents.defaults.sandbox.mode or agents.entries.<id>.sandbox.mode to an approved value."
		}, {
			kind: "backend",
			key: "allowBackends",
			checkId: CHECK_IDS.policySandboxBackendUnapproved,
			fixHint: "Use an approved sandbox backend or update policy after review."
		}].flatMap((e) => {
			const r = new Set(readStringList(o, [e.key]));
			if (r.size === 0) return [];
			return t.filter((t) => t.kind === e.kind).filter((e) => typeof e.value === "string" && !r.has(e.value.toLowerCase())).map((t) => policyEvidenceFinding(t, {
				checkId: e.checkId,
				message: `${sandboxPostureLabel(t)} uses unapproved sandbox ${e.kind} '${t.value ?? ""}'.`,
				requirement: `oc://${n}/${s}/${e.key}`,
				fixHint: e.fixHint
			}));
		});
		const l = SANDBOX_CONTAINER_POLICY_RULES.filter((e) => readBooleanPath(o, ["containers", e.key]) === true);
		c.push(...t.filter((e) => e.kind === "backend").filter((e) => typeof e.value === "string" && !isObservableContainerSandboxBackend(e.value)).flatMap((e) => l.map((t) => policyEvidenceFinding(e, {
			checkId: CHECK_IDS.policySandboxContainerPostureUnobservable,
			message: `${sandboxPostureLabel(e)} uses sandbox backend '${e.value ?? ""}', which cannot observe ${t.label}.`,
			requirement: `oc://${n}/${s}/containers/${t.key}`,
			fixHint: "Use an observable container backend for this sandbox or remove the container posture rule."
		}))));
		const u = [
			{
				path: ["containers", "denyHostNetwork"],
				kind: "containerNetwork",
				violates: (e) => typeof e.value === "string" && e.value.toLowerCase() === "host",
				checkId: CHECK_IDS.policySandboxContainerHostNetworkDenied,
				message: (e) => `${sandboxPostureLabel(e)} uses host container network mode.`,
				fixHint: "Change the container network mode or update policy after review."
			},
			{
				path: ["containers", "denyContainerNamespaceJoin"],
				kind: "containerNetwork",
				violates: (e) => typeof e.value === "string" && e.value.toLowerCase().startsWith("container:"),
				checkId: CHECK_IDS.policySandboxContainerNamespaceJoinDenied,
				message: (e) => `${sandboxPostureLabel(e)} joins another container network namespace '${e.value ?? ""}'.`,
				fixHint: "Change the container network mode or update policy after review."
			},
			{
				path: ["containers", "requireReadOnlyMounts"],
				kind: "containerMount",
				violates: (e) => e.bindMode !== "ro",
				checkId: CHECK_IDS.policySandboxContainerMountModeRequired,
				message: (e) => `${sandboxPostureLabel(e)} has container mount '${e.bind ?? ""}' with mode '${e.bindMode ?? "unknown"}'.`,
				fixHint: "Set the mount mode to read-only or update policy after review."
			},
			{
				path: ["containers", "denyContainerRuntimeSocketMounts"],
				kind: "containerMount",
				violates: (e) => bindHostLooksLikeContainerRuntimeSocket(e.bindHost),
				checkId: CHECK_IDS.policySandboxContainerRuntimeSocketMount,
				message: (e) => `${sandboxPostureLabel(e)} binds host container runtime socket '${e.bindHost ?? ""}'.`,
				fixHint: "Remove the container runtime socket bind or update policy after review."
			},
			{
				path: ["containers", "denyUnconfinedProfiles"],
				kind: "containerSecurityProfile",
				violates: (e) => typeof e.value === "string" && e.value.toLowerCase() === "unconfined",
				checkId: CHECK_IDS.policySandboxContainerUnconfinedProfile,
				message: (e) => `${sandboxPostureLabel(e)} sets container ${e.profile ?? "security"} profile to unconfined.`,
				fixHint: "Remove the unconfined container profile or update policy after review."
			},
			{
				path: ["browser", "requireCdpSourceRange"],
				kind: "browserCdpSourceRange",
				violates: (e) => e.value === void 0,
				checkId: CHECK_IDS.policySandboxBrowserCdpSourceRangeMissing,
				message: (e) => `${sandboxPostureLabel(e)} enables sandbox browser without cdpSourceRange.`,
				fixHint: "Set agents.*.sandbox.browser.cdpSourceRange or update policy after review."
			}
		];
		c.push(...policyEvidenceRuleFindings(t, u.filter((e) => readBooleanPath(o, e.path) === true), n, s));
		i.push(...c);
	}
	return i;
}
function scopedSandboxAgentMatches(e, t, n) {
	if (scopedAgentIdMatches(e.agentId, t)) return true;
	return e.scope === "defaults" && !scopedSandboxDefaultDisabledForAgent(e, t, n) && !n.some((n) => n.scope === "agent" && sandboxPostureEntriesDescribeSameField(n, e) && scopedAgentIdMatches(n.agentId, t));
}
function scopedSandboxDefaultDisabledForAgent(e, t, n) {
	if (sandboxEntryRequiresContainerBackend(e)) {
		const e = n.find((e) => e.scope === "agent" && e.kind === "backend" && scopedAgentIdMatches(e.agentId, t));
		if (typeof e?.value === "string" && !isObservableContainerSandboxBackend(e.value)) return true;
	}
	if (sandboxEntryRequiresBrowser(e)) {
		if (n.find((e) => e.scope === "agent" && e.kind === "browserCdpSourceRange" && scopedAgentIdMatches(e.agentId, t))?.value === false) return true;
	}
	return false;
}
function sandboxEntryRequiresContainerBackend(e) {
	return e.kind === "containerNetwork" && e.networkSurface === "docker" || e.kind === "containerSecurityProfile" || e.kind === "containerMount" && e.bindSurface === "docker";
}
function sandboxEntryRequiresBrowser(e) {
	return e.kind === "browserCdpSourceRange" || e.kind === "containerNetwork" && e.networkSurface === "browser" || e.kind === "containerMount" && e.bindSurface === "browser";
}
function sandboxPostureEntriesDescribeSameField(e, t) {
	return e.kind === t.kind && e.bindSurface === t.bindSurface && e.networkSurface === t.networkSurface && e.profile === t.profile;
}
function isObservableContainerSandboxBackend(e) {
	return e.toLowerCase() === "docker" || e.toLowerCase() === "podman";
}
function sandboxPostureLabel(e) {
	return e.agentId === void 0 ? "default sandbox config" : `agent '${e.agentId}'`;
}
const CONTAINER_RUNTIME_SOCKET_BASENAMES = /* @__PURE__ */ new Set([
	"containerd.sock",
	"docker.sock",
	"podman.sock"
]);
function bindHostLooksLikeContainerRuntimeSocket(e) {
	if (e === void 0) return false;
	const t = e.replaceAll("\\", "/").toLowerCase().split("/").at(-1) ?? "";
	return CONTAINER_RUNTIME_SOCKET_BASENAMES.has(t);
}
//#endregion
//#region extensions/policy/src/doctor/scopes/gateway.ts
function gatewayExposureFindings(e, t, n) {
	const r = [
		{
			path: ["exposure", "allowNonLoopbackBind"],
			enabled: false,
			violates: (e) => e.kind === "bind" && e.nonLoopback === true,
			checkId: CHECK_IDS.policyGatewayNonLoopbackBind,
			message: (e) => e.explicit === false ? "Gateway bind is omitted while the runtime default can permit non-loopback exposure." : `Gateway bind setting '${e.id}' permits non-loopback exposure.`,
			fixHint: "Use gateway.bind=loopback or update policy after review."
		},
		{
			path: ["auth", "requireAuth"],
			enabled: true,
			violates: (e) => e.kind === "auth" && e.value === "none",
			checkId: CHECK_IDS.policyGatewayAuthDisabled,
			message: () => "Gateway authentication is disabled.",
			fixHint: "Set gateway.auth.mode to token, password, or trusted-proxy."
		},
		{
			path: ["auth", "requireExplicitRateLimit"],
			enabled: true,
			violates: (e) => e.kind === "authRateLimit" && e.explicit !== true,
			checkId: CHECK_IDS.policyGatewayRateLimitMissing,
			message: () => "Gateway authentication rate-limit posture is not explicit.",
			fixHint: "Configure gateway.auth.rateLimit or update policy after review."
		},
		{
			path: ["controlUi", "allowInsecure"],
			enabled: false,
			violates: (e) => e.kind === "controlUi" && e.value === true && (e.id === "gateway-control-ui-insecure-auth" || e.id === "gateway-control-ui-device-auth-disabled" || e.id === "gateway-control-ui-host-origin-fallback"),
			checkId: CHECK_IDS.policyGatewayControlUiInsecure,
			message: (e) => `Gateway Control UI insecure toggle '${e.id}' is enabled.`,
			fixHint: "Disable the insecure Control UI toggle or update policy after review."
		},
		{
			path: ["exposure", "allowTailscaleFunnel"],
			enabled: false,
			violates: (e) => e.kind === "tailscale" && e.value === "funnel",
			checkId: CHECK_IDS.policyGatewayTailscaleFunnel,
			message: () => "Gateway Tailscale Funnel exposure is enabled.",
			fixHint: "Use tailscale serve/off or update policy after review."
		},
		{
			path: ["remote", "allow"],
			enabled: false,
			violates: (e) => e.kind === "remote",
			checkId: CHECK_IDS.policyGatewayRemoteEnabled,
			message: (e) => `Gateway remote posture '${e.id}' is enabled.`,
			fixHint: "Disable remote gateway mode/config or update policy after review."
		}
	];
	return [
		...policyEvidenceRuleFindings(n.gatewayExposure ?? [], r.filter((t) => readBooleanPath(e, ["gateway", ...t.path]) === t.enabled), t, "gateway"),
		...gatewayHttpEndpointFindings(e, t, n),
		...gatewayHttpUrlFetchFindings(e, t, n),
		...gatewayNodeCommandFindings(e, t, n)
	];
}
function gatewayHttpEndpointFindings(e, t, n) {
	const r = new Set(readStringList(e, [
		"gateway",
		"http",
		"denyEndpoints"
	]));
	if (r.size === 0) return [];
	return (n.gatewayExposure ?? []).filter((e) => e.kind === "httpEndpoint" && e.endpoint !== void 0 && r.has(e.endpoint.toLowerCase())).map((e) => {
		return policyEvidenceFinding(e, {
			checkId: CHECK_IDS.policyGatewayHttpEndpointEnabled,
			message: `Gateway HTTP endpoint '${e.endpoint ?? e.id}' is denied by policy.`,
			requirement: `oc://${t}/gateway/http/denyEndpoints`,
			fixHint: "Disable the HTTP endpoint or update policy after review."
		});
	});
}
function gatewayHttpUrlFetchFindings(e, t, n) {
	if (readBooleanPath(e, [
		"gateway",
		"http",
		"requireUrlAllowlists"
	]) !== true) return [];
	return (n.gatewayExposure ?? []).filter((e) => e.kind === "httpUrlFetch" && e.hasAllowlist !== true).map((e) => {
		return policyEvidenceFinding(e, {
			checkId: CHECK_IDS.policyGatewayHttpUrlFetchUnrestricted,
			message: `Gateway HTTP URL-fetch input '${e.id}' has no URL allowlist.`,
			requirement: `oc://${t}/gateway/http/requireUrlAllowlists`,
			fixHint: "Add a urlAllowlist for this URL-fetch input or update policy after review."
		});
	});
}
function gatewayNodeCommandFindings(e, t, n) {
	if (!hasValidOptionalStringList(e, [
		"gateway",
		"nodes",
		"denyCommands"
	])) return [];
	const r = readStringList(e, [
		"gateway",
		"nodes",
		"denyCommands"
	], { lowercase: false });
	if (r.length === 0) return [];
	const i = new Set((n.gatewayExposure ?? []).filter((e) => e.kind === "nodeDenyCommand" && e.command !== void 0).map((e) => e.command));
	return r.filter((e) => !i.has(e)).map((e) => {
		return policyEvidenceFinding({ source: "oc://openclaw.config/gateway/nodes/commands/deny" }, {
			checkId: CHECK_IDS.policyGatewayNodeCommandDenied,
			message: `Gateway node command '${e}' is denied by policy but not denied by OpenClaw config.`,
			requirement: `oc://${t}/gateway/nodes/denyCommands`,
			fixHint: `Add '${e}' to gateway.nodes.commands.deny or update policy after review.`
		});
	});
}
function hasValidOptionalStringList(e, t) {
	const n = getPolicyPath(e, t);
	return n === void 0 || Array.isArray(n) && n.every((e) => typeof e === "string" && e.trim() !== "");
}
//#endregion
//#region extensions/policy/src/doctor/scopes/model-network.ts
function mcpServerFindings(e, t, n) {
	const r = new Set(readStringList(e, [
		"mcp",
		"servers",
		"deny"
	], { lowercase: false }));
	const i = new Set(readStringList(e, [
		"mcp",
		"servers",
		"allow"
	], { lowercase: false }));
	return n.mcpServers.flatMap((e) => {
		const n = r.has(e.id);
		if (!n && (i.size === 0 || i.has(e.id))) return [];
		return [policyEvidenceFinding(e, {
			checkId: n ? CHECK_IDS.policyDeniedMcpServer : CHECK_IDS.policyUnapprovedMcpServer,
			message: n ? `MCP server '${e.id}' is denied by policy.` : `MCP server '${e.id}' is not in the policy allowlist.`,
			requirement: `oc://${t}/mcp/servers/${n ? "deny" : "allow"}`,
			fixHint: n ? "Remove this configured MCP server or update the policy after review." : "Use an approved MCP server or update the policy after review."
		})];
	});
}
function modelProviderFindings(e, t, n) {
	const r = new Set(readModelProviderPolicyList(e, [
		"models",
		"providers",
		"deny"
	]));
	const i = new Set(readModelProviderPolicyList(e, [
		"models",
		"providers",
		"allow"
	]));
	return [...n.modelProviders, ...n.modelRefs].flatMap((e) => {
		const n = "ref" in e;
		const a = n ? e.provider : e.id;
		const o = r.has(a);
		if (!o && (i.size === 0 || i.has(a))) return [];
		const s = n ? `Model ref '${e.ref}' uses ${o ? "denied" : "unapproved"} provider '${a}'.` : `Model provider '${a}' is ${o ? "denied by policy" : "not in the policy allowlist"}.`;
		return [policyEvidenceFinding(e, {
			checkId: o ? CHECK_IDS.policyDeniedModelProvider : CHECK_IDS.policyUnapprovedModelProvider,
			message: s,
			requirement: `oc://${t}/models/providers/${o ? "deny" : "allow"}`,
			fixHint: n ? "Select an approved model provider or update the policy after review." : o ? "Remove this configured provider or update the policy after review." : "Use an approved model provider or update the policy after review."
		})];
	});
}
function readModelProviderPolicyList(e, t) {
	return readStringList(e, t).map((e) => normalizeProviderId(e));
}
function networkFindings(e, t, n) {
	if (readBooleanPath(e, [
		"network",
		"privateNetwork",
		"allow"
	]) !== false) return [];
	return n.network.filter((e) => e.value).map((e) => {
		return policyEvidenceFinding(e, {
			checkId: CHECK_IDS.policyPrivateNetworkAccess,
			message: `Network setting '${e.id}' allows private-network access.`,
			requirement: `oc://${t}/network/privateNetwork/allow`,
			fixHint: "Disable this private-network access setting or update policy after review."
		});
	});
}
//#endregion
//#region extensions/policy/src/doctor/tool-findings.ts
function toolPostureFindings(e, t, n, r) {
	const i = [];
	const a = r.toolPosture ?? [];
	for (const r of policySectionTargets(e, t, n, "tools")) {
		const e = r.selectorId;
		const t = e === void 0 ? a : a.filter((t) => scopedAgentEvidenceMatches(t, e, a, t.scope === "global"));
		const o = [
			{
				path: ["profiles", "allow"],
				kind: "profile",
				checkId: CHECK_IDS.policyToolsProfileUnapproved,
				message: (e) => `${toolPostureLabel(e)} uses unapproved tool profile '${e.value ?? ""}'.`,
				fixHint: "Use an approved tools.profile value or update policy after review."
			},
			{
				path: ["fs", "requireWorkspaceOnly"],
				kind: "fsWorkspaceOnly",
				required: true,
				checkId: CHECK_IDS.policyToolsFsWorkspaceOnlyRequired,
				message: (e) => `${toolPostureLabel(e)} does not require workspace-only filesystem tools.`,
				fixHint: "Set tools.fs.workspaceOnly=true or update policy after review."
			},
			...[
				[
					"allowSecurity",
					"execSecurity",
					"exec security",
					CHECK_IDS.policyToolsExecSecurityUnapproved
				],
				[
					"requireAsk",
					"execAsk",
					"exec ask",
					CHECK_IDS.policyToolsExecAskUnapproved
				],
				[
					"allowHosts",
					"execHost",
					"exec host",
					CHECK_IDS.policyToolsExecHostUnapproved
				]
			].map(([e, t, n, r]) => ({
				path: ["exec", e],
				kind: t,
				checkId: r,
				message: (e) => `${toolPostureLabel(e)} uses unapproved ${n} '${e.value ?? ""}'.`,
				fixHint: "Adjust the configured tool posture or update policy after review."
			})),
			{
				path: ["elevated", "allow"],
				kind: "elevatedEnabled",
				required: false,
				checkId: CHECK_IDS.policyToolsElevatedEnabled,
				message: (e) => `${toolPostureLabel(e)} permits elevated tool mode.`,
				fixHint: "Set tools.elevated.enabled=false or update policy after review."
			}
		];
		i.push(...o.flatMap((e) => {
			const i = new Set(readStringList(r.policy, e.path));
			if (e.required === void 0 ? i.size === 0 : readBooleanPath(r.policy, e.path) !== e.required) return [];
			return policyEvidenceRuleFindings(t, [{
				...e,
				violates: (t) => e.required === void 0 ? typeof t.value === "string" && !i.has(t.value.toLowerCase()) : t.value !== e.required
			}], n, r.requirementBase);
		}));
		if ((isRecord(r.policy.alsoAllow) ? r.policy.alsoAllow : {}).expected !== void 0) {
			const e = new Set(readStringList(r.policy, ["alsoAllow", "expected"]).toSorted());
			for (const a of t.filter((e) => e.kind === "alsoAllow")) {
				const t = new Set(normalizeStringEntriesLower(a.entries).toSorted());
				for (const o of e) {
					if (t.has(o)) continue;
					i.push(policyEvidenceFinding(a, {
						checkId: CHECK_IDS.policyToolsAlsoAllowMissing,
						message: `${toolPostureLabel(a)} is missing expected tools.alsoAllow entry '${o}'.`,
						requirement: `oc://${n}/${r.requirementBase}/alsoAllow/expected`,
						fixHint: "Add the expected tools.alsoAllow entry or update policy after review."
					}));
				}
				for (const o of t) {
					if (e.has(o)) continue;
					i.push(policyEvidenceFinding(a, {
						checkId: CHECK_IDS.policyToolsAlsoAllowUnexpected,
						message: `${toolPostureLabel(a)} has unexpected tools.alsoAllow entry '${o}'.`,
						requirement: `oc://${n}/${r.requirementBase}/alsoAllow/expected`,
						fixHint: "Remove the unexpected tools.alsoAllow entry or update policy after review."
					}));
				}
			}
		}
		const s = readStringList(r.policy, ["denyTools"]);
		if (s.length > 0) {
			const e = uniqueStrings(s.flatMap(expandPolicyToolRequirement));
			for (const a of t.filter((e) => e.kind === "deny")) for (const t of e) {
				if (toolListCoversTool(a.entries ?? [], t)) continue;
				i.push(policyEvidenceFinding(a, {
					checkId: CHECK_IDS.policyToolsRequiredDenyMissing,
					message: `${toolPostureLabel(a)} does not deny required tool '${t}'.`,
					requirement: `oc://${n}/${r.requirementBase}/denyTools`,
					fixHint: "Add the tool or group to tools.deny/agents.entries.<id>.tools.deny, or update policy after review."
				}));
			}
		}
	}
	return i;
}
function toolPostureLabel(e) {
	return e.agentId === void 0 ? "global tools config" : `agent '${e.agentId}'`;
}
function toolMetadataFinding(e, t, n, r, i) {
	return policyEvidenceFinding(e, {
		checkId: n,
		message: r,
		requirement: `oc://${t}/tools/requireMetadata`,
		fixHint: i
	}, {
		path: "AGENTS.md",
		line: e.line
	});
}
const TOOL_METADATA_CHECKS = [
	{
		metadata: "risk",
		issue: (e) => e.risk === void 0 ? [
			CHECK_IDS.policyMissingToolRisk,
			`AGENTS.md tool '${e.id}' has no explicit risk classification.`,
			"Declare risk:low, risk:medium, risk:high, risk:critical, or an R0-R5 review alias."
		] : void 0
	},
	{
		metadata: "risk",
		issue: (e) => e.risk !== void 0 && !KNOWN_RISK_LEVELS.some((t) => t === e.risk) ? [
			CHECK_IDS.policyUnknownToolRisk,
			`AGENTS.md tool '${e.id}' declares unknown risk '${e.risk}'.`,
			`Use one of: ${KNOWN_RISK_LEVELS.join(", ")}.`
		] : void 0
	},
	{
		metadata: "sensitivity",
		issue: (e) => {
			if (e.sensitivity === void 0) return [
				CHECK_IDS.policyMissingToolSensitivity,
				`AGENTS.md tool '${e.id}' has no declared artifact sensitivity.`,
				`Declare sensitivity as one of: ${KNOWN_SENSITIVITY_LEVELS.join(", ")}.`
			];
			return KNOWN_SENSITIVITY_LEVELS.some((t) => t === e.sensitivity) ? void 0 : [
				CHECK_IDS.policyUnknownToolSensitivity,
				`AGENTS.md tool '${e.id}' declares unknown sensitivity '${e.sensitivity}'.`,
				`Use one of: ${KNOWN_SENSITIVITY_LEVELS.join(", ")}.`
			];
		}
	},
	{
		metadata: "owner",
		issue: (e) => e.owner === void 0 ? [
			CHECK_IDS.policyMissingToolOwner,
			`AGENTS.md tool '${e.id}' has no declared owner.`,
			"Declare owner:<team-or-person> for this tool."
		] : void 0
	}
];
function toolMetadataFindings(e, t, n) {
	return TOOL_METADATA_CHECKS.filter((e) => n.has(e.metadata)).flatMap((n) => (t.tools ?? []).flatMap((t) => {
		const r = n.issue(t);
		return r === void 0 ? [] : [toolMetadataFinding(t, e, ...r)];
	}));
}
//#endregion
//#region extensions/policy/src/doctor/evaluation.ts
const policyEvaluationCache = /* @__PURE__ */ new WeakMap();
function evaluatePolicy(e) {
	const t = policyEvaluationCache.get(e);
	if (t !== void 0) return t;
	const n = evaluatePolicyUncached(e);
	policyEvaluationCache.set(e, n);
	return n;
}
async function evaluatePolicyUncached(e) {
	const t = policySettings(e);
	const n = policyDisplayName(e);
	let r = collectPolicyEvidence(e.cfg, {
		includeIngress: false,
		includeGatewayExposure: false,
		includeAgentWorkspace: false,
		includeToolPosture: false,
		includeSandboxPosture: false,
		includeSecrets: false,
		includeAuthProfiles: false,
		includeExecApprovals: false
	});
	const i = [];
	const a = {
		policyPath: n,
		evidence: r,
		expectedAttestationHash: t.expectedAttestationHash,
		findings: i,
		attestedFindings: i
	};
	if (!policyChecksEnabled(e, t)) return a;
	const o = await readPolicyFile(e);
	if (o === null) {
		i.push({
			checkId: CHECK_IDS.policyMissingFile,
			severity: "warning",
			message: `${n} is missing for the enabled Policy plugin.`,
			source: "policy",
			path: n,
			fixHint: `Restore ${n} or add the policy artifact for this workspace.`
		});
		return a;
	}
	const s = parsePolicyFile(o.raw);
	if (!s.ok) {
		i.push(policyParseFinding(o.displayName, o.ocDocName, s));
		return a;
	}
	const c = s.value;
	const l = policyDocumentHash(c);
	const u = t.expectedHash;
	if (typeof u === "string" && u.trim() !== "" && l !== u.trim()) {
		i.push({
			checkId: CHECK_IDS.policyHashMismatch,
			severity: "error",
			message: `${o.displayName} does not match the configured policy hash.`,
			source: "policy",
			path: o.displayName,
			target: `oc://${o.ocDocName}`,
			requirement: "oc://openclaw.config/plugins/entries/policy/config/expectedHash",
			fixHint: `Restore the approved policy artifact or update plugins.entries.policy.config.expectedHash after review.`
		});
		return {
			...a,
			policy: {
				value: c,
				hash: l
			}
		};
	}
	const metadataRequirementShapeFindings = (e) => {
		const t = createOrderedPolicyShape(c, {
			policyPath: o.displayName,
			policyDocName: o.ocDocName
		}).list(e, {
			allowed: e === "tools.requireMetadata" ? SUPPORTED_TOOL_METADATA : SUPPORTED_AUTH_PROFILE_METADATA,
			normalize: "lower",
			array: {
				message: "{policy} {property} must be an array of metadata keys.",
				hint: "Use supported metadata keys: {allowed}."
			},
			entry: {
				message: "{policy} {property}[{index}] must be a supported metadata key.",
				hint: "Use supported metadata keys: {allowed}."
			}
		});
		return t === void 0 ? [] : [t];
	};
	const d = metadataRequirementShapeFindings("tools.requireMetadata");
	const f = metadataRequirementShapeFindings("auth.profiles.requireMetadata");
	const p = d.length === 0 ? requiredToolMetadata(c) : /* @__PURE__ */ new Set();
	const m = policyHasRules(c, "execApprovals");
	const h = isRecord(c) && isRecord(c.routing) && routingPolicyShapeFinding(c.routing, {
		policyDocName: o.ocDocName,
		policyPath: o.displayName
	}) === void 0 ? policyRoutingRules(c) : void 0;
	const g = m ? await readExecApprovalsFile() : void 0;
	const _ = {
		includeIngress: policyHasRules(c, "ingress"),
		includeGatewayExposure: policyHasRules(c, "gateway"),
		includeAgentWorkspace: policyHasRules(c, "agents"),
		includeDataHandling: policyHasRules(c, "dataHandling"),
		includeToolPosture: policyHasRules(c, "tools"),
		includeSandboxPosture: policyHasRules(c, "sandbox"),
		includeSecrets: policyHasRules(c, "secrets"),
		includeAuthProfiles: policyHasRules(c, "auth"),
		includeExecApprovals: m,
		execApprovalsRaw: m ? g?.raw ?? null : void 0,
		routing: h
	};
	let v;
	if (p.size > 0) {
		const [t, n] = await Promise.all([readWorkspaceFile(e, "AGENTS.md"), readWorkspaceFile(e, "TOOLS.md")]);
		if (n !== null) v = {
			checkId: CHECK_IDS.policyUnmigratedToolsFile,
			severity: "error",
			message: "TOOLS.md contains unmigrated governed tool declarations; run `openclaw doctor --fix` to migrate them into the AGENTS.md `## Tools` section before policy evaluation can pass.",
			source: "policy",
			path: "TOOLS.md",
			target: "oc://TOOLS.md/tools",
			requirement: `oc://${o.ocDocName}/tools/requireMetadata`,
			fixHint: "Run `openclaw doctor --fix` to migrate TOOLS.md into the AGENTS.md `## Tools` section."
		};
		r = collectPolicyEvidence(e.cfg, {
			toolsRaw: t?.raw ?? "",
			..._
		});
	} else r = collectPolicyEvidence(e.cfg, _);
	const y = [
		...policyContainerShapeFindings(c, o.displayName, o.ocDocName),
		...channelFindings(c, o.displayName, o.ocDocName, r),
		...mcpServerFindings(c, o.ocDocName, r),
		...modelProviderFindings(c, o.ocDocName, r),
		...networkFindings(c, o.ocDocName, r),
		...routingFindings(h, o.displayName, o.ocDocName, r)
	];
	for (const e of policySectionTargets(c, o.displayName, o.ocDocName, "ingress")) {
		const t = e.policy;
		const n = readPolicyPathString(t, ["session", "requireDmScope"]);
		const i = new Set(readStringList(t, ["channels", "allowDmPolicies"]));
		const a = (r.ingress ?? []).filter((t) => e.selectorId === void 0 || normalizeLowercaseStringOrEmpty(t.channel ?? "") === e.selectorId);
		const s = a.filter((e) => e.kind === "channelGroupPolicy");
		const c = [
			{
				kind: "sessionDmScope",
				enabled: n !== void 0,
				violates: (e) => e.value !== n,
				checkId: CHECK_IDS.policyIngressDmScopeUnapproved,
				message: (e) => `session.dmScope '${e.value ?? ""}' does not match policy.`,
				path: ["session", "requireDmScope"],
				fixHint: "Set session.dmScope to the required isolation scope or update policy after review."
			},
			{
				kind: "channelDmPolicy",
				enabled: i.size > 0,
				violates: (e) => typeof e.value === "string" && !i.has(e.value.toLowerCase()),
				checkId: CHECK_IDS.policyIngressDmPolicyUnapproved,
				message: (e) => `${ingressLabel(e)} uses unapproved DM policy '${e.value ?? ""}'.`,
				path: ["channels", "allowDmPolicies"],
				fixHint: "Set the channel DM policy to an allowed value or update policy after review."
			},
			{
				kind: "channelGroupPolicy",
				enabled: readBooleanPath(t, ["channels", "denyOpenGroups"]) === true,
				violates: (e) => e.value !== "allowlist" && e.value !== "disabled",
				checkId: CHECK_IDS.policyIngressOpenGroupsDenied,
				message: (e) => `${ingressLabel(e)} allows open group ingress.`,
				path: ["channels", "denyOpenGroups"],
				fixHint: "Set groupPolicy to allowlist or disabled, or update policy after review."
			},
			{
				kind: "channelRequireMention",
				enabled: readBooleanPath(t, ["channels", "requireMentionInGroups"]) === true,
				violates: (e) => !isGroupIngressDisabled(e, s) && e.value !== true,
				checkId: CHECK_IDS.policyIngressGroupMentionRequired,
				message: (e) => `${ingressLabel(e)} does not require group mentions.`,
				path: ["channels", "requireMentionInGroups"],
				fixHint: "Set requireMention=true for the channel/group entry or update policy after review."
			}
		];
		y.push(...policyEvidenceRuleFindings(a, c.filter((e) => e.enabled), o.ocDocName, e.requirementBase));
	}
	y.push(...gatewayExposureFindings(c, o.ocDocName, r));
	{
		const e = r.agentWorkspace ?? [];
		for (const t of policySectionTargets(c, o.displayName, o.ocDocName, "agents/workspace")) {
			const n = t.selectorId;
			const r = n === void 0 ? e : e.filter((t) => scopedAgentEvidenceMatches(t, n, e, t.scope === "defaults"));
			const i = new Set(readStringList(t.policy, ["allowedAccess"]));
			const a = new Set(readStringList(t.policy, ["denyTools"]));
			y.push(...r.filter((e) => i.size > 0 && e.kind === "workspaceAccess" && e.value !== void 0 && (e.sandboxEnabled !== true || !i.has(e.value))).map((e) => {
				const n = e.sandboxEnabled !== true;
				const r = n ? `sandbox mode '${e.sandboxMode ?? "off"}'` : `sandbox workspaceAccess '${e.value ?? ""}'`;
				const i = n ? e.sandboxModeSource ?? e.source : e.source;
				return policyEvidenceFinding({ source: i }, {
					checkId: CHECK_IDS.policyAgentsWorkspaceAccessDenied,
					message: `${workspaceLabel(e)} ${r} is not allowed by policy.`,
					requirement: `oc://${o.ocDocName}/${t.requirementBase}/allowedAccess`,
					fixHint: "Enable sandbox mode with workspaceAccess none/ro or update policy after review."
				});
			}), ...r.filter((e) => e.kind === "toolDeny" && e.tool !== void 0 && a.has(e.tool) && e.denied !== true).map((e) => policyEvidenceFinding(e, {
				checkId: CHECK_IDS.policyAgentsToolNotDenied,
				message: `${workspaceLabel(e)} does not deny required tool '${e.tool ?? ""}'.`,
				requirement: `oc://${o.ocDocName}/${t.requirementBase}/denyTools`,
				fixHint: "Add the tool to tools.deny or agents.entries.<id>.tools.deny, or update policy after review."
			})));
		}
	}
	y.push(...toolPostureFindings(c, o.displayName, o.ocDocName, r), ...sandboxPostureFindings(c, o.displayName, o.ocDocName, r), ...dataHandlingFindings(c, o.displayName, o.ocDocName, r), ...secretAuthProvenanceFindings(c, o.displayName, o.ocDocName, r), ...execApprovalsFindings(c, o.displayName, o.ocDocName, r, g, resolveExecApprovalsDisplayPath()), ...f, ...d, ...v === void 0 ? [] : [v]);
	y.push(...toolMetadataFindings(o.ocDocName, r, p));
	const b = [];
	const x = t.expectedAttestationHash?.trim();
	if (x) {
		const e = createPolicyAttestation({
			ok: y.length === 0,
			checkedAt: (/* @__PURE__ */ new Date(0)).toISOString(),
			policyPath: o.displayName,
			policyHash: l,
			evidence: r,
			findings: y.map(toAttestedFinding)
		});
		if (e.attestationHash !== x) b.push({
			checkId: CHECK_IDS.policyAttestationMismatch,
			severity: "error",
			message: "The current policy check no longer matches the accepted policy attestation.",
			source: "policy",
			path: "policy attestation",
			target: "oc://policy/attestation/current",
			requirement: "oc://openclaw.config/plugins/entries/policy/config/expectedAttestationHash",
			fixHint: `Run policy check, review attestation ${e.attestationHash}, then update plugins.entries.policy.config.expectedAttestationHash and the supervisor/gateway accepted attestation.`
		});
	}
	if (hasPolicyValidationFinding(y)) i.push(...y);
	else if (b.length > 0) i.push(...b);
	else i.push(...y);
	return {
		policyPath: n,
		policy: {
			value: c,
			hash: l
		},
		evidence: r,
		expectedAttestationHash: t.expectedAttestationHash,
		findings: i,
		attestedFindings: y
	};
}
function policyParseFinding(e, t, n) {
	return {
		checkId: CHECK_IDS.policyInvalidFile,
		severity: "error",
		message: `${e} could not be parsed: ${n.message}`,
		source: "policy",
		path: e,
		target: `oc://${t}`,
		fixHint: `Fix ${e} so policy conformance checks can run.`
	};
}
function hasPolicyValidationFinding(e) {
	return e.some((e) => e.checkId === CHECK_IDS.policyInvalidFile || e.checkId === CHECK_IDS.policyUnmigratedToolsFile);
}
function channelFindings(e, t, n, r) {
	function invalidChannelDenyRuleFindings() {
		const r = createOrderedPolicyShape(e, {
			policyPath: t,
			policyDocName: n
		});
		const i = r.value("channels.denyRules");
		if (i === void 0) return [];
		if (!Array.isArray(i)) return [r.finding("channels.denyRules", {
			message: "{policy} {property} must be an array.",
			hint: "Fix {policy} so channel deny rules are an array."
		})];
		for (const [e, r] of i.entries()) {
			if (!isRecord(r)) continue;
			const i = createOrderedPolicyShape(r, {
				policyPath: t,
				policyDocName: n,
				propertyPrefix: "channels.denyRules[" + e + "]",
				targetPrefix: "channels/denyRules/#" + e
			});
			const a = i.keys("", [
				"id",
				"reason",
				"when"
			], "", "Remove {unsupported} or use id, when.provider, and reason.", "{policy} {unsupported} is not supported in channel deny rules.") ?? i.keys("when", ["provider"], "", "Remove {unsupported} or use when.provider.", "{policy} {unsupported} is not supported in channel deny rules.");
			if (a !== void 0) return [a];
		}
		const a = i.findIndex((e) => !isChannelDenyRule(e));
		return a < 0 ? [] : [r.finding("channels.denyRules", {
			message: "{policy} {property}[{index}] must define when.provider as a string.",
			hint: "Fix {policy} so each channel deny rule has a provider match."
		}, { index: a })];
	}
	const i = invalidChannelDenyRuleFindings();
	if (i.length > 0) return i;
	const a = readChannelDenyRules(e, n);
	if (a.length === 0) return [];
	return r.channels.flatMap((e) => {
		if (e.enabled === false) return [];
		const t = a.find((t) => t.when.provider === e.provider);
		if (t === void 0) return [];
		return [policyEvidenceFinding(e, {
			checkId: CHECK_IDS.policyDeniedChannelProvider,
			message: `Channel '${e.id}' uses denied provider '${e.provider}'.`,
			requirement: t.requirement,
			fixHint: t.reason ?? "Disable this channel, remove it from config, or update the policy deny rule."
		})];
	});
}
function toAttestedFinding(e) {
	return {
		checkId: e.checkId,
		severity: e.severity,
		message: e.message,
		...e.source !== void 0 ? { source: e.source } : {},
		...e.path !== void 0 ? { path: e.path } : {},
		...e.line !== void 0 ? { line: e.line } : {},
		...e.column !== void 0 ? { column: e.column } : {},
		...e.ocPath !== void 0 ? { ocPath: e.ocPath } : {},
		...e.target !== void 0 ? { target: e.target } : {},
		...e.requirement !== void 0 ? { requirement: e.requirement } : {},
		...e.fixHint !== void 0 ? { fixHint: e.fixHint } : {}
	};
}
function workspaceLabel(e) {
	return e.agentId === void 0 ? "agents.defaults" : `agent '${e.agentId}'`;
}
function isGroupIngressDisabled(e, t) {
	const n = ocPathParent(e.source);
	const r = "oc://openclaw.config/channels/defaults";
	return t.filter((t) => {
		const i = ocPathParent(t.source);
		return t.channel === e.channel && (t.accountId ?? "") === (e.accountId ?? "") && (i === r || n === i || n.startsWith(`${i}/`));
	}).toSorted((e, t) => ocPathParent(t.source).length - ocPathParent(e.source).length)[0]?.value === "disabled";
}
function ocPathParent(e) {
	return e.slice(0, Math.max(0, e.lastIndexOf("/")));
}
function ingressLabel(e) {
	const t = e.accountId === void 0 ? "" : ` account '${e.accountId}'`;
	const n = e.groupId === void 0 ? "" : ` group '${e.groupId}'`;
	return `channel '${e.channel ?? "unknown"}'${t}${n}`;
}
//#endregion
export { POLICY_RULE_METADATA as _, scopedPolicyFields as a, policyRuleValueIsValid as c, disableChannels as d, workspaceRepairsEnabled as f, POLICY_FIX_METADATA_BY_CHECK_ID as g, POLICY_CHECK_METADATA as h, normalizePolicySelectorValues as i, createPolicyAttestation as l, getPolicyPath as m, toAttestedFinding as n, scopedPolicyOverlays as o, ocPathSegment as p, policyContainerShapeFindings as r, isPolicyValueAtLeastAsStrict as s, evaluatePolicy as t, channelIdsFromFindings as u, CHECK_IDS as v, POLICY_CHECK_IDS as y };