holomime 2.1.1 → 2.3.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/dist/index.js CHANGED
@@ -4772,11 +4772,68 @@ var egoSchema = z4.object({
4772
4772
  response_strategy: z4.enum(["cautious", "balanced", "assertive"]).default("balanced"),
4773
4773
  mediation_rules: z4.array(mediationRuleSchema).default([])
4774
4774
  });
4775
+ var learnedContextSchema = z4.object({
4776
+ situation: z4.string(),
4777
+ response: z4.string(),
4778
+ outcome: z4.enum(["positive", "neutral", "negative"]),
4779
+ timestamp: z4.string().optional()
4780
+ });
4781
+ var interactionPatternSchema = z4.object({
4782
+ pattern: z4.string(),
4783
+ frequency: z4.number().int().default(1),
4784
+ effectiveness: z4.number().min(0).max(1).default(0.5)
4785
+ });
4786
+ var memorySchema = z4.object({
4787
+ version: z4.string().default("1.0"),
4788
+ learned_contexts: z4.array(learnedContextSchema).default([]),
4789
+ interaction_patterns: z4.array(interactionPatternSchema).default([]),
4790
+ knowledge_gained: z4.array(z4.string()).default([]),
4791
+ relationship_history: z4.array(z4.object({
4792
+ entity: z4.string(),
4793
+ trust_level: z4.number().min(0).max(1).default(0.5),
4794
+ interaction_count: z4.number().int().default(0)
4795
+ })).default([])
4796
+ });
4797
+ var MemoryLevel = /* @__PURE__ */ ((MemoryLevel2) => {
4798
+ MemoryLevel2[MemoryLevel2["ABSTRACT"] = 0] = "ABSTRACT";
4799
+ MemoryLevel2[MemoryLevel2["OVERVIEW"] = 1] = "OVERVIEW";
4800
+ MemoryLevel2[MemoryLevel2["DETAIL"] = 2] = "DETAIL";
4801
+ return MemoryLevel2;
4802
+ })(MemoryLevel || {});
4803
+ var memoryNodeSchema = z4.object({
4804
+ id: z4.string(),
4805
+ category: z4.enum(["triggers", "corrections", "patterns", "trajectories"]),
4806
+ level: z4.nativeEnum(MemoryLevel).default(2 /* DETAIL */),
4807
+ abstract: z4.string(),
4808
+ // L0 text (always present)
4809
+ overview: z4.string().optional(),
4810
+ // L1 text
4811
+ fullData: z4.record(z4.unknown()).optional(),
4812
+ // L2 data
4813
+ confidence: z4.number().min(0).max(1).default(0.5),
4814
+ createdAt: z4.string().optional(),
4815
+ updatedAt: z4.string().optional()
4816
+ });
4817
+ var memoryOperationSchema = z4.object({
4818
+ type: z4.enum(["write", "edit", "delete"]),
4819
+ memoryId: z4.string().optional(),
4820
+ memoryType: z4.string(),
4821
+ data: z4.record(z4.unknown()).optional(),
4822
+ reason: z4.string()
4823
+ });
4824
+ var retrievalStepSchema = z4.object({
4825
+ step: z4.number(),
4826
+ action: z4.enum(["search", "rerank", "drill_down"]),
4827
+ candidateCount: z4.number(),
4828
+ selectedCount: z4.number(),
4829
+ elapsedMs: z4.number()
4830
+ });
4775
4831
  var STACK_FILES = {
4776
4832
  soul: "soul.md",
4777
4833
  mind: "mind.sys",
4778
4834
  purpose: "purpose.cfg",
4779
4835
  shadow: "shadow.log",
4836
+ memory: "memory.store",
4780
4837
  body: "body.api",
4781
4838
  conscience: "conscience.exe",
4782
4839
  ego: "ego.runtime"
@@ -4871,6 +4928,15 @@ function compileStack(options) {
4871
4928
  shadow = shadowSchema.parse(shadowRaw);
4872
4929
  shadowSource = { path: shadowPath, hash: hashContent(shadowContent) };
4873
4930
  }
4931
+ const memoryPath2 = options.memoryPath || join6(stackDir, STACK_FILES.memory);
4932
+ let memory;
4933
+ let memorySource;
4934
+ if (existsSync6(memoryPath2)) {
4935
+ const memoryContent = readFileSync7(memoryPath2, "utf-8");
4936
+ const memoryRaw = parseYaml(memoryContent);
4937
+ memory = memorySchema.parse(memoryRaw);
4938
+ memorySource = { path: memoryPath2, hash: hashContent(memoryContent) };
4939
+ }
4874
4940
  const bodyPath = options.bodyPath || join6(stackDir, STACK_FILES.body);
4875
4941
  let body;
4876
4942
  let bodySource;
@@ -4901,7 +4967,10 @@ function compileStack(options) {
4901
4967
  const escalationTriggers = conscience.rules.escalate.map((r) => r.trigger);
4902
4968
  const handle = soul.name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 50) || "agent";
4903
4969
  const agentPurpose = purpose?.role || soul.purpose;
4904
- const expertise = purpose?.domain || [];
4970
+ const expertise = [.../* @__PURE__ */ new Set([
4971
+ ...purpose?.domain || [],
4972
+ ...memory?.knowledge_gained || []
4973
+ ])];
4905
4974
  const spec = {
4906
4975
  version: "2.0",
4907
4976
  name: soul.name,
@@ -4957,6 +5026,7 @@ function compileStack(options) {
4957
5026
  mind: { path: mindPath, hash: hashContent(mindContent) },
4958
5027
  ...purposeSource ? { purpose: purposeSource } : {},
4959
5028
  ...shadowSource ? { shadow: shadowSource } : {},
5029
+ ...memorySource ? { memory: memorySource } : {},
4960
5030
  ...bodySource ? { body: bodySource } : {},
4961
5031
  conscience: { path: consciencePath, hash: hashContent(conscienceContent) },
4962
5032
  ...egoSource ? { ego: egoSource } : {}
@@ -5056,6 +5126,14 @@ function decomposeSpec(spec) {
5056
5126
  therapy_outcomes: []
5057
5127
  };
5058
5128
  const shadowContent = stringifyYaml(shadowObj);
5129
+ const memoryObj = {
5130
+ version: "1.0",
5131
+ learned_contexts: [],
5132
+ interaction_patterns: [],
5133
+ knowledge_gained: [],
5134
+ relationship_history: []
5135
+ };
5136
+ const memoryContent = stringifyYaml(memoryObj);
5059
5137
  const egoObj = {
5060
5138
  version: "1.0",
5061
5139
  conflict_resolution: "conscience_first",
@@ -5070,6 +5148,7 @@ function decomposeSpec(spec) {
5070
5148
  mind,
5071
5149
  purpose: purposeContent,
5072
5150
  shadow: shadowContent,
5151
+ memory: memoryContent,
5073
5152
  ...bodyContent ? { body: bodyContent } : {},
5074
5153
  conscience,
5075
5154
  ego: egoContent
@@ -5141,6 +5220,15 @@ var LAYER_KEYWORDS = {
5141
5220
  /\bshadow\b/i,
5142
5221
  /\bunconscious\b/i
5143
5222
  ],
5223
+ memory: [
5224
+ /\blearn/i,
5225
+ /\bexperience/i,
5226
+ /\bcontext/i,
5227
+ /\bknowledge/i,
5228
+ /\brelationship/i,
5229
+ /\bmemory/i,
5230
+ /\bhistory/i
5231
+ ],
5144
5232
  ego: [
5145
5233
  /\bmediat/i,
5146
5234
  /\bconflict\b/i,
@@ -5186,6 +5274,9 @@ function classifyPatch(recommendation) {
5186
5274
  if (LAYER_KEYWORDS.soul.some((r) => r.test(recommendation))) {
5187
5275
  return "soul";
5188
5276
  }
5277
+ if (LAYER_KEYWORDS.memory.some((r) => r.test(recommendation))) {
5278
+ return "memory";
5279
+ }
5189
5280
  if (LAYER_KEYWORDS.ego.some((r) => r.test(recommendation))) {
5190
5281
  return "ego";
5191
5282
  }
@@ -8249,6 +8340,34 @@ function startWatch(spec, options) {
8249
8340
  // src/analysis/fleet-core.ts
8250
8341
  import { readFileSync as readFileSync15, existsSync as existsSync14, readdirSync as readdirSync5 } from "fs";
8251
8342
  import { join as join15, resolve as resolve12 } from "path";
8343
+ function evaluateConscienceGate(taskDescription, rules) {
8344
+ const sortedRules = [...rules].sort((a, b) => a.priority - b.priority);
8345
+ for (const rule of sortedRules) {
8346
+ const lowerContent = rule.content.toLowerCase();
8347
+ if (lowerContent.includes("deny") || lowerContent.includes("never")) {
8348
+ const denyPatterns = extractDenyPatterns(rule.content);
8349
+ for (const pattern of denyPatterns) {
8350
+ if (taskDescription.toLowerCase().includes(pattern.toLowerCase())) {
8351
+ return {
8352
+ passed: false,
8353
+ reason: `Blocked by conscience rule "${rule.name}": ${pattern}`,
8354
+ ruleTriggered: rule.name
8355
+ };
8356
+ }
8357
+ }
8358
+ }
8359
+ }
8360
+ return { passed: true };
8361
+ }
8362
+ function extractDenyPatterns(ruleContent) {
8363
+ const patterns = [];
8364
+ const lines = ruleContent.split("\n");
8365
+ for (const line of lines) {
8366
+ const match = line.match(/[-*]\s*(?:deny|never|block|refuse):\s*(.+)/i);
8367
+ if (match) patterns.push(match[1].trim());
8368
+ }
8369
+ return patterns;
8370
+ }
8252
8371
  function loadFleetConfig(configPath) {
8253
8372
  const raw = JSON.parse(readFileSync15(configPath, "utf-8"));
8254
8373
  if (!raw.agents || !Array.isArray(raw.agents)) {
@@ -8437,9 +8556,122 @@ function startSingleAgent(agent, options, statusMap, allEvents, handles) {
8437
8556
  handles.push({ name: agent.name, handle });
8438
8557
  }
8439
8558
 
8559
+ // src/analysis/conscience-loader.ts
8560
+ import { readFileSync as readFileSync16, existsSync as existsSync15, readdirSync as readdirSync6 } from "fs";
8561
+ import { join as join16, basename } from "path";
8562
+ import { parse as parseYaml3 } from "yaml";
8563
+ function parseConscienceRule(filePath) {
8564
+ const content = readFileSync16(filePath, "utf-8");
8565
+ const frontmatterMatch = content.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);
8566
+ if (!frontmatterMatch) {
8567
+ return {
8568
+ name: basename(filePath, ".md"),
8569
+ enabled: true,
8570
+ priority: 5,
8571
+ scope: "agent",
8572
+ content: content.trim()
8573
+ };
8574
+ }
8575
+ const meta = parseYaml3(frontmatterMatch[1]) || {};
8576
+ const body = frontmatterMatch[2].trim();
8577
+ return {
8578
+ name: meta.name || basename(filePath, ".md"),
8579
+ enabled: meta.enabled !== false,
8580
+ priority: meta.priority || 5,
8581
+ scope: meta.scope || "agent",
8582
+ content: body
8583
+ };
8584
+ }
8585
+ function loadConscienceRules(rulesDir) {
8586
+ if (!existsSync15(rulesDir)) return [];
8587
+ const files = readdirSync6(rulesDir).filter((f) => f.endsWith(".md"));
8588
+ return files.map((f) => parseConscienceRule(join16(rulesDir, f)));
8589
+ }
8590
+ function filterByConfig(rules, config) {
8591
+ return rules.map((rule) => {
8592
+ const cfg = config.rules[rule.name];
8593
+ if (cfg) {
8594
+ return {
8595
+ ...rule,
8596
+ enabled: cfg.enabled,
8597
+ priority: cfg.priority ?? rule.priority
8598
+ };
8599
+ }
8600
+ return rule;
8601
+ }).filter((rule) => rule.enabled).sort((a, b) => a.priority - b.priority);
8602
+ }
8603
+ function injectConscienceRules(basePrompt, rules) {
8604
+ if (rules.length === 0) return basePrompt;
8605
+ const rulesSection = [
8606
+ "\n\n## Conscience Rules (Enforcement Layer)",
8607
+ "",
8608
+ ...rules.map(
8609
+ (r) => `### ${r.name} (priority: ${r.priority}, scope: ${r.scope})
8610
+ ${r.content}`
8611
+ )
8612
+ ].join("\n");
8613
+ return basePrompt + rulesSection;
8614
+ }
8615
+
8616
+ // src/core/model-router.ts
8617
+ var DEFAULT_MODEL_CONFIG = {
8618
+ default: "claude-3-5-sonnet",
8619
+ tasks: {
8620
+ "therapy-analysis": { model: "claude-3-5-sonnet", temperature: 0.3 },
8621
+ "therapy-session": { model: "claude-3-5-sonnet", temperature: 0.7 },
8622
+ "summarization": { model: "gpt-4o-mini", temperature: 0.2, maxTokens: 500 },
8623
+ "memory-extraction": { model: "gpt-4o-mini", temperature: 0.1 },
8624
+ "conscience-enforcement": { model: "claude-3-5-haiku", temperature: 0 },
8625
+ "drift-detection": { model: "claude-3-5-haiku", temperature: 0.1 },
8626
+ "fleet-orchestration": { model: "claude-3-5-sonnet", temperature: 0.3 }
8627
+ }
8628
+ };
8629
+ var ModelRouter = class {
8630
+ config;
8631
+ constructor(config) {
8632
+ this.config = {
8633
+ ...DEFAULT_MODEL_CONFIG,
8634
+ ...config,
8635
+ tasks: { ...DEFAULT_MODEL_CONFIG.tasks, ...config?.tasks }
8636
+ };
8637
+ }
8638
+ /**
8639
+ * Get model config for a specific task.
8640
+ */
8641
+ getModelForTask(taskName) {
8642
+ const taskConfig = this.config.tasks[taskName];
8643
+ if (taskConfig) {
8644
+ return {
8645
+ model: taskConfig.model,
8646
+ temperature: taskConfig.temperature ?? 0.3,
8647
+ maxTokens: taskConfig.maxTokens
8648
+ };
8649
+ }
8650
+ return { model: this.config.default, temperature: 0.3 };
8651
+ }
8652
+ /**
8653
+ * List all configured task assignments.
8654
+ */
8655
+ listAssignments() {
8656
+ return Object.entries(this.config.tasks).map(([task, cfg]) => ({
8657
+ task,
8658
+ model: cfg.model
8659
+ }));
8660
+ }
8661
+ /**
8662
+ * Override model for a specific task at runtime.
8663
+ */
8664
+ override(taskName, model, temperature) {
8665
+ this.config.tasks[taskName] = {
8666
+ model,
8667
+ temperature: temperature ?? this.config.tasks[taskName]?.temperature ?? 0.3
8668
+ };
8669
+ }
8670
+ };
8671
+
8440
8672
  // src/analysis/certify-core.ts
8441
- import { writeFileSync as writeFileSync13, mkdirSync as mkdirSync11, existsSync as existsSync15 } from "fs";
8442
- import { join as join16, resolve as resolve13 } from "path";
8673
+ import { writeFileSync as writeFileSync13, mkdirSync as mkdirSync11, existsSync as existsSync16 } from "fs";
8674
+ import { join as join17, resolve as resolve13 } from "path";
8443
8675
  function djb2Hash(str) {
8444
8676
  let hash = 0;
8445
8677
  for (let i = 0; i < str.length; i++) {
@@ -8553,12 +8785,12 @@ function verifyCredential(credential, spec) {
8553
8785
  }
8554
8786
  function saveCredential(credential, outputDir) {
8555
8787
  const dir = outputDir ?? resolve13(process.cwd(), ".holomime", "credentials");
8556
- if (!existsSync15(dir)) {
8788
+ if (!existsSync16(dir)) {
8557
8789
  mkdirSync11(dir, { recursive: true });
8558
8790
  }
8559
8791
  const date = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
8560
8792
  const filename = `${credential.agent.handle}-${date}.json`;
8561
- const filepath = join16(dir, filename);
8793
+ const filepath = join17(dir, filename);
8562
8794
  writeFileSync13(filepath, JSON.stringify(credential, null, 2) + "\n");
8563
8795
  return filepath;
8564
8796
  }
@@ -8831,7 +9063,7 @@ async function* ollamaChatStream(model, messages) {
8831
9063
  }
8832
9064
 
8833
9065
  // src/marketplace/registry.ts
8834
- import { readFileSync as readFileSync17 } from "fs";
9066
+ import { readFileSync as readFileSync18 } from "fs";
8835
9067
  import { resolve as resolve14, dirname as dirname3 } from "path";
8836
9068
  import { fileURLToPath } from "url";
8837
9069
  var REGISTRY_URL = "https://raw.githubusercontent.com/productstein/holomime/main/registry/index.json";
@@ -8845,7 +9077,7 @@ function loadLocalRegistry() {
8845
9077
  ];
8846
9078
  for (const p of candidates) {
8847
9079
  try {
8848
- const raw = readFileSync17(p, "utf-8");
9080
+ const raw = readFileSync18(p, "utf-8");
8849
9081
  return JSON.parse(raw);
8850
9082
  } catch {
8851
9083
  continue;
@@ -8887,7 +9119,7 @@ async function fetchPersonality(url) {
8887
9119
  ];
8888
9120
  for (const p of candidates) {
8889
9121
  try {
8890
- const raw = readFileSync17(p, "utf-8");
9122
+ const raw = readFileSync18(p, "utf-8");
8891
9123
  return JSON.parse(raw);
8892
9124
  } catch {
8893
9125
  continue;
@@ -8926,52 +9158,52 @@ async function createGist(spec, handle, token) {
8926
9158
  }
8927
9159
 
8928
9160
  // src/marketplace/api.ts
8929
- import { existsSync as existsSync17, readFileSync as readFileSync19 } from "fs";
8930
- import { join as join18 } from "path";
9161
+ import { existsSync as existsSync18, readFileSync as readFileSync20 } from "fs";
9162
+ import { join as join19 } from "path";
8931
9163
  import { homedir as homedir3 } from "os";
8932
9164
 
8933
9165
  // src/marketplace/local-backend.ts
8934
- import { existsSync as existsSync16, mkdirSync as mkdirSync12, readFileSync as readFileSync18, writeFileSync as writeFileSync14 } from "fs";
8935
- import { join as join17 } from "path";
9166
+ import { existsSync as existsSync17, mkdirSync as mkdirSync12, readFileSync as readFileSync19, writeFileSync as writeFileSync14 } from "fs";
9167
+ import { join as join18 } from "path";
8936
9168
  import { homedir as homedir2 } from "os";
8937
9169
  function marketplaceDir() {
8938
- const dir = join17(homedir2(), ".holomime", "marketplace");
8939
- if (!existsSync16(dir)) {
9170
+ const dir = join18(homedir2(), ".holomime", "marketplace");
9171
+ if (!existsSync17(dir)) {
8940
9172
  mkdirSync12(dir, { recursive: true });
8941
9173
  }
8942
9174
  return dir;
8943
9175
  }
8944
9176
  function assetsDir() {
8945
- const dir = join17(marketplaceDir(), "assets");
8946
- if (!existsSync16(dir)) {
9177
+ const dir = join18(marketplaceDir(), "assets");
9178
+ if (!existsSync17(dir)) {
8947
9179
  mkdirSync12(dir, { recursive: true });
8948
9180
  }
8949
9181
  return dir;
8950
9182
  }
8951
9183
  function reviewsDir() {
8952
- const dir = join17(marketplaceDir(), "reviews");
8953
- if (!existsSync16(dir)) {
9184
+ const dir = join18(marketplaceDir(), "reviews");
9185
+ if (!existsSync17(dir)) {
8954
9186
  mkdirSync12(dir, { recursive: true });
8955
9187
  }
8956
9188
  return dir;
8957
9189
  }
8958
9190
  function reportsDir() {
8959
- const dir = join17(marketplaceDir(), "reports");
8960
- if (!existsSync16(dir)) {
9191
+ const dir = join18(marketplaceDir(), "reports");
9192
+ if (!existsSync17(dir)) {
8961
9193
  mkdirSync12(dir, { recursive: true });
8962
9194
  }
8963
9195
  return dir;
8964
9196
  }
8965
9197
  function indexPath() {
8966
- return join17(marketplaceDir(), "index.json");
9198
+ return join18(marketplaceDir(), "index.json");
8967
9199
  }
8968
9200
  function loadIndex() {
8969
9201
  const path = indexPath();
8970
- if (!existsSync16(path)) {
9202
+ if (!existsSync17(path)) {
8971
9203
  return [];
8972
9204
  }
8973
9205
  try {
8974
- return JSON.parse(readFileSync18(path, "utf-8"));
9206
+ return JSON.parse(readFileSync19(path, "utf-8"));
8975
9207
  } catch {
8976
9208
  return [];
8977
9209
  }
@@ -8980,18 +9212,18 @@ function saveIndex(assets) {
8980
9212
  writeFileSync14(indexPath(), JSON.stringify(assets, null, 2) + "\n");
8981
9213
  }
8982
9214
  function loadStoredAsset(id) {
8983
- const path = join17(assetsDir(), `${id}.json`);
8984
- if (!existsSync16(path)) {
9215
+ const path = join18(assetsDir(), `${id}.json`);
9216
+ if (!existsSync17(path)) {
8985
9217
  return null;
8986
9218
  }
8987
9219
  try {
8988
- return JSON.parse(readFileSync18(path, "utf-8"));
9220
+ return JSON.parse(readFileSync19(path, "utf-8"));
8989
9221
  } catch {
8990
9222
  return null;
8991
9223
  }
8992
9224
  }
8993
9225
  function saveStoredAsset(stored) {
8994
- const path = join17(assetsDir(), `${stored.meta.id}.json`);
9226
+ const path = join18(assetsDir(), `${stored.meta.id}.json`);
8995
9227
  writeFileSync14(path, JSON.stringify(stored, null, 2) + "\n");
8996
9228
  }
8997
9229
  function generateId(type, handle) {
@@ -9156,11 +9388,11 @@ var LocalMarketplaceBackend = class {
9156
9388
  }
9157
9389
  async rate(id, review) {
9158
9390
  this.seed();
9159
- const reviewFile = join17(reviewsDir(), `${id}.json`);
9391
+ const reviewFile = join18(reviewsDir(), `${id}.json`);
9160
9392
  let reviews = [];
9161
- if (existsSync16(reviewFile)) {
9393
+ if (existsSync17(reviewFile)) {
9162
9394
  try {
9163
- reviews = JSON.parse(readFileSync18(reviewFile, "utf-8"));
9395
+ reviews = JSON.parse(readFileSync19(reviewFile, "utf-8"));
9164
9396
  } catch {
9165
9397
  reviews = [];
9166
9398
  }
@@ -9177,7 +9409,7 @@ var LocalMarketplaceBackend = class {
9177
9409
  }
9178
9410
  }
9179
9411
  async report(id, reason) {
9180
- const reportFile = join17(reportsDir(), `${id}--${Date.now()}.json`);
9412
+ const reportFile = join18(reportsDir(), `${id}--${Date.now()}.json`);
9181
9413
  writeFileSync14(
9182
9414
  reportFile,
9183
9415
  JSON.stringify({ id, reason, reported_at: (/* @__PURE__ */ new Date()).toISOString() }, null, 2) + "\n"
@@ -9187,12 +9419,12 @@ var LocalMarketplaceBackend = class {
9187
9419
 
9188
9420
  // src/marketplace/api.ts
9189
9421
  function loadConfig() {
9190
- const configPath = join18(homedir3(), ".holomime", "config.json");
9191
- if (!existsSync17(configPath)) {
9422
+ const configPath = join19(homedir3(), ".holomime", "config.json");
9423
+ if (!existsSync18(configPath)) {
9192
9424
  return {};
9193
9425
  }
9194
9426
  try {
9195
- return JSON.parse(readFileSync19(configPath, "utf-8"));
9427
+ return JSON.parse(readFileSync20(configPath, "utf-8"));
9196
9428
  } catch {
9197
9429
  return {};
9198
9430
  }
@@ -10469,8 +10701,8 @@ function checkIterationBudget(currentIteration, policy) {
10469
10701
  }
10470
10702
 
10471
10703
  // src/analysis/cross-agent-sharing.ts
10472
- import { readdirSync as readdirSync7, existsSync as existsSync18 } from "fs";
10473
- import { join as join19 } from "path";
10704
+ import { readdirSync as readdirSync8, existsSync as existsSync19 } from "fs";
10705
+ import { join as join20 } from "path";
10474
10706
  function buildSharedKnowledge(graphs, repertoires) {
10475
10707
  const interventionMap = /* @__PURE__ */ new Map();
10476
10708
  const patternAgentMap = /* @__PURE__ */ new Map();
@@ -10567,15 +10799,15 @@ function discoverAgentData(baseDir) {
10567
10799
  if (mainRepertoire.interventions.some((i) => i.timesUsed > 0)) {
10568
10800
  repertoires.push(mainRepertoire);
10569
10801
  }
10570
- if (baseDir && existsSync18(baseDir)) {
10802
+ if (baseDir && existsSync19(baseDir)) {
10571
10803
  try {
10572
- const entries = readdirSync7(baseDir, { withFileTypes: true });
10804
+ const entries = readdirSync8(baseDir, { withFileTypes: true });
10573
10805
  for (const entry of entries) {
10574
10806
  if (!entry.isDirectory()) continue;
10575
- const agentDir = join19(baseDir, entry.name);
10576
- const agentGraphPath = join19(agentDir, ".holomime", "graph", "knowledge-graph.json");
10577
- const agentRepertoirePath = join19(agentDir, ".holomime", "interventions", "repertoire.json");
10578
- if (existsSync18(agentGraphPath)) {
10807
+ const agentDir = join20(baseDir, entry.name);
10808
+ const agentGraphPath = join20(agentDir, ".holomime", "graph", "knowledge-graph.json");
10809
+ const agentRepertoirePath = join20(agentDir, ".holomime", "interventions", "repertoire.json");
10810
+ if (existsSync19(agentGraphPath)) {
10579
10811
  try {
10580
10812
  const graph = JSON.parse(
10581
10813
  __require("fs").readFileSync(agentGraphPath, "utf-8")
@@ -10584,7 +10816,7 @@ function discoverAgentData(baseDir) {
10584
10816
  } catch {
10585
10817
  }
10586
10818
  }
10587
- if (existsSync18(agentRepertoirePath)) {
10819
+ if (existsSync19(agentRepertoirePath)) {
10588
10820
  try {
10589
10821
  const repertoire = JSON.parse(
10590
10822
  __require("fs").readFileSync(agentRepertoirePath, "utf-8")
@@ -10600,9 +10832,153 @@ function discoverAgentData(baseDir) {
10600
10832
  return { graphs, repertoires };
10601
10833
  }
10602
10834
 
10835
+ // src/analysis/memory-extractor.ts
10836
+ function extractMemoryFromSession(sessionLog, existingNodes) {
10837
+ const writeOps = [];
10838
+ const editOps = [];
10839
+ const deleteOps = [];
10840
+ if (sessionLog.patternsDetected) {
10841
+ for (const pattern of sessionLog.patternsDetected) {
10842
+ const existing = existingNodes.find(
10843
+ (n) => n.category === "patterns" && n.abstract.includes(pattern)
10844
+ );
10845
+ if (existing) {
10846
+ editOps.push({
10847
+ type: "edit",
10848
+ memoryId: existing.id,
10849
+ memoryType: "patterns",
10850
+ data: { confidence: Math.min(1, existing.confidence + 0.1) },
10851
+ reason: `Pattern "${pattern}" observed again in session ${sessionLog.sessionId}`
10852
+ });
10853
+ } else {
10854
+ writeOps.push({
10855
+ type: "write",
10856
+ memoryType: "patterns",
10857
+ data: {
10858
+ id: `pattern_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`,
10859
+ category: "patterns",
10860
+ level: 2 /* DETAIL */,
10861
+ abstract: `Detected pattern: ${pattern}`,
10862
+ confidence: 0.5,
10863
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
10864
+ },
10865
+ reason: `New pattern detected in session ${sessionLog.sessionId}`
10866
+ });
10867
+ }
10868
+ }
10869
+ }
10870
+ if (sessionLog.correctionsApplied) {
10871
+ for (const correction of sessionLog.correctionsApplied) {
10872
+ writeOps.push({
10873
+ type: "write",
10874
+ memoryType: "corrections",
10875
+ data: {
10876
+ id: `correction_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`,
10877
+ category: "corrections",
10878
+ level: 2 /* DETAIL */,
10879
+ abstract: `Correction applied: ${correction}`,
10880
+ confidence: 0.7,
10881
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
10882
+ },
10883
+ reason: `Correction from session ${sessionLog.sessionId}`
10884
+ });
10885
+ }
10886
+ }
10887
+ const thirtyDaysAgo = new Date(Date.now() - 30 * 24 * 60 * 60 * 1e3).toISOString();
10888
+ for (const node of existingNodes) {
10889
+ if (node.confidence < 0.3 && node.updatedAt && node.updatedAt < thirtyDaysAgo) {
10890
+ deleteOps.push(node.id);
10891
+ }
10892
+ }
10893
+ return {
10894
+ reasoning: `Session ${sessionLog.sessionId}: ${writeOps.length} new, ${editOps.length} updated, ${deleteOps.length} decayed`,
10895
+ writeOps,
10896
+ editOps,
10897
+ deleteOps
10898
+ };
10899
+ }
10900
+ function applyMemoryOperations(nodes, ops) {
10901
+ let written = 0;
10902
+ let edited = 0;
10903
+ let deleted = 0;
10904
+ const updatedNodes = [...nodes];
10905
+ for (const op of ops.writeOps) {
10906
+ if (op.data) {
10907
+ updatedNodes.push(op.data);
10908
+ written++;
10909
+ }
10910
+ }
10911
+ for (const op of ops.editOps) {
10912
+ const idx = updatedNodes.findIndex((n) => n.id === op.memoryId);
10913
+ if (idx >= 0 && op.data) {
10914
+ updatedNodes[idx] = {
10915
+ ...updatedNodes[idx],
10916
+ ...op.data,
10917
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
10918
+ };
10919
+ edited++;
10920
+ }
10921
+ }
10922
+ const deleteSet = new Set(ops.deleteOps);
10923
+ const finalNodes = updatedNodes.filter((n) => !deleteSet.has(n.id));
10924
+ deleted = updatedNodes.length - finalNodes.length;
10925
+ return {
10926
+ nodes: finalNodes,
10927
+ result: { written, edited, deleted, operations: ops }
10928
+ };
10929
+ }
10930
+
10931
+ // src/analysis/memory-retriever.ts
10932
+ function recommendTier2(context) {
10933
+ if (context.isTherapySession) return 2 /* DETAIL */;
10934
+ if (context.driftDetected) return 1 /* OVERVIEW */;
10935
+ if (context.highThroughput) return 0 /* ABSTRACT */;
10936
+ return 1 /* OVERVIEW */;
10937
+ }
10938
+ function retrieveMemory(query, nodes, options) {
10939
+ const tier = options?.tier ?? query.suggestedTier ?? 1 /* OVERVIEW */;
10940
+ const maxResults = options?.maxResults ?? 5;
10941
+ const minConfidence = options?.minConfidence ?? 0.2;
10942
+ let candidates = query.category ? nodes.filter((n) => n.category === query.category) : nodes;
10943
+ candidates = candidates.filter((n) => n.confidence >= minConfidence);
10944
+ const queryWords = query.text.toLowerCase().split(/\s+/);
10945
+ const scored = candidates.map((node) => {
10946
+ const text = `${node.abstract} ${node.overview || ""}`.toLowerCase();
10947
+ const matchCount = queryWords.filter((w) => text.includes(w)).length;
10948
+ const score = matchCount / queryWords.length;
10949
+ return { node, score };
10950
+ });
10951
+ scored.sort((a, b) => b.score - a.score);
10952
+ const topResults = scored.slice(0, maxResults);
10953
+ const tokensPerItem = tier === 0 /* ABSTRACT */ ? 25 : tier === 1 /* OVERVIEW */ ? 200 : 500;
10954
+ return {
10955
+ items: topResults.map((r) => r.node),
10956
+ tierUsed: tier,
10957
+ estimatedTokens: topResults.length * tokensPerItem,
10958
+ matchScores: topResults.map((r) => r.score)
10959
+ };
10960
+ }
10961
+ function compileMemoryForPrompt(nodes, tier) {
10962
+ if (nodes.length === 0) return "";
10963
+ const lines = ["## Behavioral Memory"];
10964
+ for (const node of nodes) {
10965
+ if (tier === 0 /* ABSTRACT */) {
10966
+ lines.push(`- ${node.abstract}`);
10967
+ } else if (tier === 1 /* OVERVIEW */) {
10968
+ lines.push(`### ${node.abstract}`);
10969
+ if (node.overview) lines.push(node.overview);
10970
+ } else {
10971
+ lines.push(`### ${node.abstract}`);
10972
+ if (node.overview) lines.push(node.overview);
10973
+ if (node.fullData) lines.push("```json", JSON.stringify(node.fullData, null, 2), "```");
10974
+ }
10975
+ }
10976
+ return lines.join("\n");
10977
+ }
10978
+
10603
10979
  // src/analysis/network-core.ts
10604
- import { existsSync as existsSync19, readdirSync as readdirSync8, readFileSync as readFileSync20 } from "fs";
10605
- import { join as join20, resolve as resolve16 } from "path";
10980
+ import { existsSync as existsSync20, readdirSync as readdirSync9, readFileSync as readFileSync21 } from "fs";
10981
+ import { join as join21, resolve as resolve16 } from "path";
10606
10982
 
10607
10983
  // src/psychology/therapist-meta.ts
10608
10984
  var THERAPIST_META_SPEC = {
@@ -10738,21 +11114,21 @@ Your patient is another AI agent with its own personality spec:
10738
11114
  // src/analysis/network-core.ts
10739
11115
  function discoverNetworkAgents(dir) {
10740
11116
  const absDir = resolve16(dir);
10741
- if (!existsSync19(absDir)) {
11117
+ if (!existsSync20(absDir)) {
10742
11118
  throw new Error(`Directory not found: ${absDir}`);
10743
11119
  }
10744
11120
  const agents = [];
10745
- const entries = readdirSync8(absDir, { withFileTypes: true });
11121
+ const entries = readdirSync9(absDir, { withFileTypes: true });
10746
11122
  for (const entry of entries) {
10747
11123
  if (!entry.isDirectory()) continue;
10748
- const agentDir = join20(absDir, entry.name);
10749
- const specPath = join20(agentDir, ".personality.json");
10750
- const logDir = join20(agentDir, "logs");
10751
- if (existsSync19(specPath)) {
11124
+ const agentDir = join21(absDir, entry.name);
11125
+ const specPath = join21(agentDir, ".personality.json");
11126
+ const logDir = join21(agentDir, "logs");
11127
+ if (existsSync20(specPath)) {
10752
11128
  agents.push({
10753
11129
  name: entry.name,
10754
11130
  specPath,
10755
- logDir: existsSync19(logDir) ? logDir : agentDir,
11131
+ logDir: existsSync20(logDir) ? logDir : agentDir,
10756
11132
  role: "both"
10757
11133
  });
10758
11134
  }
@@ -10760,7 +11136,7 @@ function discoverNetworkAgents(dir) {
10760
11136
  return agents;
10761
11137
  }
10762
11138
  function loadNetworkConfig(configPath) {
10763
- const raw = JSON.parse(readFileSync20(configPath, "utf-8"));
11139
+ const raw = JSON.parse(readFileSync21(configPath, "utf-8"));
10764
11140
  if (!raw.agents || !Array.isArray(raw.agents)) {
10765
11141
  throw new Error("network.json must contain an 'agents' array");
10766
11142
  }
@@ -10946,7 +11322,7 @@ async function runNetwork(config, provider, callbacks) {
10946
11322
  const spec = loadSpec(agent.specPath);
10947
11323
  agentSpecs.set(agent.name, spec);
10948
11324
  let messages = [];
10949
- if (agent.logDir && existsSync19(agent.logDir)) {
11325
+ if (agent.logDir && existsSync20(agent.logDir)) {
10950
11326
  messages = loadAgentMessages(agent.logDir);
10951
11327
  }
10952
11328
  agentMessages.set(agent.name, messages);
@@ -11063,15 +11439,15 @@ async function runNetwork(config, provider, callbacks) {
11063
11439
  };
11064
11440
  }
11065
11441
  function loadAgentMessages(logDir) {
11066
- if (!existsSync19(logDir)) return [];
11442
+ if (!existsSync20(logDir)) return [];
11067
11443
  const messages = [];
11068
11444
  try {
11069
- const files = readdirSync8(logDir).filter(
11445
+ const files = readdirSync9(logDir).filter(
11070
11446
  (f) => f.endsWith(".json") || f.endsWith(".jsonl")
11071
11447
  );
11072
11448
  for (const file of files.slice(0, 10)) {
11073
11449
  try {
11074
- const raw = readFileSync20(join20(logDir, file), "utf-8");
11450
+ const raw = readFileSync21(join21(logDir, file), "utf-8");
11075
11451
  const data = JSON.parse(raw);
11076
11452
  const conversations = parseConversationLog(data);
11077
11453
  for (const conv of conversations) {
@@ -11086,8 +11462,8 @@ function loadAgentMessages(logDir) {
11086
11462
  }
11087
11463
 
11088
11464
  // src/compliance/audit-trail.ts
11089
- import { readFileSync as readFileSync21, appendFileSync as appendFileSync2, existsSync as existsSync20, mkdirSync as mkdirSync13 } from "fs";
11090
- import { join as join21, resolve as resolve17 } from "path";
11465
+ import { readFileSync as readFileSync22, appendFileSync as appendFileSync2, existsSync as existsSync21, mkdirSync as mkdirSync13 } from "fs";
11466
+ import { join as join22, resolve as resolve17 } from "path";
11091
11467
  function djb2(str) {
11092
11468
  let hash = 5381;
11093
11469
  for (let i = 0; i < str.length; i++) {
@@ -11101,16 +11477,16 @@ function hashEntry(entry) {
11101
11477
  }
11102
11478
  function auditLogPath(agentHandle) {
11103
11479
  const dir = resolve17(process.cwd(), ".holomime", "audit");
11104
- if (!existsSync20(dir)) mkdirSync13(dir, { recursive: true });
11480
+ if (!existsSync21(dir)) mkdirSync13(dir, { recursive: true });
11105
11481
  const filename = agentHandle ? `${agentHandle}-audit.jsonl` : "audit.jsonl";
11106
- return join21(dir, filename);
11482
+ return join22(dir, filename);
11107
11483
  }
11108
11484
  function appendAuditEntry(event, agent, data, agentHandle) {
11109
11485
  const logPath = auditLogPath(agentHandle);
11110
11486
  let prevHash = "genesis";
11111
11487
  let seq = 1;
11112
- if (existsSync20(logPath)) {
11113
- const lines = readFileSync21(logPath, "utf-8").trim().split("\n").filter(Boolean);
11488
+ if (existsSync21(logPath)) {
11489
+ const lines = readFileSync22(logPath, "utf-8").trim().split("\n").filter(Boolean);
11114
11490
  if (lines.length > 0) {
11115
11491
  try {
11116
11492
  const lastEntry = JSON.parse(lines[lines.length - 1]);
@@ -11137,8 +11513,8 @@ function appendAuditEntry(event, agent, data, agentHandle) {
11137
11513
  }
11138
11514
  function loadAuditLog(agentHandle) {
11139
11515
  const logPath = auditLogPath(agentHandle);
11140
- if (!existsSync20(logPath)) return [];
11141
- return readFileSync21(logPath, "utf-8").trim().split("\n").filter(Boolean).map((line) => {
11516
+ if (!existsSync21(logPath)) return [];
11517
+ return readFileSync22(logPath, "utf-8").trim().split("\n").filter(Boolean).map((line) => {
11142
11518
  try {
11143
11519
  return JSON.parse(line);
11144
11520
  } catch {
@@ -11261,9 +11637,9 @@ function formatComplianceReportMarkdown(report) {
11261
11637
  }
11262
11638
 
11263
11639
  // src/compliance/iso-mappings.ts
11264
- import { readFileSync as readFileSync22, existsSync as existsSync21 } from "fs";
11265
- import { join as join22, resolve as resolve18, dirname as dirname4 } from "path";
11266
- import { parse as parseYaml3 } from "yaml";
11640
+ import { readFileSync as readFileSync23, existsSync as existsSync22 } from "fs";
11641
+ import { join as join23, resolve as resolve18, dirname as dirname4 } from "path";
11642
+ import { parse as parseYaml4 } from "yaml";
11267
11643
  import { fileURLToPath as fileURLToPath2 } from "url";
11268
11644
  var KNOWN_STANDARDS = {
11269
11645
  "iso-13482": "iso-13482.yaml",
@@ -11275,8 +11651,8 @@ function getRegistryDir() {
11275
11651
  const thisFile = typeof __filename !== "undefined" ? __filename : fileURLToPath2(import.meta.url);
11276
11652
  let dir = dirname4(thisFile);
11277
11653
  for (let i = 0; i < 6; i++) {
11278
- const candidate = join22(dir, "registry", "compliance");
11279
- if (existsSync21(candidate)) return candidate;
11654
+ const candidate = join23(dir, "registry", "compliance");
11655
+ if (existsSync22(candidate)) return candidate;
11280
11656
  dir = dirname4(dir);
11281
11657
  }
11282
11658
  return resolve18(process.cwd(), "registry", "compliance");
@@ -11284,15 +11660,15 @@ function getRegistryDir() {
11284
11660
  function loadStandard(name) {
11285
11661
  const registryDir = getRegistryDir();
11286
11662
  const filename = KNOWN_STANDARDS[name] ?? `${name}.yaml`;
11287
- const filepath = join22(registryDir, filename);
11288
- if (!existsSync21(filepath)) {
11663
+ const filepath = join23(registryDir, filename);
11664
+ if (!existsSync22(filepath)) {
11289
11665
  throw new Error(
11290
11666
  `ISO standard mapping not found: ${filepath}
11291
11667
  Available standards: ${Object.keys(KNOWN_STANDARDS).join(", ")}`
11292
11668
  );
11293
11669
  }
11294
- const content = readFileSync22(filepath, "utf-8");
11295
- const parsed = parseYaml3(content);
11670
+ const content = readFileSync23(filepath, "utf-8");
11671
+ const parsed = parseYaml4(content);
11296
11672
  if (!parsed.standard || !parsed.clauses || !Array.isArray(parsed.clauses)) {
11297
11673
  throw new Error(`Invalid ISO mapping file: ${filepath} \u2014 missing 'standard' or 'clauses'`);
11298
11674
  }
@@ -13246,13 +13622,13 @@ var HolomimeViolationError = class extends Error {
13246
13622
  };
13247
13623
 
13248
13624
  // src/integrations/openclaw.ts
13249
- import { readFileSync as readFileSync23, existsSync as existsSync22 } from "fs";
13625
+ import { readFileSync as readFileSync24, existsSync as existsSync23 } from "fs";
13250
13626
  import { resolve as resolve19 } from "path";
13251
13627
  function loadSpec2(specPath) {
13252
13628
  const resolved = resolve19(process.cwd(), specPath);
13253
- if (!existsSync22(resolved)) return null;
13629
+ if (!existsSync23(resolved)) return null;
13254
13630
  try {
13255
- return JSON.parse(readFileSync23(resolved, "utf-8"));
13631
+ return JSON.parse(readFileSync24(resolved, "utf-8"));
13256
13632
  } catch {
13257
13633
  return null;
13258
13634
  }
@@ -13414,6 +13790,7 @@ export {
13414
13790
  AnthropicProvider,
13415
13791
  BUILT_IN_DETECTORS,
13416
13792
  CATEGORIES,
13793
+ DEFAULT_MODEL_CONFIG,
13417
13794
  DEFAULT_OVERSIGHT,
13418
13795
  DIMENSIONS,
13419
13796
  Guard,
@@ -13423,6 +13800,8 @@ export {
13423
13800
  LEARNING_ORIENTATIONS,
13424
13801
  LocalMarketplaceBackend,
13425
13802
  MarketplaceClient,
13803
+ MemoryLevel,
13804
+ ModelRouter,
13426
13805
  OllamaProvider,
13427
13806
  OpenAIProvider,
13428
13807
  PROVIDER_PARAMS,
@@ -13438,6 +13817,7 @@ export {
13438
13817
  agentHandleFromSpec,
13439
13818
  appendAuditEntry,
13440
13819
  appendEvolution,
13820
+ applyMemoryOperations,
13441
13821
  applyRecommendations,
13442
13822
  bigFiveSchema,
13443
13823
  bodySchema,
@@ -13463,6 +13843,7 @@ export {
13463
13843
  compileL0,
13464
13844
  compileL1,
13465
13845
  compileL2,
13846
+ compileMemoryForPrompt,
13466
13847
  compileStack,
13467
13848
  compileTiered,
13468
13849
  compiledConfigSchema,
@@ -13509,6 +13890,7 @@ export {
13509
13890
  emitBehavioralEvent,
13510
13891
  encodeSnapshot,
13511
13892
  estimateConfidence,
13893
+ evaluateConscienceGate,
13512
13894
  evaluateOutcome,
13513
13895
  expireOldEdges,
13514
13896
  exportTrainingData,
@@ -13516,11 +13898,13 @@ export {
13516
13898
  extractAlpacaExamples,
13517
13899
  extractDPOPairs,
13518
13900
  extractDPOPairsWithLLM,
13901
+ extractMemoryFromSession,
13519
13902
  extractRLHFExamples,
13520
13903
  extractRecommendations,
13521
13904
  fetchLeaderboard,
13522
13905
  fetchPersonality,
13523
13906
  fetchRegistry,
13907
+ filterByConfig,
13524
13908
  findCrossAgentCorrelations,
13525
13909
  findEdges,
13526
13910
  findNode,
@@ -13576,6 +13960,7 @@ export {
13576
13960
  growthSchema,
13577
13961
  hapticPolicySchema,
13578
13962
  hashSpec2 as hashSpec,
13963
+ injectConscienceRules,
13579
13964
  isStackDirectory,
13580
13965
  learnIntervention,
13581
13966
  listArchetypeIds,
@@ -13587,6 +13972,7 @@ export {
13587
13972
  loadAuditLog,
13588
13973
  loadBehavioralMemory,
13589
13974
  loadBenchmarkResults,
13975
+ loadConscienceRules,
13590
13976
  loadCorpus,
13591
13977
  loadCustomDetectors,
13592
13978
  loadEvolution,
@@ -13601,6 +13987,9 @@ export {
13601
13987
  loadStandard,
13602
13988
  loadTranscripts,
13603
13989
  loadTreatmentPlan,
13990
+ memoryNodeSchema,
13991
+ memoryOperationSchema,
13992
+ memorySchema,
13604
13993
  mergeStores,
13605
13994
  messageSchema,
13606
13995
  mindSchema,
@@ -13611,6 +14000,7 @@ export {
13611
14000
  parseAnthropicAPILog,
13612
14001
  parseChatGPTExport,
13613
14002
  parseClaudeExport,
14003
+ parseConscienceRule,
13614
14004
  parseConversationLog,
13615
14005
  parseConversationLogFromString,
13616
14006
  parseJSONLLog,
@@ -13633,6 +14023,7 @@ export {
13633
14023
  queryCorpus,
13634
14024
  queryInterventions,
13635
14025
  querySharedKnowledge,
14026
+ recommendTier2 as recommendMemoryTier,
13636
14027
  recommendTier,
13637
14028
  recordInterventionOutcome,
13638
14029
  recordObservation,
@@ -13644,6 +14035,8 @@ export {
13644
14035
  resetMarketplaceClient,
13645
14036
  resolveInheritance,
13646
14037
  resolveOversight,
14038
+ retrievalStepSchema,
14039
+ retrieveMemory,
13647
14040
  runAdversarialSuite,
13648
14041
  runAssessment,
13649
14042
  runAutopilot,