@remnic/plugin-openclaw 1.0.11 → 1.0.12

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.
Files changed (24) hide show
  1. package/dist/capsule-cli-GBM3WPAM.js +33 -0
  2. package/dist/capsule-export-IXVERCQG.js +17 -0
  3. package/dist/{capsule-import-CFX7BY5W.js → capsule-import-IA6VIOPQ.js} +3 -3
  4. package/dist/{capsule-merge-7RVOHJK3.js → capsule-merge-IWOQ34KL.js} +2 -2
  5. package/dist/{causal-consolidation-JD6KJJH6.js → causal-consolidation-YI53C2AO.js} +3 -3
  6. package/dist/{chunk-K7EUBNDD.js → chunk-4LYQ4ONL.js} +1 -1
  7. package/dist/{chunk-N7EOZY6F.js → chunk-6F6EKSVP.js} +54 -1
  8. package/dist/{chunk-TNH24SF6.js → chunk-7UZNLMW5.js} +301 -125
  9. package/dist/{chunk-TVKKIS53.js → chunk-CDAZGIGT.js} +1 -1
  10. package/dist/{chunk-XMSDA5WA.js → chunk-EXDYWXMB.js} +1 -0
  11. package/dist/{capsule-export-CVA3CKUQ.js → chunk-FGTYFLL5.js} +21 -12
  12. package/dist/{chunk-ETJZRIAM.js → chunk-L6I4MQKO.js} +1 -1
  13. package/dist/{capsule-cli-TFKLAG3S.js → chunk-LLUROTZJ.js} +11 -12
  14. package/dist/{chunk-L4PRBB2A.js → chunk-OAE7AQ6R.js} +63 -91
  15. package/dist/{chunk-3I7RHWYT.js → chunk-RKR6PTPA.js} +105 -11
  16. package/dist/{chunk-P3DIW2SD.js → chunk-TILAJIJR.js} +1 -1
  17. package/dist/{engine-VMTFKFGO.js → engine-BIYI3P4J.js} +6 -4
  18. package/dist/index.js +1020 -308
  19. package/dist/{memory-governance-DWGFV4FX.js → memory-governance-SJ5DGRB3.js} +3 -3
  20. package/dist/{secure-store-FWJ7LBPH.js → secure-store-A4NGCNXV.js} +8 -2
  21. package/dist/{storage-T2OGFUF4.js → storage-PTQ2H2YJ.js} +2 -2
  22. package/dist/{types-H5R5D3WF.js → types-R4DO7AKM.js} +2 -2
  23. package/package.json +2 -2
  24. package/dist/chunk-YGXXBRV7.js +0 -10
@@ -3,7 +3,7 @@ import {
3
3
  } from "./chunk-4G2XCSD2.js";
4
4
  import {
5
5
  StorageManager
6
- } from "./chunk-TNH24SF6.js";
6
+ } from "./chunk-7UZNLMW5.js";
7
7
 
8
8
  // ../remnic-core/src/maintenance/memory-governance.ts
9
9
  import path from "path";
@@ -4044,5 +4044,6 @@ var coerce = {
4044
4044
  var NEVER = INVALID;
4045
4045
 
4046
4046
  export {
4047
+ ZodError,
4047
4048
  external_exports
4048
4049
  };
@@ -1,13 +1,9 @@
1
- import {
2
- CAPSULE_SCHEMA_VERSION,
3
- EXPORT_FORMAT
4
- } from "./chunk-YGXXBRV7.js";
5
1
  import {
6
2
  CAPSULE_ID_PATTERN,
7
3
  CapsuleBlockSchema,
8
4
  ExportBundleV2Schema,
9
5
  ExportManifestV2Schema
10
- } from "./chunk-K7EUBNDD.js";
6
+ } from "./chunk-4LYQ4ONL.js";
11
7
  import {
12
8
  listFilesRecursive,
13
9
  sha256File,
@@ -17,17 +13,18 @@ import {
17
13
  import {
18
14
  encryptCapsuleFile
19
15
  } from "./chunk-SSFTU6LP.js";
20
- import "./chunk-XMSDA5WA.js";
21
- import "./chunk-CXM7EBAO.js";
22
- import "./chunk-JZBOXOUC.js";
23
- import "./chunk-6IWEAUN6.js";
24
- import "./chunk-YGGGUTG3.js";
25
- import "./chunk-MLKGABMK.js";
26
16
 
27
17
  // ../remnic-core/src/transfer/capsule-export.ts
28
18
  import { mkdir, readFile, stat, writeFile } from "fs/promises";
29
19
  import path from "path";
30
20
  import { gzipSync } from "zlib";
21
+
22
+ // ../remnic-core/src/transfer/constants.ts
23
+ var EXPORT_FORMAT = "openclaw-engram-export";
24
+ var EXPORT_SCHEMA_VERSION = 1;
25
+ var CAPSULE_SCHEMA_VERSION = 2;
26
+
27
+ // ../remnic-core/src/transfer/capsule-export.ts
31
28
  var DEFAULT_EXCLUDE_DIRS = /* @__PURE__ */ new Set([
32
29
  "node_modules",
33
30
  ".git",
@@ -145,6 +142,14 @@ function parseSince(since) {
145
142
  assertCalendarRoundTrip(since, ms);
146
143
  return ms;
147
144
  }
145
+ function isValidCapsuleSince(since) {
146
+ try {
147
+ parseSince(since);
148
+ return true;
149
+ } catch {
150
+ return false;
151
+ }
152
+ }
148
153
  function assertCalendarRoundTrip(since, ms) {
149
154
  const m = /^(\d{4})-(\d{2})-(\d{2})/.exec(since);
150
155
  if (!m) return;
@@ -260,6 +265,10 @@ function buildCapsuleBlock(name, override) {
260
265
  };
261
266
  return CapsuleBlockSchema.parse(merged);
262
267
  }
268
+
263
269
  export {
264
- exportCapsule
270
+ EXPORT_FORMAT,
271
+ EXPORT_SCHEMA_VERSION,
272
+ exportCapsule,
273
+ isValidCapsuleSince
265
274
  };
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  parseExportBundle
3
- } from "./chunk-K7EUBNDD.js";
3
+ } from "./chunk-4LYQ4ONL.js";
4
4
  import {
5
5
  assertIsDirectoryNotSymlink,
6
6
  assertRealpathInsideRoot,
@@ -1,5 +1,3 @@
1
- import "./chunk-MLKGABMK.js";
2
-
3
1
  // ../remnic-core/src/capsule-cli.ts
4
2
  import path from "path";
5
3
  function parseCapsuleOutputFormat(raw) {
@@ -311,19 +309,20 @@ function renderCapsuleInspect(manifest, format) {
311
309
  }
312
310
  return lines.join("\n") + "\n";
313
311
  }
312
+
314
313
  export {
315
- defaultCapsulesDir,
314
+ parseCapsuleOutputFormat,
315
+ parseCapsuleImportMode,
316
316
  parseCapsuleConflictMode,
317
+ parseCapsuleSince,
318
+ parseCapsuleIncludeKinds,
319
+ parseCapsulePeers,
317
320
  parseCapsuleExportOptions,
318
- parseCapsuleImportMode,
319
321
  parseCapsuleImportOptions,
320
- parseCapsuleIncludeKinds,
321
- parseCapsuleInspectOptions,
322
- parseCapsuleListOptions,
323
322
  parseCapsuleMergeOptions,
324
- parseCapsuleOutputFormat,
325
- parseCapsulePeers,
326
- parseCapsuleSince,
327
- renderCapsuleInspect,
328
- renderCapsuleList
323
+ parseCapsuleListOptions,
324
+ parseCapsuleInspectOptions,
325
+ defaultCapsulesDir,
326
+ renderCapsuleList,
327
+ renderCapsuleInspect
329
328
  };
@@ -1,26 +1,26 @@
1
1
  import {
2
2
  external_exports
3
- } from "./chunk-XMSDA5WA.js";
3
+ } from "./chunk-EXDYWXMB.js";
4
4
  import {
5
5
  StorageManager,
6
6
  parseContinuityImprovementLoops,
7
- parseContinuityIncident,
8
7
  sanitizeMemoryContent
9
- } from "./chunk-TNH24SF6.js";
8
+ } from "./chunk-7UZNLMW5.js";
10
9
  import {
11
10
  log
12
11
  } from "./chunk-UFU5GGGA.js";
12
+ import {
13
+ expandTildePath
14
+ } from "./chunk-OEI7GLV2.js";
13
15
 
14
16
  // ../remnic-core/src/compounding/engine.ts
15
17
  import { createHash } from "crypto";
16
18
  import { mkdir as mkdir2, readFile as readFile2, readdir as readdir2, unlink, writeFile as writeFile2 } from "fs/promises";
17
19
  import path2 from "path";
18
- import os2 from "os";
19
20
 
20
21
  // ../remnic-core/src/shared-context/manager.ts
21
22
  import { mkdir, readFile, readdir, appendFile, writeFile, stat } from "fs/promises";
22
23
  import path from "path";
23
- import os from "os";
24
24
  var SharedFeedbackEntrySchema = external_exports.object({
25
25
  agent: external_exports.string().min(1),
26
26
  decision: external_exports.enum(["approved", "approved_with_feedback", "rejected"]),
@@ -256,10 +256,13 @@ function formatFeedbackLine(entry) {
256
256
  function formatOverlapLine(entry) {
257
257
  return `- \`${entry.token}\` (${entry.agentCount} agents: ${entry.agents.join(", ")}) [sources: ${entry.sourcePaths.join(", ")}]`;
258
258
  }
259
+ function resolveSharedContextDir(config) {
260
+ return typeof config.sharedContextDir === "string" && config.sharedContextDir.length > 0 ? expandTildePath(config.sharedContextDir) : path.join(expandTildePath(config.workspaceDir), "shared-context");
261
+ }
259
262
  var SharedContextManager = class {
260
263
  constructor(config) {
261
264
  this.config = config;
262
- const base = typeof config.sharedContextDir === "string" && config.sharedContextDir.length > 0 ? config.sharedContextDir : path.join(os.homedir(), ".openclaw", "workspace", "shared-context");
265
+ const base = resolveSharedContextDir(config);
263
266
  this.dir = base;
264
267
  this.prioritiesPath = path.join(base, "priorities.md");
265
268
  this.prioritiesInboxPath = path.join(base, "priorities.inbox.md");
@@ -764,12 +767,6 @@ function monthIdFromIsoWeek(weekId) {
764
767
  monday.setUTCDate(isoWeekOneMonday.getUTCDate() + (week - 1) * 7);
765
768
  return isoMonthId(monday);
766
769
  }
767
- function sharedContextDir(config) {
768
- if (typeof config.sharedContextDir === "string" && config.sharedContextDir.length > 0) {
769
- return config.sharedContextDir;
770
- }
771
- return path2.join(os2.homedir(), ".openclaw", "workspace", "shared-context");
772
- }
773
770
  function cadenceStaleWindowMs(cadence) {
774
771
  switch (cadence) {
775
772
  case "daily":
@@ -785,8 +782,9 @@ function cadenceStaleWindowMs(cadence) {
785
782
  }
786
783
  }
787
784
  var CompoundingEngine = class {
788
- constructor(config) {
785
+ constructor(config, storage = new StorageManager(config.memoryDir)) {
789
786
  this.config = config;
787
+ this.storage = storage;
790
788
  this.weeklyDir = path2.join(config.memoryDir, "compounding", "weekly");
791
789
  this.rubricsDir = path2.join(config.memoryDir, "compounding", "rubrics");
792
790
  this.rubricsIndexPath = path2.join(this.rubricsDir, "index.json");
@@ -794,15 +792,13 @@ var CompoundingEngine = class {
794
792
  this.rubricsWorkflowsDir = path2.join(this.rubricsDir, "workflows");
795
793
  this.rubricsPath = path2.join(config.memoryDir, "compounding", "rubrics.md");
796
794
  this.mistakesPath = path2.join(config.memoryDir, "compounding", "mistakes.json");
797
- this.feedbackInboxPath = path2.join(sharedContextDir(config), "feedback", "inbox.jsonl");
798
- this.identityAnchorPath = path2.join(config.memoryDir, "identity", "identity-anchor.md");
799
- this.identityIncidentsDir = path2.join(config.memoryDir, "identity", "incidents");
795
+ this.feedbackInboxPath = path2.join(resolveSharedContextDir(config), "feedback", "inbox.jsonl");
800
796
  this.identityAuditWeeklyDir = path2.join(config.memoryDir, "identity", "audits", "weekly");
801
797
  this.identityAuditMonthlyDir = path2.join(config.memoryDir, "identity", "audits", "monthly");
802
- this.identityImprovementLoopsPath = path2.join(config.memoryDir, "identity", "improvement-loops.md");
803
798
  this.memoryActionEventsPath = path2.join(config.memoryDir, "state", "memory-actions.jsonl");
804
799
  }
805
800
  config;
801
+ storage;
806
802
  weeklyDir;
807
803
  rubricsDir;
808
804
  rubricsIndexPath;
@@ -811,11 +807,8 @@ var CompoundingEngine = class {
811
807
  rubricsPath;
812
808
  mistakesPath;
813
809
  feedbackInboxPath;
814
- identityAnchorPath;
815
- identityIncidentsDir;
816
810
  identityAuditWeeklyDir;
817
811
  identityAuditMonthlyDir;
818
- identityImprovementLoopsPath;
819
812
  memoryActionEventsPath;
820
813
  async ensureDirs() {
821
814
  await mkdir2(this.weeklyDir, { recursive: true });
@@ -838,7 +831,7 @@ var CompoundingEngine = class {
838
831
  let promotionCandidates = this.config.compoundingSemanticEnabled ? this.derivePromotionCandidates(outcomeSummary, mistakes.registry, rubrics) : [];
839
832
  if (this.config.cmcConsolidationEnabled) {
840
833
  try {
841
- const { deriveCausalPromotionCandidates, materializeAfterCausalConsolidation } = await import("./causal-consolidation-JD6KJJH6.js");
834
+ const { deriveCausalPromotionCandidates, materializeAfterCausalConsolidation } = await import("./causal-consolidation-YI53C2AO.js");
842
835
  const causalCandidates = await deriveCausalPromotionCandidates({
843
836
  memoryDir: this.config.memoryDir,
844
837
  causalTrajectoryStoreDir: this.config.causalTrajectoryStoreDir,
@@ -1030,13 +1023,14 @@ var CompoundingEngine = class {
1030
1023
  const period = opts?.period === "monthly" ? "monthly" : "weekly";
1031
1024
  const key = opts?.key?.trim() || (period === "weekly" ? isoWeekId(/* @__PURE__ */ new Date()) : isoMonthId(/* @__PURE__ */ new Date()));
1032
1025
  const nowIso = (/* @__PURE__ */ new Date()).toISOString();
1033
- const [anchorPresent, improvementLoopsRaw, openIncidents, closedIncidents, mistakes] = await Promise.all([
1034
- this.readNonEmptyFile(this.identityAnchorPath),
1035
- this.readOptionalFile(this.identityImprovementLoopsPath),
1036
- this.readContinuityIncidents(200, "open"),
1037
- this.readContinuityIncidents(200, "closed"),
1026
+ const [identityAnchor, improvementLoopsRaw, openIncidents, closedIncidents, mistakes] = await Promise.all([
1027
+ this.readOptionalIdentityAnchorForAudit(),
1028
+ this.readOptionalImprovementLoopsForAudit(),
1029
+ this.readContinuityIncidentsForAudit(200, "open"),
1030
+ this.readContinuityIncidentsForAudit(200, "closed"),
1038
1031
  this.readMistakes()
1039
1032
  ]);
1033
+ const anchorPresent = (identityAnchor ?? "").trim().length > 0;
1040
1034
  const improvementLoops = improvementLoopsRaw ? parseContinuityImprovementLoops(improvementLoopsRaw) : [];
1041
1035
  const activeLoops = improvementLoops.filter((loop) => loop.status === "active");
1042
1036
  const staleActiveLoops = activeLoops.filter((loop) => {
@@ -1097,10 +1091,7 @@ var CompoundingEngine = class {
1097
1091
  ...openIncidents.length > 0 ? openIncidents.slice(0, 20).map((i) => `- ${i.id}`) : ["- (none)"],
1098
1092
  ""
1099
1093
  ];
1100
- const dir = period === "weekly" ? this.identityAuditWeeklyDir : this.identityAuditMonthlyDir;
1101
- await mkdir2(dir, { recursive: true });
1102
- const reportPath = path2.join(dir, `${key}.md`);
1103
- await writeFile2(reportPath, lines.join("\n"), "utf-8");
1094
+ const reportPath = await this.storage.writeIdentityAudit(period, key, lines.join("\n"));
1104
1095
  return { period, key, reportPath };
1105
1096
  }
1106
1097
  async readMistakes() {
@@ -1254,29 +1245,19 @@ var CompoundingEngine = class {
1254
1245
  }
1255
1246
  async readActionEventsForWeek(weekId) {
1256
1247
  const out = [];
1257
- try {
1258
- const raw = await readFile2(this.memoryActionEventsPath, "utf-8");
1259
- const lines = raw.split("\n");
1260
- for (let idx = 0; idx < lines.length; idx += 1) {
1261
- const line = lines[idx];
1262
- if (!line.trim()) continue;
1263
- try {
1264
- const parsed = JSON.parse(line);
1265
- if (typeof parsed.timestamp !== "string" || typeof parsed.action !== "string") continue;
1266
- const ts = new Date(parsed.timestamp);
1267
- if (!Number.isFinite(ts.getTime()) || isoWeekId(ts) !== weekId) continue;
1268
- out.push({
1269
- line: idx + 1,
1270
- action: parsed.action,
1271
- outcome: parsed.outcome === "applied" || parsed.outcome === "skipped" || parsed.outcome === "failed" ? parsed.outcome : "unknown",
1272
- policyDecision: parsed.policyDecision === "deny" || parsed.policyDecision === "defer" ? parsed.policyDecision : null,
1273
- namespace: typeof parsed.namespace === "string" && parsed.namespace.length > 0 ? parsed.namespace : "default",
1274
- reason: typeof parsed.reason === "string" ? parsed.reason : null
1275
- });
1276
- } catch {
1277
- }
1278
- }
1279
- } catch {
1248
+ const rows = await this.storage.readMemoryActionEventRows(Number.MAX_SAFE_INTEGER);
1249
+ for (const row of rows) {
1250
+ const event = row.event;
1251
+ const ts = new Date(event.timestamp);
1252
+ if (!Number.isFinite(ts.getTime()) || isoWeekId(ts) !== weekId) continue;
1253
+ out.push({
1254
+ line: row.line,
1255
+ action: event.action,
1256
+ outcome: event.outcome,
1257
+ policyDecision: event.policyDecision === "deny" || event.policyDecision === "defer" ? event.policyDecision : null,
1258
+ namespace: typeof event.namespace === "string" && event.namespace.length > 0 ? event.namespace : "default",
1259
+ reason: typeof event.reason === "string" ? event.reason : null
1260
+ });
1280
1261
  }
1281
1262
  return out;
1282
1263
  }
@@ -1285,19 +1266,18 @@ var CompoundingEngine = class {
1285
1266
  for (const event of events) {
1286
1267
  const key = event.action;
1287
1268
  const acc = byAction.get(key) ?? {
1288
- counts: { applied: 0, skipped: 0, failed: 0, unknown: 0 },
1269
+ counts: { applied: 0, skipped: 0, failed: 0 },
1289
1270
  provenance: /* @__PURE__ */ new Set()
1290
1271
  };
1291
1272
  if (event.outcome === "applied") acc.counts.applied += 1;
1292
1273
  else if (event.outcome === "skipped") acc.counts.skipped += 1;
1293
- else if (event.outcome === "failed") acc.counts.failed += 1;
1294
- else acc.counts.unknown += 1;
1274
+ else acc.counts.failed += 1;
1295
1275
  acc.provenance.add(`${path2.basename(this.memoryActionEventsPath)}:L${event.line}`);
1296
1276
  byAction.set(key, acc);
1297
1277
  }
1298
1278
  const out = [];
1299
1279
  for (const [action, data] of byAction.entries()) {
1300
- const total = data.counts.applied + data.counts.skipped + data.counts.failed + data.counts.unknown;
1280
+ const total = data.counts.applied + data.counts.skipped + data.counts.failed;
1301
1281
  if (total <= 0) continue;
1302
1282
  const weightedScore = Number(((data.counts.applied * 1 - data.counts.skipped * 0.5 - data.counts.failed * 1.5) / total).toFixed(3));
1303
1283
  out.push({
@@ -1334,7 +1314,7 @@ var CompoundingEngine = class {
1334
1314
  if (item.total < 3) continue;
1335
1315
  if (item.weightedScore < 0.3) continue;
1336
1316
  const content = normalizePromotedGuidanceContent(
1337
- `Prefer ${item.action} when the same workflow recurs; this week's outcomes were applied=${item.counts.applied}, skipped=${item.counts.skipped}, failed=${item.counts.failed}, unknown=${item.counts.unknown}.`
1317
+ `Prefer ${item.action} when the same workflow recurs; this week's outcomes were applied=${item.counts.applied}, skipped=${item.counts.skipped}, failed=${item.counts.failed}.`
1338
1318
  );
1339
1319
  upsert({
1340
1320
  id: stablePromotionCandidateId("action-outcome", item.action, content),
@@ -1561,7 +1541,7 @@ var CompoundingEngine = class {
1561
1541
  } else {
1562
1542
  for (const item of outcomeSummary.slice(0, 20)) {
1563
1543
  lines.push(
1564
- `- ${item.action}: applied=${item.counts.applied}, skipped=${item.counts.skipped}, failed=${item.counts.failed}, unknown=${item.counts.unknown}, weight=${item.weightedScore} _(source: ${item.provenance.join(", ")})_`
1544
+ `- ${item.action}: applied=${item.counts.applied}, skipped=${item.counts.skipped}, failed=${item.counts.failed}, weight=${item.weightedScore} _(source: ${item.provenance.join(", ")})_`
1565
1545
  );
1566
1546
  }
1567
1547
  }
@@ -1572,7 +1552,7 @@ var CompoundingEngine = class {
1572
1552
  lines.push("- (no advisory promotion candidates this week)");
1573
1553
  } else {
1574
1554
  for (const candidate of promotionCandidates) {
1575
- const outcomeSummaryText = candidate.outcome ? ` outcomes[a=${candidate.outcome.applied}, s=${candidate.outcome.skipped}, f=${candidate.outcome.failed}, u=${candidate.outcome.unknown}]` : "";
1555
+ const outcomeSummaryText = candidate.outcome ? ` outcomes[a=${candidate.outcome.applied}, s=${candidate.outcome.skipped}, f=${candidate.outcome.failed}]` : "";
1576
1556
  lines.push(
1577
1557
  `- [${candidate.sourceType}] ${candidate.subject} -> ${candidate.content} (category=${candidate.category}, score=${candidate.score}, id=${candidate.id}): ${candidate.rationale}${outcomeSummaryText} _(source: ${candidate.provenance.join(", ")})_`
1578
1558
  );
@@ -1648,7 +1628,7 @@ var CompoundingEngine = class {
1648
1628
  };
1649
1629
  this.addRubricObservation(
1650
1630
  workflowEntry,
1651
- `Outcome weight=${item.weightedScore} (applied=${item.counts.applied}, skipped=${item.counts.skipped}, failed=${item.counts.failed}, unknown=${item.counts.unknown})`,
1631
+ `Outcome weight=${item.weightedScore} (applied=${item.counts.applied}, skipped=${item.counts.skipped}, failed=${item.counts.failed})`,
1652
1632
  ...item.provenance
1653
1633
  );
1654
1634
  byWorkflow.set(item.action, workflowEntry);
@@ -1705,7 +1685,7 @@ var CompoundingEngine = class {
1705
1685
  } else {
1706
1686
  for (const item of outcomeSummary.slice(0, 20)) {
1707
1687
  lines.push(
1708
- `- ${item.action}: weight=${item.weightedScore} (applied=${item.counts.applied}, skipped=${item.counts.skipped}, failed=${item.counts.failed}, unknown=${item.counts.unknown})`
1688
+ `- ${item.action}: weight=${item.weightedScore} (applied=${item.counts.applied}, skipped=${item.counts.skipped}, failed=${item.counts.failed})`
1709
1689
  );
1710
1690
  }
1711
1691
  }
@@ -1798,52 +1778,44 @@ var CompoundingEngine = class {
1798
1778
  entry.observations = normalized.observationEntries?.map((item) => item.note) ?? [];
1799
1779
  entry.provenance = [...new Set((normalized.observationEntries ?? []).flatMap((item) => item.provenance))];
1800
1780
  }
1801
- async readNonEmptyFile(filePath) {
1781
+ async readOptionalIdentityAnchorForAudit() {
1802
1782
  try {
1803
- const raw = await readFile2(filePath, "utf-8");
1804
- return raw.trim().length > 0;
1783
+ return await this.storage.readIdentityAnchor();
1805
1784
  } catch {
1806
- return false;
1785
+ return null;
1807
1786
  }
1808
1787
  }
1809
- async readOptionalFile(filePath) {
1788
+ async readOptionalImprovementLoopsForAudit() {
1810
1789
  try {
1811
- const raw = await readFile2(filePath, "utf-8");
1812
- return raw.trim().length > 0 ? raw : null;
1790
+ return await this.storage.readIdentityImprovementLoops();
1813
1791
  } catch {
1814
1792
  return null;
1815
1793
  }
1816
1794
  }
1817
- async readContinuityIncidents(limit = 200, state) {
1818
- const normalizedLimit = Number.isFinite(limit) ? limit : 0;
1819
- const cappedLimit = Math.max(0, Math.floor(normalizedLimit));
1820
- if (cappedLimit === 0) return [];
1821
- const incidents = [];
1795
+ async readContinuityIncidentsForAudit(limit, state) {
1822
1796
  try {
1823
- const names = await readdir2(this.identityIncidentsDir);
1824
- const files = names.filter((n) => n.endsWith(".md")).sort().reverse();
1825
- for (const file of files) {
1826
- if (incidents.length >= cappedLimit) break;
1827
- const filePath = path2.join(this.identityIncidentsDir, file);
1828
- try {
1829
- const raw = await readFile2(filePath, "utf-8");
1830
- const parsed = parseContinuityIncident(raw);
1831
- if (!parsed) continue;
1832
- if (state && parsed.state !== state) continue;
1833
- incidents.push(parsed);
1834
- } catch {
1835
- }
1836
- }
1797
+ return await this.storage.readContinuityIncidents(limit, state);
1837
1798
  } catch {
1799
+ return [];
1800
+ }
1801
+ }
1802
+ async readOptionalIdentityAuditForReference(period, key) {
1803
+ try {
1804
+ return await this.storage.readIdentityAudit(period, key);
1805
+ } catch {
1806
+ return null;
1838
1807
  }
1839
- return incidents;
1840
1808
  }
1841
1809
  async readContinuityAuditReferences(weekId) {
1842
1810
  const monthId = monthIdFromIsoWeek(weekId);
1843
1811
  const weeklyPath = path2.join(this.identityAuditWeeklyDir, `${weekId}.md`);
1844
1812
  const monthlyPath = path2.join(this.identityAuditMonthlyDir, `${monthId}.md`);
1845
- const weeklyExists = await this.readNonEmptyFile(weeklyPath);
1846
- const monthlyExists = await this.readNonEmptyFile(monthlyPath);
1813
+ const [weeklyAudit, monthlyAudit] = await Promise.all([
1814
+ this.readOptionalIdentityAuditForReference("weekly", weekId),
1815
+ this.readOptionalIdentityAuditForReference("monthly", monthId)
1816
+ ]);
1817
+ const weeklyExists = (weeklyAudit ?? "").trim().length > 0;
1818
+ const monthlyExists = (monthlyAudit ?? "").trim().length > 0;
1847
1819
  return {
1848
1820
  weekId,
1849
1821
  monthId,
@@ -111,8 +111,8 @@ async function writeMaybeEncryptedFile(filePath, content, key, options = {}, mem
111
111
  }
112
112
  async function migrateMemoryDirToEncrypted(dir, key, onBeforeEncrypt) {
113
113
  const result = { encrypted: 0, skipped: 0, errors: [] };
114
- const mdFiles = await collectMdFiles(dir);
115
- for (const filePath of mdFiles) {
114
+ const files = await collectEncryptableStorageFiles(dir);
115
+ for (const filePath of files) {
116
116
  try {
117
117
  const buf = await readFile(filePath);
118
118
  if (isEncryptedFile(buf)) {
@@ -126,7 +126,7 @@ async function migrateMemoryDirToEncrypted(dir, key, onBeforeEncrypt) {
126
126
  }
127
127
  }
128
128
  const content = buf.toString("utf8");
129
- const aad = filePathAad(filePath, dir);
129
+ const aad = filePathAad(filePath, storageAadRootForFile(filePath, dir));
130
130
  const encrypted = encryptFileBody(content, key, aad);
131
131
  const tempPath = `${filePath}.enc-tmp-${process.pid}-${Date.now()}`;
132
132
  try {
@@ -150,7 +150,43 @@ async function migrateMemoryDirToEncrypted(dir, key, onBeforeEncrypt) {
150
150
  }
151
151
  return result;
152
152
  }
153
- async function collectMdFiles(dir, rootDir = dir) {
153
+ async function decryptMemoryDirToPlaintext(dir, key) {
154
+ const result = { decrypted: 0, skipped: 0, errors: [] };
155
+ const files = await collectStorageManagedFiles(dir, isDecryptableStoragePath);
156
+ for (const filePath of files) {
157
+ try {
158
+ const buf = await readFile(filePath);
159
+ if (!isEncryptedFile(buf)) {
160
+ result.skipped++;
161
+ continue;
162
+ }
163
+ const aad = filePathAad(filePath, storageAadRootForFile(filePath, dir));
164
+ const plaintext = decryptFileBody(buf, key, aad);
165
+ const tempPath = `${filePath}.dec-tmp-${process.pid}-${Date.now()}`;
166
+ try {
167
+ await writeFile(tempPath, plaintext, { mode: 384 });
168
+ await rename(tempPath, filePath);
169
+ result.decrypted++;
170
+ } catch (writeErr) {
171
+ try {
172
+ await unlink(tempPath);
173
+ } catch {
174
+ }
175
+ throw writeErr;
176
+ }
177
+ } catch (err) {
178
+ result.errors.push({
179
+ filePath,
180
+ error: err instanceof Error ? err.message : String(err)
181
+ });
182
+ }
183
+ }
184
+ return result;
185
+ }
186
+ async function collectEncryptableStorageFiles(dir, rootDir = dir) {
187
+ return collectStorageManagedFiles(dir, isEncryptableStoragePath, rootDir);
188
+ }
189
+ async function collectStorageManagedFiles(dir, includeFile, rootDir = dir) {
154
190
  const results = [];
155
191
  let names;
156
192
  try {
@@ -172,9 +208,9 @@ async function collectMdFiles(dir, rootDir = dir) {
172
208
  continue;
173
209
  }
174
210
  if (isDir) {
175
- const sub = await collectMdFiles(full, rootDir);
211
+ const sub = await collectStorageManagedFiles(full, includeFile, rootDir);
176
212
  results.push(...sub);
177
- } else if (isFile && name.endsWith(".md") && isEncryptableStoragePath(full, rootDir)) {
213
+ } else if (isFile && includeFile(full, rootDir)) {
178
214
  results.push(full);
179
215
  }
180
216
  }
@@ -183,18 +219,75 @@ async function collectMdFiles(dir, rootDir = dir) {
183
219
  function isEncryptableStoragePath(filePath, rootDir) {
184
220
  const rel = path.relative(rootDir, filePath);
185
221
  if (rel === "" || rel.startsWith("..") || path.isAbsolute(rel)) return false;
186
- const normalized = rel.split(path.sep).join("/");
222
+ const normalized = normalizeStorageRelativePath(rel);
187
223
  if (normalized === "profile.md") return true;
224
+ if (isEncryptableStateSidecar(normalized)) return true;
225
+ if (isEncryptableSummarySidecar(normalized)) return true;
188
226
  const firstSegment = normalized.split("/", 1)[0];
189
- return ENCRYPTABLE_STORAGE_ROOTS.has(firstSegment);
227
+ return ENCRYPTABLE_MARKDOWN_STORAGE_ROOTS.has(firstSegment) && normalized.endsWith(".md");
190
228
  }
191
- var ENCRYPTABLE_STORAGE_ROOTS = /* @__PURE__ */ new Set([
229
+ function isDecryptableStoragePath(filePath, rootDir) {
230
+ if (isEncryptableStoragePath(filePath, rootDir)) return true;
231
+ const rel = path.relative(rootDir, filePath);
232
+ if (rel === "" || rel.startsWith("..") || path.isAbsolute(rel)) return false;
233
+ const normalized = normalizeStorageRelativePath(rel);
234
+ const firstSegment = normalized.split("/", 1)[0];
235
+ return DECRYPTABLE_SIDECAR_ROOTS.has(firstSegment);
236
+ }
237
+ function normalizeStorageRelativePath(rel) {
238
+ const normalized = rel.split(path.sep).join("/");
239
+ const parts = normalized.split("/");
240
+ if (parts[0] === "namespaces" && parts.length >= 3) {
241
+ return parts.slice(2).join("/");
242
+ }
243
+ return normalized;
244
+ }
245
+ function storageAadRootForFile(filePath, rootDir) {
246
+ const rel = path.relative(rootDir, filePath);
247
+ if (rel === "" || rel.startsWith("..") || path.isAbsolute(rel)) return rootDir;
248
+ const parts = rel.split(path.sep);
249
+ if (parts[0] === "namespaces" && parts.length >= 3 && parts[1]) {
250
+ return path.join(rootDir, "namespaces", parts[1]);
251
+ }
252
+ return rootDir;
253
+ }
254
+ var ENCRYPTABLE_MARKDOWN_STORAGE_ROOTS = /* @__PURE__ */ new Set([
192
255
  "facts",
193
256
  "corrections",
194
257
  "procedures",
195
258
  "reasoning-traces",
196
259
  "artifacts",
197
- "archive"
260
+ "archive",
261
+ "entities",
262
+ "identity"
263
+ ]);
264
+ var ENCRYPTABLE_STATE_SIDECARS = /* @__PURE__ */ new Set([
265
+ "state/behavior-signals.jsonl",
266
+ "state/buffer-surprise-ledger.jsonl",
267
+ "state/buffer.json",
268
+ "state/compression-guideline-draft-state.json",
269
+ "state/compression-guideline-state.json",
270
+ "state/compression-guidelines.draft.md",
271
+ "state/compression-guidelines.md",
272
+ "state/entity-synthesis-queue.json",
273
+ "state/fact-hashes.txt",
274
+ "state/memory-actions.jsonl",
275
+ "state/memory-lifecycle-ledger.jsonl",
276
+ "state/meta.json",
277
+ "state/reextract-jobs.jsonl",
278
+ "state/topics.json"
279
+ ]);
280
+ function isEncryptableStateSidecar(normalized) {
281
+ return ENCRYPTABLE_STATE_SIDECARS.has(normalized);
282
+ }
283
+ function isEncryptableSummarySidecar(normalized) {
284
+ return normalized.startsWith("summaries/") && normalized.endsWith(".json");
285
+ }
286
+ var DECRYPTABLE_SIDECAR_ROOTS = /* @__PURE__ */ new Set([
287
+ "state",
288
+ "indexes",
289
+ "index",
290
+ "provenance"
198
291
  ]);
199
292
 
200
293
  export {
@@ -210,5 +303,6 @@ export {
210
303
  filePathAad,
211
304
  readMaybeEncryptedFile,
212
305
  writeMaybeEncryptedFile,
213
- migrateMemoryDirToEncrypted
306
+ migrateMemoryDirToEncrypted,
307
+ decryptMemoryDirToPlaintext
214
308
  };
@@ -5,7 +5,7 @@ import {
5
5
  import {
6
6
  StorageManager,
7
7
  isSemanticConsolidationLlmOperator
8
- } from "./chunk-TNH24SF6.js";
8
+ } from "./chunk-7UZNLMW5.js";
9
9
  import {
10
10
  log
11
11
  } from "./chunk-UFU5GGGA.js";
@@ -1,13 +1,15 @@
1
1
  import {
2
2
  CompoundingEngine,
3
3
  defaultTierMigrationCycleBudget
4
- } from "./chunk-L4PRBB2A.js";
5
- import "./chunk-XMSDA5WA.js";
6
- import "./chunk-TNH24SF6.js";
4
+ } from "./chunk-OAE7AQ6R.js";
5
+ import "./chunk-EXDYWXMB.js";
6
+ import "./chunk-7UZNLMW5.js";
7
7
  import "./chunk-6OJAU466.js";
8
- import "./chunk-3I7RHWYT.js";
8
+ import "./chunk-RKR6PTPA.js";
9
9
  import "./chunk-UFU5GGGA.js";
10
10
  import "./chunk-YGGGUTG3.js";
11
+ import "./chunk-OEI7GLV2.js";
12
+ import "./chunk-I6B2W2IY.js";
11
13
  import "./chunk-MLKGABMK.js";
12
14
  export {
13
15
  CompoundingEngine,