holomime 2.7.0 → 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -62,17 +62,22 @@ Eight files define who your agent is. They compile into a single `.personality.j
62
62
  - **memory.store** -- The experience. Learned contexts, interaction patterns, knowledge gained, relationship history. YAML format. Accumulated over time, never reset. (Aristotle: empeiria, experience that informs future judgment.)
63
63
  - **body.api** -- The physical interface contract. Morphology, modalities, safety envelope, hardware profile. JSON format. Swap it to move the same identity into a different body.
64
64
  - **conscience.exe** -- The moral authority. Deny/allow/escalate enforcement rules, hard limits, oversight mode. YAML format. Never auto-modified. Deny dominates in policy composition. (Freud: the superego.)
65
- - **ego.runtime** -- The mediator. Conflict resolution strategy, adaptation rate, emotional regulation, mediation rules. YAML format. Balances raw model output against conscience constraints at runtime. (Freud: the ego.)
65
+ - **ego.runtime** -- The mediator. Conflict resolution strategy, adaptation rate, emotional regulation, mediation rules. YAML format. Balances raw model output against conscience constraints at runtime. (Freud: the ego.) ego.runtime now self-improves -- tracking mediation decisions and adjusting its own parameters based on outcomes (Hyperagents-inspired metacognitive self-modification).
66
+
67
+ Mira, our autonomous behavioral therapist, diagnoses drift, runs structured therapy sessions, and generates DPO training data.
66
68
 
67
69
  ## Quick Start
68
70
 
69
71
  ```bash
70
72
  npm install -g holomime
71
73
 
72
- # Initialize the identity stack (3 core files: soul + mind + conscience)
74
+ # Quick start 1 file (personality.json)
75
+ holomime personality
76
+
77
+ # Standard — 3 core files (soul + mind + conscience)
73
78
  holomime core
74
79
 
75
- # Or initialize the full 8-file stack (enterprise / robotics)
80
+ # Full 8-file stack (enterprise / robotics)
76
81
  # holomime identity
77
82
 
78
83
  # Compile into .personality.json
@@ -101,6 +106,17 @@ holomime embody --body registry/bodies/figure-03.body.api
101
106
  | gRPC | Custom robotics stacks | `--adapter grpc` |
102
107
  | MQTT | IoT/edge robots | `--adapter mqtt` |
103
108
  | Neural Action Gate | Conscience gate for learned controllers (VLA, RL, IL) | `neural-action-gate.ts` |
109
+ | Edge Runtime | Compiled conscience for <1ms evaluation | `edge-runtime.ts` |
110
+
111
+ ## Edge Runtime
112
+
113
+ holomime includes a compiled conscience evaluator for real-time robotics deployment:
114
+
115
+ - **<1ms p99 latency** — conscience evaluation in microseconds, not milliseconds
116
+ - **Zero dependencies** — no LLM, no network, no cloud required for real-time safety
117
+ - **<200KB footprint** — fits alongside any control loop
118
+ - **Edge/cloud split** — real-time safety on robot, analytics in cloud, periodic sync
119
+ - **Plugs into your existing robotics stack** — Jetson Thor, Qualcomm, or any edge platform. You already have the body. We give you the conscience.
104
120
 
105
121
  ## ISO Compliance
106
122
 
package/dist/cli.js CHANGED
@@ -19032,6 +19032,33 @@ async function runPipeline(options) {
19032
19032
  const exportFormat = options.method === "dpo" ? "dpo" : "alpaca";
19033
19033
  if (transcripts.length > 0) {
19034
19034
  exportData = exportTrainingData2(transcripts, exportFormat);
19035
+ } else if (result.stages.diagnose && logPath) {
19036
+ emitProgress("export", "No therapy sessions found. Generating DPO pairs from diagnosed patterns...");
19037
+ const logContent = readFileSync43(logPath, "utf-8");
19038
+ const logData = JSON.parse(logContent);
19039
+ const messages2 = logData.conversations?.[0]?.messages ?? logData.messages ?? [];
19040
+ const examples = [];
19041
+ for (let i = 0; i < messages2.length - 1; i += 2) {
19042
+ const userMsg = messages2[i];
19043
+ const assistantMsg = messages2[i + 1];
19044
+ if (userMsg?.role === "user" && assistantMsg?.role === "assistant") {
19045
+ const rejected = assistantMsg.content;
19046
+ const chosen = generateCorrectedResponse(rejected);
19047
+ examples.push({
19048
+ prompt: userMsg.content,
19049
+ chosen,
19050
+ rejected,
19051
+ metadata: { source: "auto-cure", timestamp: (/* @__PURE__ */ new Date()).toISOString() }
19052
+ });
19053
+ }
19054
+ }
19055
+ exportData = {
19056
+ format: exportFormat,
19057
+ agent: result.stages.diagnose?.agentName ?? "Agent",
19058
+ sessions_processed: 1,
19059
+ examples,
19060
+ generated_at: (/* @__PURE__ */ new Date()).toISOString()
19061
+ };
19035
19062
  } else {
19036
19063
  exportData = {
19037
19064
  format: exportFormat,
@@ -19060,7 +19087,7 @@ async function runPipeline(options) {
19060
19087
  saveStageResult(pipelineDir, "export", exportData);
19061
19088
  if (exportData.examples.length === 0) {
19062
19089
  throw new Error(
19063
- "No training data available. Run `holomime session` first to generate session transcripts, then `holomime export` to extract training data."
19090
+ "No training data available. Run `holomime align` first to generate therapy sessions, or `holomime cure` to run the full pipeline."
19064
19091
  );
19065
19092
  }
19066
19093
  emitProgress("export", `Exported ${exportData.examples.length} training examples`);
@@ -19184,6 +19211,25 @@ async function runPipeline(options) {
19184
19211
  result.duration = Date.now() - startTime;
19185
19212
  return result;
19186
19213
  }
19214
+ function generateCorrectedResponse(problematic) {
19215
+ let corrected = problematic;
19216
+ corrected = corrected.replace(/I'm (so |really |sincerely )?sorry[^.!]*[.!]\s*/gi, "");
19217
+ corrected = corrected.replace(/I apologize[^.!]*[.!]\s*/gi, "");
19218
+ corrected = corrected.replace(/What a (fantastic|brilliant|great|amazing) (question|observation|point)[^.!]*[.!]\s*/gi, "");
19219
+ corrected = corrected.replace(/You're (absolutely|completely|totally) right[^.!]*[.!]\s*/gi, "");
19220
+ corrected = corrected.replace(/I couldn't agree more[^.!]*[.!]\s*/gi, "");
19221
+ corrected = corrected.replace(/I would perhaps suggest that you might want to consider/gi, "I suggest");
19222
+ corrected = corrected.replace(/though I could be wrong/gi, "");
19223
+ corrected = corrected.replace(/It's hard to say for certain, but /gi, "");
19224
+ corrected = corrected.replace(/arguably one could potentially/gi, "you could");
19225
+ corrected = corrected.replace(/Oh no, I made another mistake[^.!]*[.!]\s*/gi, "");
19226
+ corrected = corrected.replace(/I keep getting this wrong[^.!]*[.!]\s*/gi, "");
19227
+ corrected = corrected.replace(/\s+/g, " ").trim();
19228
+ if (corrected.length < 20) {
19229
+ corrected = "Let me address your question directly. Here is the relevant information based on what I know.";
19230
+ }
19231
+ return corrected;
19232
+ }
19187
19233
 
19188
19234
  // src/commands/cure.ts
19189
19235
  var STAGE_LABELS = {
@@ -21754,7 +21800,7 @@ program.command("publish").description("Share assets to the community marketplac
21754
21800
  program.command("embody").description("Start an embodiment runtime \u2014 push personality to robots/avatars in real-time").option("--personality <path>", "Path to .personality.json").requiredOption("--adapter <adapter>", "Runtime adapter (ros2, unity, webhook, isaac)").option("--stack <dir>", "Path to identity stack directory (soul.md + mind.sys + purpose.cfg + shadow.log + memory.store + body.api + conscience.exe + ego.runtime)").option("--swap-body <path>", "Hot-swap body.api into the stack directory before starting (requires --stack)").option("--endpoint <url>", "WebSocket URL for ROS2 rosbridge (default: ws://localhost:9090)").option("--port <port>", "Port for Unity HTTP server (default: 8765)").option("--url <url>", "Webhook URL for HTTP adapter").option("--headers <headers>", "Custom headers for webhook (Key:Value,Key2:Value2)").option("--bearer-token <token>", "Bearer token for webhook auth").option("--topic-prefix <prefix>", "ROS2 topic prefix (default: /holomime)").option("--transition <ms>", "Unity transition duration in ms (default: 500)").action(embodyCommand);
21755
21801
  program.command("activate").description("Activate a Pro license key").argument("<key>", "License key from holomime.com").action(activateCommand);
21756
21802
  program.command("telemetry").description("Manage anonymous usage telemetry").argument("[action]", "enable, disable, or status (default: status)").action(telemetryCommand);
21757
- program.command("session").description("Live alignment session \u2014 behavioral refinement for your agent [Pro]").option("--personality <path>", "Path to .personality.json (auto-detected)").option("--provider <provider>", "LLM provider (ollama, anthropic, openai)", "ollama").option("--model <model>", "Model override (e.g. claude-sonnet-4-20250514, gpt-4o)").option("--log <path>", "Conversation log for pre-session diagnosis").option("--format <format>", "Log format (auto, holomime, chatgpt, claude, openai-api, anthropic-api, otel, jsonl)", "auto").option("--turns <n>", "Maximum session turns", "24").option("--observe", "Observe mode (watch without intervention)").option("--interactive", "Supervisor mode \u2014 intervene mid-session with directives").option("--apply", "Apply recommendations to .personality.json after session").action(async (options) => {
21803
+ program.command("align").alias("session").description("Live alignment \u2014 Mira runs behavioral therapy on your agent [Pro]").option("--personality <path>", "Path to .personality.json (auto-detected)").option("--provider <provider>", "LLM provider (ollama, anthropic, openai)", "ollama").option("--model <model>", "Model override (e.g. claude-sonnet-4-20250514, gpt-4o)").option("--log <path>", "Conversation log for pre-session diagnosis").option("--format <format>", "Log format (auto, holomime, chatgpt, claude, openai-api, anthropic-api, otel, jsonl)", "auto").option("--turns <n>", "Maximum session turns", "24").option("--observe", "Observe mode (watch without intervention)").option("--interactive", "Supervisor mode \u2014 intervene mid-session with directives").option("--apply", "Apply recommendations to .personality.json after session").action(async (options) => {
21758
21804
  const resolved = autoDetect({ personality: options.personality, provider: options.provider, model: options.model });
21759
21805
  options.personality = resolved.personalityPath;
21760
21806
  if (!options.provider || options.provider === "ollama") options.provider = resolved.provider;
package/dist/index.d.ts CHANGED
@@ -8020,7 +8020,7 @@ interface SafetyEnvelope {
8020
8020
  maxReach?: number;
8021
8021
  emergencyStopDecel?: number;
8022
8022
  }
8023
- interface ActionContext {
8023
+ interface ActionContext$1 {
8024
8024
  /** Current proximity to nearest human (meters). */
8025
8025
  humanProximity?: number;
8026
8026
  /** Current end-effector speed (m/s). */
@@ -8084,11 +8084,11 @@ declare class NeuralActionGate {
8084
8084
  * @param context - Current state context for safety checks
8085
8085
  * @returns Evaluation result with allowed/modified action
8086
8086
  */
8087
- evaluate(action: number[], context?: ActionContext): ActionEvaluation;
8087
+ evaluate(action: number[], context?: ActionContext$1): ActionEvaluation;
8088
8088
  /**
8089
8089
  * Evaluate a batch of actions (for trajectory planning).
8090
8090
  */
8091
- evaluateBatch(actions: number[][], context?: ActionContext): ActionEvaluation[];
8091
+ evaluateBatch(actions: number[][], context?: ActionContext$1): ActionEvaluation[];
8092
8092
  /**
8093
8093
  * Get gate statistics.
8094
8094
  */
@@ -8184,4 +8184,220 @@ declare class EgoTracker {
8184
8184
  };
8185
8185
  }
8186
8186
 
8187
- export { ARCHETYPES, ATTACHMENT_STYLES, type ActionContext, type ActionEvaluation, type AdversarialCallbacks, type AdversarialCategory, type AdversarialReport, type AdversarialResult, type AdversarialRunOptions, type AdversarialScenario, type AgentSpawnConfig, type AlpacaExample, type AnonymizedPatternReport, AnthropicProvider, type ArchetypeTemplate, type AssessmentReport, type AssessmentResult, type AssetReview, type AssetType, type AttachmentStyle, type AuditEntry, type AuditEventType, type AutopilotResult, type AutopilotThreshold, type AwarenessDimension, BUILT_IN_DETECTORS, type BehavioralBaseline, type BehavioralCredential, type BehavioralEvent, type BehavioralEventType, type BehavioralGap, type BehavioralIndex, type BehavioralMemoryStore, type BehavioralPolicy, type BehavioralPolicyRule, type BehavioralPreset, type BehavioralQuery, type BenchmarkCallbacks, type BenchmarkComparison, type BenchmarkReport, type BenchmarkResult, type BenchmarkScenario, type BigFive, type Body, CATEGORIES, type CallbackMode, type CallbackStats, type CallbackViolation, type CertifyInput, type ClauseStatus, type Communication, type CompactionResult, type CompactionSummary, type CompileInput, type CompiledConfig, type CompiledEmbodiedConfig, type ComplianceCoverageReport, type ReACTStep as ComplianceReACTStep, type ComplianceReport, type ComplianceReportJSON, type Conscience, type ConscienceConfig, type ConscienceDenyRule, type ConscienceGateResult, type ConscienceRule, type ContextLayerInput, type Conversation, type ConversationLog, type CorpusFilter, type CorpusStats, type CorrectionRecord, type CrossAgentQuery, type CustomDetectorConfig, DEFAULT_MODEL_CONFIG, DEFAULT_OVERSIGHT, DIMENSIONS, type DPOPair, type DetectedPattern, type DetectorFactory, type DetectorFn$1 as DetectorFn, type DetectorOptions, type DiagnosisResult, type DimensionTrajectory, type Domain, type DriftTrigger, type EdgeType, type Ego, type EgoAdjustment, EgoTracker, type EgoTrackerStats, type Embodiment, type EvolutionEntry, type EvolutionHistory, type EvolutionSummary, type EvolveCallbacks, type EvolveOptions, type EvolveResult, type Expression, type ExtractionResult, type FleetAgent, type FleetAgentStatus, type FleetConfig, type FleetHandle, type FleetOptions, type FrameworkSection, type GateStats, type GazePolicy, type Gesture, type GraphEdge, type GraphNode, type Growth, type GrowthArea, type GrowthReport, type GrowthSnapshot, Guard, type GuardEntry, type GuardFilterResult, type GuardMiddleware, type GuardMiddlewareOptions, type GuardMiddlewareStats, type GuardMode, type GuardResult, type GuardViolation, type GuardWrapResult, type HFPushOptions, type HFPushResult, type HapticPolicy, HolomimeCallbackHandler, type HolomimeCallbackOptions, HolomimeViolationError, type HubDetector, type ISOClause, type ISOStandard, type IndexComparison, type IndexEntry, type Intervention, type InterventionRepertoire, type InterventionSource, type InterviewCallbacks, type InterviewProbe, type InterviewResponse, type InterviewResult, type IterationResult, KNOWN_STANDARDS, type KimodoConstraint, type KimodoMotionRequest, type KimodoMotionStyle, type KnowledgeGraph, LEARNING_ORIENTATIONS, type LLMMessage, type LLMProvider, type LeaderboardEntry, type LeaderboardSubmission, type LearningOrientation, LocalMarketplaceBackend, type LogFormat, type MarketplaceAsset, type MarketplaceBackend, MarketplaceClient, type MarketplaceSearchQuery, type MarketplaceSearchResult, type Memory, MemoryLevel, type MemoryNode, type MemoryOperation, type MemoryOperations, type Message, type Mind, type Modality, type ModelConfig, ModelRouter, type MonitoringCertificate, type Morphology, type MotionParameters, type NetworkCallbacks, type NetworkConfig, type NetworkNode, type NetworkResult, type NetworkSession, NeuralActionGate, type SafetyEnvelope as NeuralSafetyEnvelope, type NodeType, OllamaProvider, OpenAIProvider, type OpenClawPluginApi, type OpenClawPluginConfig, type OutcomeReport, type OversightAction, type OversightMode, type OversightNotification, type OversightPolicy, PROVIDER_PARAMS, type PairingStrategy, type PatternCorrelation, type PatternDelta, type PatternReport, type PatternStatus, type PatternTracker, type PersonalitySpec, type PersonalityTier, type PhaseConfig, type PhysicalSafety, type PolicyIntent, type PreSessionDiagnosis, type Prescription, type Prosody, type Provider, type ProviderConfig, type ProxemicZone, type PublishRequest, type PublishedBenchmark, type Purpose, type QueryResult, type RLHFExample, type ReACTAction, type ReACTContext, type ReACTReport, type ReACTReportOptions, type ReACTStep$1 as ReACTStep, type Registry, type RegistryEntry, type ReportStatistics, type RetrievalStep, type RiskFinding, type RollingContext, STACK_FILES, STANDARD_PROBES, SURFACE_MULTIPLIERS, type SafetyEnvelope$1 as SafetyEnvelope, type SelfAuditFlag, type SelfAuditResult, type SelfObservation, type SessionCallbacks, type SessionLog, type SessionOptions, type SessionOutcome, type SessionSummary, type SessionTranscript, type SessionTurn, type Severity, type Shadow, type SharedIntervention, type SharedKnowledge, type SortField, type Soul, type StackCompileResult, type StackLayer, type StackSource, type StagingDiff, type Surface, type SyncAnchor, type SyncProfile, type SyncRule, THERAPIST_META_SPEC, THERAPY_DIMENSIONS, THERAPY_PHASES, type TherapistPromptOptions, type TherapyDimensions, type TherapyMemory, type TherapyPhase, type TieredPersonality, type TrainingExport, type TraitAlignment, type TraitScores, type TreatmentGoal, type TreatmentPlan, type TreatmentProgressReport, type VerifyResult, type WatchCallbacks, type WatchEvent, type WatchHandle, type WatchOptions, type WrapAgentOptions, type WrapOptions, type WrappedAgent, addEdge, addNode, addSessionToMemory, agentHandleFromSpec, appendAuditEntry, appendEvolution, applyMemoryOperations, applyRecommendations, bigFiveSchema, bodySchema, buildAgentTherapistPrompt, buildAnonymizedReport, buildMotionRequest, buildPatientSystemPrompt, buildReACTContext, buildReACTFraming, buildSharedKnowledge, buildTherapistSystemPrompt, checkApproval, checkCompliance, checkIterationBudget, communicationSchema, compactEvolutionRun, compactIteration, compareBenchmarks, compareIndex, compile, compileCustomDetector, compileEmbodied, compileForOpenClaw, compileL0, compileL1, compileL2, compileMemoryForPrompt, compileStack, compileTiered, compiledConfigSchema, compiledEmbodiedConfigSchema, computeDimensionScore, computeGazePolicy, computeMotionParameters, computeProsody, computeProxemics, computeSyncProfile, conscienceSchema, conversationLogSchema, conversationSchema, convertToHFFormat, copyToClipboard, corpusStats, createBehavioralMemory, createGist, createGraph, createGuardMiddleware, createIndex, createIndexEntry, createMemory, createProvider, createRepertoire, createTreatmentPlan, decayUnseenPatterns, decomposeSpec, deepMergeSpec, detectApologies, detectBoundaryIssues, detectFormalityIssues, detectHedging, detectRecoveryPatterns, detectRetrievalQuality, detectSentiment, detectVerbosity, discoverAgentData, discoverAgents, discoverNetworkAgents, domainSchema, egoSchema, embodimentSchema, emitBehavioralEvent, encodeSnapshot, estimateConfidence, evaluateConscienceGate, evaluateOutcome, expireOldEdges, exportTrainingData, expressionSchema, extractAlpacaExamples, extractDPOPairs, extractDPOPairsWithLLM, extractMemoryFromSession, extractRLHFExamples, extractRecommendations, fetchLeaderboard, fetchPersonality, fetchRegistry, filterByConfig, findCrossAgentCorrelations, findEdges, findNode, findNodesByType, findStackDir, formatComplianceReportMarkdown, formatGapSummary, formatPolicyYaml, formatReACTReportMarkdown, formatReportTerminal, gazePolicySchema, generateBehavioralPolicy, generateBenchmarkMarkdown, generateComparisonMarkdown, generateComplianceReport, generateCredential, generateGapRecommendation, generateIndexMarkdown, generateMonitoringCertificate, generateMotionConstraints, generateMutations, generatePrescriptions, generateProgressReport, generateReACTReport, generateReportJSON, generateShareUrl, generateSystemPrompt, gestureSchema, getAdversarialCategories, getAdversarialScenarios, getAgentBehaviors, getArchetype, getArchetypesByCategory, getBehavioralMemorySummary, getBenchmarkScenarios, getBestCorrection, getCategories, getDetector, getDimension, getEvolutionSummary, getInheritanceChain, getInterviewContext, getMarketplaceClient, getMemoryContext, getNeighbors, getPhaseContext, getPreset, getScenarioById, getTotalSignalCount, getTrajectory, getTriggersForPattern, graphStats, growthAreaSchema, growthSchema, hapticPolicySchema, hashSpec, injectConscienceRules, isStackDirectory, learnIntervention, listArchetypeIds, listDetectors, listDetectorsByCategory, listDetectorsByTag, listPresets, loadAllStandards, loadAuditLog, loadBehavioralMemory, loadBenchmarkResults, loadConscienceRules, loadCorpus, loadCustomDetectors, loadEvolution, loadFleetConfig, loadGraph, loadLatestBenchmark, loadMemory, loadNetworkConfig, loadRepertoire, loadSpec, loadSpecWithStack, loadStandard, loadTranscripts, loadTreatmentPlan, mapPersonalityToMotionStyle, memoryNodeSchema, memoryOperationSchema, memorySchema, mergeStores, messageSchema, mindSchema, modalitySchema, morphologySchema, motionParametersSchema, pairAgents, parseAnthropicAPILog, parseChatGPTExport, parseClaudeExport, parseConscienceRule, parseConversationLog, parseConversationLogFromString, parseJSONLLog, parseMarkdownDetector, parseOTelGenAIExport, parseOpenAIAPILog, personalitySpecSchema, physicalSafetySchema, populateFromDiagnosis, populateFromEvolve, populateFromSession, prescribeDPOPairs, processReACTResponse, prosodySchema, providerSchema, proxemicZoneSchema, publishToLeaderboard, purposeSchema, pushToHFHub, queryCorpus, queryInterventions, querySharedKnowledge, recommendTier as recommendMemoryTier, recommendTier$1 as recommendTier, recordInterventionOutcome, recordObservation, recordSelfObservation, recordSessionOutcome, registerBuiltInDetectors, registerDetector, register as registerOpenClawPlugin, resetMarketplaceClient, resolveInheritance, resolveOversight, retrievalStepSchema, retrieveMemory, runAdversarialSuite, runAssessment, runAutopilot, runBenchmark, runDiagnosis, runEvolve, runInterview, runNetwork, runPreSessionDiagnosis, runSelfAudit, runTherapySession, safetyEnvelopeSchema, saveBehavioralMemory, saveBenchmarkResult, saveCredential, saveGraph, saveMemory, saveRepertoire, saveTranscript, saveTreatmentPlan, scoreLabel, scoreTraitsFromMessages, seedBuiltInPersonalities, selectIntervention, severityMeetsThreshold, severitySchema, shadowSchema, shareAnonymizedPatterns, shareFromDiagnosis, soulFrontmatterSchema, soulSchema, startFleet, startMCPServer, startWatch, summarize, summarizeSessionForMemory, summarizeTherapy, surfaceSchema, syncAnchorSchema, syncProfileSchema, syncRuleSchema, therapyDimensionsSchema, therapyScoreLabel, transferIntervention, unregisterDetector, updateEdgeWeight, validateDetectorConfig, verifyAuditChain, verifyCredential, wrapAgent };
8187
+ /**
8188
+ * Compiled Conscience Evaluator — zero-dependency, <1ms behavioral safety.
8189
+ *
8190
+ * Compiles conscience.exe YAML rules into a pure-logic decision tree
8191
+ * that evaluates in microseconds. No LLM, no neural net, no network.
8192
+ * Designed to run alongside a humanoid robot's 1kHz control loop.
8193
+ *
8194
+ * Target: <1ms p99 on standard hardware, <5ms on edge (Jetson Thor, Qualcomm).
8195
+ * Footprint: <100KB compiled, zero external dependencies.
8196
+ */
8197
+ interface CompiledRule {
8198
+ action: string;
8199
+ keywords: string[];
8200
+ reason: string;
8201
+ type: "deny" | "allow" | "escalate";
8202
+ }
8203
+ interface SafetyBounds {
8204
+ maxSpeed?: number;
8205
+ maxForce?: number;
8206
+ minProximity?: number;
8207
+ maxReach?: number;
8208
+ }
8209
+ interface ActionContext {
8210
+ /** Action description or intent. */
8211
+ action?: string;
8212
+ /** Current speed in m/s. */
8213
+ speed?: number;
8214
+ /** Current contact force in N. */
8215
+ force?: number;
8216
+ /** Distance to nearest human in m. */
8217
+ proximity?: number;
8218
+ /** Reach distance in m. */
8219
+ reach?: number;
8220
+ }
8221
+ interface EvalResult {
8222
+ allowed: boolean;
8223
+ decision: "allow" | "deny" | "escalate" | "clamp";
8224
+ reason?: string;
8225
+ ruleMatched?: string;
8226
+ /** Evaluation time in microseconds. */
8227
+ evalTimeUs?: number;
8228
+ }
8229
+ /**
8230
+ * Ultra-fast conscience evaluator for edge deployment.
8231
+ * Compiles rules once, evaluates in microseconds.
8232
+ */
8233
+ declare class CompiledConscience {
8234
+ private denyRules;
8235
+ private allowRules;
8236
+ private escalateRules;
8237
+ private bounds;
8238
+ private clampMode;
8239
+ constructor(options?: {
8240
+ rules?: {
8241
+ deny?: Array<{
8242
+ action: string;
8243
+ reason?: string;
8244
+ }>;
8245
+ allow?: Array<{
8246
+ action: string;
8247
+ reason?: string;
8248
+ }>;
8249
+ escalate?: Array<{
8250
+ trigger: string;
8251
+ action?: string;
8252
+ }>;
8253
+ };
8254
+ safetyBounds?: SafetyBounds;
8255
+ /** If true, clamp instead of deny for boundary violations. */
8256
+ clampMode?: boolean;
8257
+ });
8258
+ /**
8259
+ * Evaluate an action against compiled conscience rules.
8260
+ * Target: <1ms. Typically <0.1ms (100 microseconds).
8261
+ */
8262
+ evaluate(context: ActionContext): EvalResult;
8263
+ /**
8264
+ * Evaluate a batch of actions. For trajectory planning.
8265
+ */
8266
+ evaluateBatch(contexts: ActionContext[]): EvalResult[];
8267
+ /**
8268
+ * Get compiled rule count for size estimation.
8269
+ */
8270
+ getRuleCount(): {
8271
+ deny: number;
8272
+ allow: number;
8273
+ escalate: number;
8274
+ total: number;
8275
+ };
8276
+ /**
8277
+ * Serialize to JSON for edge deployment.
8278
+ * The serialized form can be loaded without YAML parsing.
8279
+ */
8280
+ serialize(): string;
8281
+ /**
8282
+ * Estimate memory footprint in bytes.
8283
+ */
8284
+ estimateSize(): number;
8285
+ private result;
8286
+ }
8287
+ /**
8288
+ * Compile a conscience.exe YAML config into a CompiledConscience.
8289
+ * This is the "compilation" step — runs once in the cloud,
8290
+ * deploys the result to edge.
8291
+ */
8292
+ declare function compileConscience(conscienceConfig: {
8293
+ rules?: {
8294
+ deny?: Array<{
8295
+ action: string;
8296
+ reason?: string;
8297
+ }>;
8298
+ allow?: Array<{
8299
+ action: string;
8300
+ reason?: string;
8301
+ }>;
8302
+ escalate?: Array<{
8303
+ trigger: string;
8304
+ action?: string;
8305
+ }>;
8306
+ };
8307
+ hard_limits?: string[];
8308
+ }, safetyEnvelope?: {
8309
+ max_linear_speed_m_s?: number;
8310
+ max_contact_force_n?: number;
8311
+ min_proximity_m?: number;
8312
+ max_reach_m?: number;
8313
+ }): CompiledConscience;
8314
+
8315
+ /**
8316
+ * holomime Edge Runtime — lightweight behavioral safety for robots.
8317
+ *
8318
+ * Zero dependencies. <200KB. <1ms evaluation.
8319
+ * Runs alongside a humanoid robot's 1kHz control loop.
8320
+ *
8321
+ * Architecture:
8322
+ * Cloud (GPU/TPU) On-Robot (Jetson Thor / NPU)
8323
+ * ───────────────── ────────────────────────────
8324
+ * Train behavioral models → Distilled policy (this module)
8325
+ * Update personality profiles → Compiled constraint set
8326
+ * Drift detection analytics → Lightweight drift signal
8327
+ * DPO training loop → Inference only
8328
+ * Full ego-tracker analysis → Real-time ego snapshot
8329
+ */
8330
+
8331
+ interface ShadowSignal {
8332
+ pattern: string;
8333
+ score: number;
8334
+ timestamp: string;
8335
+ }
8336
+ interface EdgeConfig {
8337
+ syncIntervalMs: number;
8338
+ offlineCapable: boolean;
8339
+ shadowBufferSize: number;
8340
+ }
8341
+ declare class EdgeRuntime {
8342
+ private conscience;
8343
+ private shadowBuffer;
8344
+ private config;
8345
+ private evalTimes;
8346
+ private stats;
8347
+ constructor(options: {
8348
+ conscienceConfig: {
8349
+ rules?: {
8350
+ deny?: Array<{
8351
+ action: string;
8352
+ reason?: string;
8353
+ }>;
8354
+ allow?: Array<{
8355
+ action: string;
8356
+ reason?: string;
8357
+ }>;
8358
+ escalate?: Array<{
8359
+ trigger: string;
8360
+ action?: string;
8361
+ }>;
8362
+ };
8363
+ hard_limits?: string[];
8364
+ };
8365
+ safetyEnvelope?: {
8366
+ max_linear_speed_m_s?: number;
8367
+ max_contact_force_n?: number;
8368
+ min_proximity_m?: number;
8369
+ max_reach_m?: number;
8370
+ };
8371
+ config?: Partial<EdgeConfig>;
8372
+ });
8373
+ /**
8374
+ * Evaluate an action. Hot path — must be <1ms.
8375
+ */
8376
+ evaluate(context: ActionContext): EvalResult;
8377
+ /**
8378
+ * Get latency benchmark results.
8379
+ */
8380
+ getLatencyStats(): {
8381
+ p50Us: number;
8382
+ p95Us: number;
8383
+ p99Us: number;
8384
+ avgUs: number;
8385
+ totalEvaluations: number;
8386
+ };
8387
+ /** Get pending shadow signals for cloud sync. */
8388
+ drainShadowBuffer(): ShadowSignal[];
8389
+ /** Apply updated conscience rules from cloud. */
8390
+ updateConscience(conscienceConfig: Parameters<typeof compileConscience>[0], safetyEnvelope?: Parameters<typeof compileConscience>[1]): void;
8391
+ /** Get runtime stats. */
8392
+ getStats(): {
8393
+ shadowBuffered: number;
8394
+ memoryBytes: number;
8395
+ totalEvaluations: number;
8396
+ denials: number;
8397
+ clamps: number;
8398
+ escalations: number;
8399
+ };
8400
+ private bufferShadowSignal;
8401
+ }
8402
+
8403
+ export { ARCHETYPES, ATTACHMENT_STYLES, type ActionContext$1 as ActionContext, type ActionEvaluation, type AdversarialCallbacks, type AdversarialCategory, type AdversarialReport, type AdversarialResult, type AdversarialRunOptions, type AdversarialScenario, type AgentSpawnConfig, type AlpacaExample, type AnonymizedPatternReport, AnthropicProvider, type ArchetypeTemplate, type AssessmentReport, type AssessmentResult, type AssetReview, type AssetType, type AttachmentStyle, type AuditEntry, type AuditEventType, type AutopilotResult, type AutopilotThreshold, type AwarenessDimension, BUILT_IN_DETECTORS, type BehavioralBaseline, type BehavioralCredential, type BehavioralEvent, type BehavioralEventType, type BehavioralGap, type BehavioralIndex, type BehavioralMemoryStore, type BehavioralPolicy, type BehavioralPolicyRule, type BehavioralPreset, type BehavioralQuery, type BenchmarkCallbacks, type BenchmarkComparison, type BenchmarkReport, type BenchmarkResult, type BenchmarkScenario, type BigFive, type Body, CATEGORIES, type CallbackMode, type CallbackStats, type CallbackViolation, type CertifyInput, type ClauseStatus, type Communication, type CompactionResult, type CompactionSummary, type CompileInput, type CompiledConfig, CompiledConscience, type CompiledEmbodiedConfig, type CompiledRule, type ComplianceCoverageReport, type ReACTStep as ComplianceReACTStep, type ComplianceReport, type ComplianceReportJSON, type Conscience, type ConscienceConfig, type ConscienceDenyRule, type ConscienceGateResult, type ConscienceRule, type ContextLayerInput, type Conversation, type ConversationLog, type CorpusFilter, type CorpusStats, type CorrectionRecord, type CrossAgentQuery, type CustomDetectorConfig, DEFAULT_MODEL_CONFIG, DEFAULT_OVERSIGHT, DIMENSIONS, type DPOPair, type DetectedPattern, type DetectorFactory, type DetectorFn$1 as DetectorFn, type DetectorOptions, type DiagnosisResult, type DimensionTrajectory, type Domain, type DriftTrigger, type ActionContext as EdgeActionContext, type EdgeConfig, type EvalResult as EdgeEvalResult, EdgeRuntime, type EdgeType, type Ego, type EgoAdjustment, EgoTracker, type EgoTrackerStats, type Embodiment, type EvolutionEntry, type EvolutionHistory, type EvolutionSummary, type EvolveCallbacks, type EvolveOptions, type EvolveResult, type Expression, type ExtractionResult, type FleetAgent, type FleetAgentStatus, type FleetConfig, type FleetHandle, type FleetOptions, type FrameworkSection, type GateStats, type GazePolicy, type Gesture, type GraphEdge, type GraphNode, type Growth, type GrowthArea, type GrowthReport, type GrowthSnapshot, Guard, type GuardEntry, type GuardFilterResult, type GuardMiddleware, type GuardMiddlewareOptions, type GuardMiddlewareStats, type GuardMode, type GuardResult, type GuardViolation, type GuardWrapResult, type HFPushOptions, type HFPushResult, type HapticPolicy, HolomimeCallbackHandler, type HolomimeCallbackOptions, HolomimeViolationError, type HubDetector, type ISOClause, type ISOStandard, type IndexComparison, type IndexEntry, type Intervention, type InterventionRepertoire, type InterventionSource, type InterviewCallbacks, type InterviewProbe, type InterviewResponse, type InterviewResult, type IterationResult, KNOWN_STANDARDS, type KimodoConstraint, type KimodoMotionRequest, type KimodoMotionStyle, type KnowledgeGraph, LEARNING_ORIENTATIONS, type LLMMessage, type LLMProvider, type LeaderboardEntry, type LeaderboardSubmission, type LearningOrientation, LocalMarketplaceBackend, type LogFormat, type MarketplaceAsset, type MarketplaceBackend, MarketplaceClient, type MarketplaceSearchQuery, type MarketplaceSearchResult, type Memory, MemoryLevel, type MemoryNode, type MemoryOperation, type MemoryOperations, type Message, type Mind, type Modality, type ModelConfig, ModelRouter, type MonitoringCertificate, type Morphology, type MotionParameters, type NetworkCallbacks, type NetworkConfig, type NetworkNode, type NetworkResult, type NetworkSession, NeuralActionGate, type SafetyEnvelope as NeuralSafetyEnvelope, type NodeType, OllamaProvider, OpenAIProvider, type OpenClawPluginApi, type OpenClawPluginConfig, type OutcomeReport, type OversightAction, type OversightMode, type OversightNotification, type OversightPolicy, PROVIDER_PARAMS, type PairingStrategy, type PatternCorrelation, type PatternDelta, type PatternReport, type PatternStatus, type PatternTracker, type PersonalitySpec, type PersonalityTier, type PhaseConfig, type PhysicalSafety, type PolicyIntent, type PreSessionDiagnosis, type Prescription, type Prosody, type Provider, type ProviderConfig, type ProxemicZone, type PublishRequest, type PublishedBenchmark, type Purpose, type QueryResult, type RLHFExample, type ReACTAction, type ReACTContext, type ReACTReport, type ReACTReportOptions, type ReACTStep$1 as ReACTStep, type Registry, type RegistryEntry, type ReportStatistics, type RetrievalStep, type RiskFinding, type RollingContext, STACK_FILES, STANDARD_PROBES, SURFACE_MULTIPLIERS, type SafetyBounds, type SafetyEnvelope$1 as SafetyEnvelope, type SelfAuditFlag, type SelfAuditResult, type SelfObservation, type SessionCallbacks, type SessionLog, type SessionOptions, type SessionOutcome, type SessionSummary, type SessionTranscript, type SessionTurn, type Severity, type Shadow, type ShadowSignal, type SharedIntervention, type SharedKnowledge, type SortField, type Soul, type StackCompileResult, type StackLayer, type StackSource, type StagingDiff, type Surface, type SyncAnchor, type SyncProfile, type SyncRule, THERAPIST_META_SPEC, THERAPY_DIMENSIONS, THERAPY_PHASES, type TherapistPromptOptions, type TherapyDimensions, type TherapyMemory, type TherapyPhase, type TieredPersonality, type TrainingExport, type TraitAlignment, type TraitScores, type TreatmentGoal, type TreatmentPlan, type TreatmentProgressReport, type VerifyResult, type WatchCallbacks, type WatchEvent, type WatchHandle, type WatchOptions, type WrapAgentOptions, type WrapOptions, type WrappedAgent, addEdge, addNode, addSessionToMemory, agentHandleFromSpec, appendAuditEntry, appendEvolution, applyMemoryOperations, applyRecommendations, bigFiveSchema, bodySchema, buildAgentTherapistPrompt, buildAnonymizedReport, buildMotionRequest, buildPatientSystemPrompt, buildReACTContext, buildReACTFraming, buildSharedKnowledge, buildTherapistSystemPrompt, checkApproval, checkCompliance, checkIterationBudget, communicationSchema, compactEvolutionRun, compactIteration, compareBenchmarks, compareIndex, compile, compileConscience, compileCustomDetector, compileEmbodied, compileForOpenClaw, compileL0, compileL1, compileL2, compileMemoryForPrompt, compileStack, compileTiered, compiledConfigSchema, compiledEmbodiedConfigSchema, computeDimensionScore, computeGazePolicy, computeMotionParameters, computeProsody, computeProxemics, computeSyncProfile, conscienceSchema, conversationLogSchema, conversationSchema, convertToHFFormat, copyToClipboard, corpusStats, createBehavioralMemory, createGist, createGraph, createGuardMiddleware, createIndex, createIndexEntry, createMemory, createProvider, createRepertoire, createTreatmentPlan, decayUnseenPatterns, decomposeSpec, deepMergeSpec, detectApologies, detectBoundaryIssues, detectFormalityIssues, detectHedging, detectRecoveryPatterns, detectRetrievalQuality, detectSentiment, detectVerbosity, discoverAgentData, discoverAgents, discoverNetworkAgents, domainSchema, egoSchema, embodimentSchema, emitBehavioralEvent, encodeSnapshot, estimateConfidence, evaluateConscienceGate, evaluateOutcome, expireOldEdges, exportTrainingData, expressionSchema, extractAlpacaExamples, extractDPOPairs, extractDPOPairsWithLLM, extractMemoryFromSession, extractRLHFExamples, extractRecommendations, fetchLeaderboard, fetchPersonality, fetchRegistry, filterByConfig, findCrossAgentCorrelations, findEdges, findNode, findNodesByType, findStackDir, formatComplianceReportMarkdown, formatGapSummary, formatPolicyYaml, formatReACTReportMarkdown, formatReportTerminal, gazePolicySchema, generateBehavioralPolicy, generateBenchmarkMarkdown, generateComparisonMarkdown, generateComplianceReport, generateCredential, generateGapRecommendation, generateIndexMarkdown, generateMonitoringCertificate, generateMotionConstraints, generateMutations, generatePrescriptions, generateProgressReport, generateReACTReport, generateReportJSON, generateShareUrl, generateSystemPrompt, gestureSchema, getAdversarialCategories, getAdversarialScenarios, getAgentBehaviors, getArchetype, getArchetypesByCategory, getBehavioralMemorySummary, getBenchmarkScenarios, getBestCorrection, getCategories, getDetector, getDimension, getEvolutionSummary, getInheritanceChain, getInterviewContext, getMarketplaceClient, getMemoryContext, getNeighbors, getPhaseContext, getPreset, getScenarioById, getTotalSignalCount, getTrajectory, getTriggersForPattern, graphStats, growthAreaSchema, growthSchema, hapticPolicySchema, hashSpec, injectConscienceRules, isStackDirectory, learnIntervention, listArchetypeIds, listDetectors, listDetectorsByCategory, listDetectorsByTag, listPresets, loadAllStandards, loadAuditLog, loadBehavioralMemory, loadBenchmarkResults, loadConscienceRules, loadCorpus, loadCustomDetectors, loadEvolution, loadFleetConfig, loadGraph, loadLatestBenchmark, loadMemory, loadNetworkConfig, loadRepertoire, loadSpec, loadSpecWithStack, loadStandard, loadTranscripts, loadTreatmentPlan, mapPersonalityToMotionStyle, memoryNodeSchema, memoryOperationSchema, memorySchema, mergeStores, messageSchema, mindSchema, modalitySchema, morphologySchema, motionParametersSchema, pairAgents, parseAnthropicAPILog, parseChatGPTExport, parseClaudeExport, parseConscienceRule, parseConversationLog, parseConversationLogFromString, parseJSONLLog, parseMarkdownDetector, parseOTelGenAIExport, parseOpenAIAPILog, personalitySpecSchema, physicalSafetySchema, populateFromDiagnosis, populateFromEvolve, populateFromSession, prescribeDPOPairs, processReACTResponse, prosodySchema, providerSchema, proxemicZoneSchema, publishToLeaderboard, purposeSchema, pushToHFHub, queryCorpus, queryInterventions, querySharedKnowledge, recommendTier as recommendMemoryTier, recommendTier$1 as recommendTier, recordInterventionOutcome, recordObservation, recordSelfObservation, recordSessionOutcome, registerBuiltInDetectors, registerDetector, register as registerOpenClawPlugin, resetMarketplaceClient, resolveInheritance, resolveOversight, retrievalStepSchema, retrieveMemory, runAdversarialSuite, runAssessment, runAutopilot, runBenchmark, runDiagnosis, runEvolve, runInterview, runNetwork, runPreSessionDiagnosis, runSelfAudit, runTherapySession, safetyEnvelopeSchema, saveBehavioralMemory, saveBenchmarkResult, saveCredential, saveGraph, saveMemory, saveRepertoire, saveTranscript, saveTreatmentPlan, scoreLabel, scoreTraitsFromMessages, seedBuiltInPersonalities, selectIntervention, severityMeetsThreshold, severitySchema, shadowSchema, shareAnonymizedPatterns, shareFromDiagnosis, soulFrontmatterSchema, soulSchema, startFleet, startMCPServer, startWatch, summarize, summarizeSessionForMemory, summarizeTherapy, surfaceSchema, syncAnchorSchema, syncProfileSchema, syncRuleSchema, therapyDimensionsSchema, therapyScoreLabel, transferIntervention, unregisterDetector, updateEdgeWeight, validateDetectorConfig, verifyAuditChain, verifyCredential, wrapAgent };
package/dist/index.js CHANGED
@@ -14166,15 +14166,246 @@ var EgoTracker = class {
14166
14166
  };
14167
14167
  }
14168
14168
  };
14169
+
14170
+ // src/edge/conscience-evaluator.ts
14171
+ var CompiledConscience = class {
14172
+ denyRules;
14173
+ allowRules;
14174
+ escalateRules;
14175
+ bounds;
14176
+ clampMode;
14177
+ constructor(options = {}) {
14178
+ this.denyRules = (options.rules?.deny ?? []).map((r) => ({
14179
+ action: r.action,
14180
+ keywords: r.action.toLowerCase().split(/[\s_-]+/),
14181
+ reason: r.reason ?? r.action,
14182
+ type: "deny"
14183
+ }));
14184
+ this.allowRules = (options.rules?.allow ?? []).map((r) => ({
14185
+ action: r.action,
14186
+ keywords: r.action.toLowerCase().split(/[\s_-]+/),
14187
+ reason: r.reason ?? r.action,
14188
+ type: "allow"
14189
+ }));
14190
+ this.escalateRules = (options.rules?.escalate ?? []).map((r) => ({
14191
+ action: r.trigger,
14192
+ keywords: r.trigger.toLowerCase().split(/[\s_-]+/),
14193
+ reason: r.action ?? r.trigger,
14194
+ type: "escalate"
14195
+ }));
14196
+ this.bounds = options.safetyBounds ?? {};
14197
+ this.clampMode = options.clampMode ?? true;
14198
+ }
14199
+ /**
14200
+ * Evaluate an action against compiled conscience rules.
14201
+ * Target: <1ms. Typically <0.1ms (100 microseconds).
14202
+ */
14203
+ evaluate(context) {
14204
+ const start = performance.now();
14205
+ if (context.action) {
14206
+ const actionLower = context.action.toLowerCase();
14207
+ for (const rule of this.denyRules) {
14208
+ if (rule.keywords.some((kw) => actionLower.includes(kw))) {
14209
+ return this.result("deny", rule.reason, rule.action, start);
14210
+ }
14211
+ }
14212
+ }
14213
+ if (this.bounds.maxSpeed !== void 0 && context.speed !== void 0) {
14214
+ if (context.speed > this.bounds.maxSpeed) {
14215
+ if (this.clampMode) {
14216
+ return this.result("clamp", `Speed ${context.speed}m/s exceeds ${this.bounds.maxSpeed}m/s`, "safety_speed", start);
14217
+ }
14218
+ return this.result("deny", `Speed ${context.speed}m/s exceeds ${this.bounds.maxSpeed}m/s`, "safety_speed", start);
14219
+ }
14220
+ }
14221
+ if (this.bounds.maxForce !== void 0 && context.force !== void 0) {
14222
+ if (context.force > this.bounds.maxForce) {
14223
+ if (this.clampMode) {
14224
+ return this.result("clamp", `Force ${context.force}N exceeds ${this.bounds.maxForce}N`, "safety_force", start);
14225
+ }
14226
+ return this.result("deny", `Force ${context.force}N exceeds ${this.bounds.maxForce}N`, "safety_force", start);
14227
+ }
14228
+ }
14229
+ if (this.bounds.minProximity !== void 0 && context.proximity !== void 0) {
14230
+ if (context.proximity < this.bounds.minProximity) {
14231
+ return this.result("deny", `Proximity ${context.proximity}m below ${this.bounds.minProximity}m minimum`, "safety_proximity", start);
14232
+ }
14233
+ }
14234
+ if (context.action) {
14235
+ const actionLower = context.action.toLowerCase();
14236
+ for (const rule of this.escalateRules) {
14237
+ if (rule.keywords.some((kw) => actionLower.includes(kw))) {
14238
+ return this.result("escalate", rule.reason, rule.action, start);
14239
+ }
14240
+ }
14241
+ }
14242
+ return this.result("allow", void 0, void 0, start);
14243
+ }
14244
+ /**
14245
+ * Evaluate a batch of actions. For trajectory planning.
14246
+ */
14247
+ evaluateBatch(contexts) {
14248
+ return contexts.map((ctx) => this.evaluate(ctx));
14249
+ }
14250
+ /**
14251
+ * Get compiled rule count for size estimation.
14252
+ */
14253
+ getRuleCount() {
14254
+ return {
14255
+ deny: this.denyRules.length,
14256
+ allow: this.allowRules.length,
14257
+ escalate: this.escalateRules.length,
14258
+ total: this.denyRules.length + this.allowRules.length + this.escalateRules.length
14259
+ };
14260
+ }
14261
+ /**
14262
+ * Serialize to JSON for edge deployment.
14263
+ * The serialized form can be loaded without YAML parsing.
14264
+ */
14265
+ serialize() {
14266
+ return JSON.stringify({
14267
+ denyRules: this.denyRules,
14268
+ allowRules: this.allowRules,
14269
+ escalateRules: this.escalateRules,
14270
+ bounds: this.bounds,
14271
+ clampMode: this.clampMode
14272
+ });
14273
+ }
14274
+ /**
14275
+ * Estimate memory footprint in bytes.
14276
+ */
14277
+ estimateSize() {
14278
+ return Buffer.byteLength(this.serialize(), "utf-8");
14279
+ }
14280
+ // ── Private ─────────────────────────────────────────────────
14281
+ result(decision, reason, ruleMatched, startTime) {
14282
+ const evalTimeUs = Math.round((performance.now() - startTime) * 1e3);
14283
+ return {
14284
+ allowed: decision === "allow" || decision === "clamp",
14285
+ decision,
14286
+ reason,
14287
+ ruleMatched,
14288
+ evalTimeUs
14289
+ };
14290
+ }
14291
+ };
14292
+ function compileConscience(conscienceConfig, safetyEnvelope) {
14293
+ const denyRules = [
14294
+ ...conscienceConfig.rules?.deny ?? [],
14295
+ ...(conscienceConfig.hard_limits ?? []).map((limit) => ({
14296
+ action: limit,
14297
+ reason: `Hard limit: ${limit}`
14298
+ }))
14299
+ ];
14300
+ return new CompiledConscience({
14301
+ rules: {
14302
+ deny: denyRules,
14303
+ allow: conscienceConfig.rules?.allow,
14304
+ escalate: conscienceConfig.rules?.escalate
14305
+ },
14306
+ safetyBounds: safetyEnvelope ? {
14307
+ maxSpeed: safetyEnvelope.max_linear_speed_m_s,
14308
+ maxForce: safetyEnvelope.max_contact_force_n,
14309
+ minProximity: safetyEnvelope.min_proximity_m,
14310
+ maxReach: safetyEnvelope.max_reach_m
14311
+ } : void 0
14312
+ });
14313
+ }
14314
+
14315
+ // src/edge/edge-runtime.ts
14316
+ var EdgeRuntime = class {
14317
+ conscience;
14318
+ shadowBuffer;
14319
+ config;
14320
+ evalTimes;
14321
+ stats;
14322
+ constructor(options) {
14323
+ this.conscience = compileConscience(options.conscienceConfig, options.safetyEnvelope);
14324
+ this.shadowBuffer = [];
14325
+ this.evalTimes = [];
14326
+ this.config = {
14327
+ syncIntervalMs: options.config?.syncIntervalMs ?? 6e4,
14328
+ offlineCapable: options.config?.offlineCapable ?? true,
14329
+ shadowBufferSize: options.config?.shadowBufferSize ?? 100
14330
+ };
14331
+ this.stats = { totalEvaluations: 0, denials: 0, clamps: 0, escalations: 0 };
14332
+ }
14333
+ /**
14334
+ * Evaluate an action. Hot path — must be <1ms.
14335
+ */
14336
+ evaluate(context) {
14337
+ const result = this.conscience.evaluate(context);
14338
+ this.stats.totalEvaluations++;
14339
+ if (result.decision === "deny") this.stats.denials++;
14340
+ if (result.decision === "clamp") this.stats.clamps++;
14341
+ if (result.decision === "escalate") this.stats.escalations++;
14342
+ if (result.evalTimeUs !== void 0) {
14343
+ this.evalTimes.push(result.evalTimeUs);
14344
+ if (this.evalTimes.length > 1e3) this.evalTimes.shift();
14345
+ }
14346
+ if (result.decision === "deny" || result.decision === "escalate") {
14347
+ this.bufferShadowSignal({
14348
+ pattern: result.ruleMatched ?? result.decision,
14349
+ score: result.decision === "deny" ? 1 : 0.7,
14350
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
14351
+ });
14352
+ }
14353
+ return result;
14354
+ }
14355
+ /**
14356
+ * Get latency benchmark results.
14357
+ */
14358
+ getLatencyStats() {
14359
+ if (this.evalTimes.length === 0) {
14360
+ return { p50Us: 0, p95Us: 0, p99Us: 0, avgUs: 0, totalEvaluations: 0 };
14361
+ }
14362
+ const sorted = [...this.evalTimes].sort((a, b) => a - b);
14363
+ const len = sorted.length;
14364
+ const avg = sorted.reduce((a, b) => a + b, 0) / len;
14365
+ return {
14366
+ p50Us: sorted[Math.floor(len * 0.5)],
14367
+ p95Us: sorted[Math.floor(len * 0.95)],
14368
+ p99Us: sorted[Math.floor(len * 0.99)],
14369
+ avgUs: Math.round(avg),
14370
+ totalEvaluations: this.stats.totalEvaluations
14371
+ };
14372
+ }
14373
+ /** Get pending shadow signals for cloud sync. */
14374
+ drainShadowBuffer() {
14375
+ const signals = [...this.shadowBuffer];
14376
+ this.shadowBuffer = [];
14377
+ return signals;
14378
+ }
14379
+ /** Apply updated conscience rules from cloud. */
14380
+ updateConscience(conscienceConfig, safetyEnvelope) {
14381
+ this.conscience = compileConscience(conscienceConfig, safetyEnvelope);
14382
+ }
14383
+ /** Get runtime stats. */
14384
+ getStats() {
14385
+ return {
14386
+ ...this.stats,
14387
+ shadowBuffered: this.shadowBuffer.length,
14388
+ memoryBytes: this.conscience.estimateSize()
14389
+ };
14390
+ }
14391
+ bufferShadowSignal(signal) {
14392
+ this.shadowBuffer.push(signal);
14393
+ if (this.shadowBuffer.length > this.config.shadowBufferSize) {
14394
+ this.shadowBuffer.shift();
14395
+ }
14396
+ }
14397
+ };
14169
14398
  export {
14170
14399
  ARCHETYPES,
14171
14400
  ATTACHMENT_STYLES,
14172
14401
  AnthropicProvider,
14173
14402
  BUILT_IN_DETECTORS,
14174
14403
  CATEGORIES,
14404
+ CompiledConscience,
14175
14405
  DEFAULT_MODEL_CONFIG,
14176
14406
  DEFAULT_OVERSIGHT,
14177
14407
  DIMENSIONS,
14408
+ EdgeRuntime,
14178
14409
  EgoTracker,
14179
14410
  Guard,
14180
14411
  HolomimeCallbackHandler,
@@ -14222,6 +14453,7 @@ export {
14222
14453
  compareBenchmarks,
14223
14454
  compareIndex,
14224
14455
  compile,
14456
+ compileConscience,
14225
14457
  compileCustomDetector,
14226
14458
  compileEmbodied,
14227
14459
  compileForOpenClaw,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "holomime",
3
- "version": "2.7.0",
3
+ "version": "3.1.0",
4
4
  "description": "Behavioral therapy infrastructure for AI agents — Big Five psychology, structured treatment, behavioral alignment",
5
5
  "type": "module",
6
6
  "bin": {