musememory 2.2.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
@@ -4594,6 +4594,18 @@ function formatPromptContext(store, memoryDir, query = "", options = {}) {
4594
4594
  }
4595
4595
  parts.push("");
4596
4596
  }
4597
+ const currentData = memoryDir ? parseCurrentFile(memoryDir) : null;
4598
+ if (currentData?.workstreams && currentData.workstreams.length > 0) {
4599
+ const activeWs = currentData.workstreams.filter((w) => w.status === "IN-PROGRESS" || w.status === "BLOCKED");
4600
+ if (activeWs.length > 0) {
4601
+ parts.push("### Active Concurrent Agent Workstreams (CURRENT.md)");
4602
+ for (const w of activeWs) {
4603
+ const scope = w.targetScope ? ` | Target: \`${w.targetScope}\`` : "";
4604
+ parts.push(`- Agent \`${w.agent}\` [${w.status}]: ${w.task}${scope} (Active: ${w.lastActive})`);
4605
+ }
4606
+ parts.push("");
4607
+ }
4608
+ }
4597
4609
  const handoff = memoryDir ? getSessionHandoff(memoryDir) : null;
4598
4610
  if (handoff && (handoff.status === "IN-PROGRESS" || handoff.task || handoff.lastQuery)) {
4599
4611
  parts.push("### Active In-Flight Context & Session Handoff (CURRENT.md)");
@@ -4891,38 +4903,83 @@ function currentFilePath(memoryDir) {
4891
4903
  function parseCurrentFile(memoryDir) {
4892
4904
  const p = currentFilePath(memoryDir);
4893
4905
  if (!existsSync6(p))
4894
- return { constraints: [], handoff: null };
4906
+ return { constraints: [], handoff: null, workstreams: [] };
4895
4907
  const raw = readFileSync5(p, "utf8");
4896
4908
  const lines = raw.split(`
4897
4909
  `);
4898
4910
  const constraints = [];
4911
+ const workstreams = [];
4899
4912
  let inConstraintsSection = false;
4900
4913
  let inHandoffSection = false;
4914
+ let inWorkstreamsSection = false;
4901
4915
  const handoffLines = [];
4902
4916
  for (const line of lines) {
4903
4917
  const trimmed = line.trim();
4904
- if (trimmed.startsWith("## Active Working Invariants") || trimmed.startsWith("## Active Constraints")) {
4918
+ if (trimmed.startsWith("## Active Working Invariants") || trimmed.startsWith("## Active Working Constraints") || trimmed.startsWith("## Active Constraints") || trimmed.startsWith("## \uD83D\uDD12 Active Working Invariants")) {
4905
4919
  inConstraintsSection = true;
4906
4920
  inHandoffSection = false;
4921
+ inWorkstreamsSection = false;
4922
+ continue;
4923
+ }
4924
+ if (trimmed.startsWith("## \uD83E\uDD16 Active Concurrent Agent Workstreams") || trimmed.startsWith("## Concurrent Agent Workstreams") || trimmed.startsWith("## Active Workstreams")) {
4925
+ inConstraintsSection = false;
4926
+ inHandoffSection = false;
4927
+ inWorkstreamsSection = true;
4907
4928
  continue;
4908
4929
  }
4909
- if (trimmed.startsWith("## Active Work In Progress") || trimmed.startsWith("## In-Flight Session State") || trimmed.startsWith("## Session Handoff")) {
4930
+ if (trimmed.startsWith("## Active Work In Progress") || trimmed.startsWith("## In-Flight Session State") || trimmed.startsWith("## Session Handoff") || trimmed.startsWith("## ⚡ Active Work In Progress")) {
4910
4931
  inConstraintsSection = false;
4911
4932
  inHandoffSection = true;
4933
+ inWorkstreamsSection = false;
4912
4934
  continue;
4913
4935
  }
4914
- if (trimmed.startsWith("# ")) {
4936
+ if (trimmed.startsWith("# ") || trimmed.startsWith("> ") || trimmed.startsWith("---")) {
4915
4937
  continue;
4916
4938
  }
4917
- if (inHandoffSection) {
4918
- handoffLines.push(line);
4939
+ if (inWorkstreamsSection) {
4940
+ if (trimmed.startsWith("##")) {
4941
+ inWorkstreamsSection = false;
4942
+ } else if (trimmed.startsWith("|")) {
4943
+ const cells = trimmed.split("|").map((c) => c.trim()).filter((_, idx, arr) => idx > 0 && idx < arr.length - 1);
4944
+ if (cells.length >= 3 && !cells[0].includes("---") && !cells[1].toLowerCase().includes("status")) {
4945
+ const agent = cells[0].replace(/[`*]/g, "").trim();
4946
+ const statusRaw = cells[1].replace(/[\[\]`*]/g, "").trim().toUpperCase();
4947
+ const status = statusRaw === "COMPLETED" || statusRaw === "BLOCKED" || statusRaw === "WAITING_REVIEW" ? statusRaw : "IN-PROGRESS";
4948
+ const task = cells[2].trim();
4949
+ const scope = cells[3] ? cells[3].replace(/[`*()]/g, "").trim() : undefined;
4950
+ const lastActive = cells[4] ? cells[4].trim() : new Date().toISOString();
4951
+ if (agent && task) {
4952
+ workstreams.push({
4953
+ agent,
4954
+ status,
4955
+ task,
4956
+ targetScope: scope && scope !== "all" ? scope : undefined,
4957
+ lastActive
4958
+ });
4959
+ }
4960
+ }
4961
+ }
4962
+ } else if (inHandoffSection) {
4963
+ if (trimmed.startsWith("##")) {
4964
+ inHandoffSection = false;
4965
+ } else {
4966
+ handoffLines.push(line);
4967
+ }
4919
4968
  } else if (inConstraintsSection) {
4920
- if (trimmed.length > 0 && !trimmed.startsWith("#") && !trimmed.startsWith("*(") && !trimmed.startsWith("(*")) {
4921
- constraints.push(trimmed.replace(/^-\s+/, ""));
4969
+ if (trimmed.startsWith("##")) {
4970
+ inConstraintsSection = false;
4971
+ } else if (trimmed.length > 0 && !trimmed.startsWith("#") && !trimmed.startsWith("*(") && !trimmed.startsWith("(*")) {
4972
+ const cleaned = trimmed.replace(/^-\s+/, "");
4973
+ if (isValidConstraintLine(cleaned)) {
4974
+ constraints.push(cleaned);
4975
+ }
4922
4976
  }
4923
- } else if (!inConstraintsSection && !inHandoffSection) {
4924
- if (trimmed.length > 0 && !trimmed.startsWith("#") && !trimmed.startsWith("*(") && !trimmed.startsWith("(*")) {
4925
- constraints.push(trimmed.replace(/^-\s+/, ""));
4977
+ } else if (!inConstraintsSection && !inHandoffSection && !inWorkstreamsSection) {
4978
+ const hasSections = lines.some((l) => l.trim().startsWith("## "));
4979
+ if (!hasSections && trimmed.length > 0 && !trimmed.startsWith("#") && !trimmed.startsWith("*(") && !trimmed.startsWith("(*") && !trimmed.startsWith("|")) {
4980
+ if (isValidConstraintLine(trimmed)) {
4981
+ constraints.push(trimmed.replace(/^-\s+/, ""));
4982
+ }
4926
4983
  }
4927
4984
  }
4928
4985
  }
@@ -4978,14 +5035,22 @@ function parseCurrentFile(memoryDir) {
4978
5035
  };
4979
5036
  }
4980
5037
  }
4981
- return { constraints, handoff };
5038
+ return { constraints, handoff, workstreams };
4982
5039
  }
4983
5040
  function writeCurrentFile(memoryDir, data) {
4984
5041
  const p = currentFilePath(memoryDir);
4985
5042
  mkdirSync5(memoryDir, { recursive: true });
4986
- const parts = [`# Active Project Constraints & In-Flight Context
4987
- `];
4988
- parts.push("## Active Working Invariants & Hard Constraints");
5043
+ const parts = [
5044
+ `# Active Project Constraints & In-Flight Context
5045
+ `,
5046
+ "> **Operational Guidelines**:",
5047
+ "> - **For Humans**: Single-pane executive summary of active hard constraints and in-flight agent tasks. Zero verbose logs or transient filler.",
5048
+ `> - **For AI Agents**: Mandatory grounding rules (never violate active constraints) and concurrent workstream awareness (check what other agents are touching before editing files).
5049
+ `,
5050
+ `---
5051
+ `
5052
+ ];
5053
+ parts.push("## \uD83D\uDD12 Active Working Invariants & Hard Constraints");
4989
5054
  if (data.constraints.length === 0) {
4990
5055
  parts.push(`*(No active hard constraints)*
4991
5056
  `);
@@ -4995,8 +5060,19 @@ function writeCurrentFile(memoryDir, data) {
4995
5060
  }
4996
5061
  parts.push("");
4997
5062
  }
5063
+ if (data.workstreams && data.workstreams.length > 0) {
5064
+ parts.push("## \uD83E\uDD16 Active Concurrent Agent Workstreams");
5065
+ parts.push("| Agent / Session ID | Status | Active Task | Target Scope / Files | Last Active |");
5066
+ parts.push("| :--- | :--- | :--- | :--- | :--- |");
5067
+ for (const ws of data.workstreams) {
5068
+ const statusTag = `[${ws.status || "IN-PROGRESS"}]`;
5069
+ const scope = ws.targetScope ? `\`${ws.targetScope}\`` : "*(all)*";
5070
+ parts.push(`| \`${ws.agent}\` | ${statusTag} | ${ws.task} | ${scope} | ${ws.lastActive} |`);
5071
+ }
5072
+ parts.push("");
5073
+ }
4998
5074
  if (data.handoff) {
4999
- parts.push("## Active Work In Progress (Real-Time Session Handoff)");
5075
+ parts.push("## ⚡ Active Work In Progress (Real-Time Session Handoff)");
5000
5076
  parts.push(`- **Status**: [${data.handoff.status}]`);
5001
5077
  if (data.handoff.agent)
5002
5078
  parts.push(`- **Active Agent**: ${data.handoff.agent}`);
@@ -5042,12 +5118,61 @@ function updateSessionHandoff(memoryDir, update) {
5042
5118
  progress: progressMerged,
5043
5119
  discoveries: discoveriesMerged
5044
5120
  };
5121
+ const workstreams = current.workstreams ? [...current.workstreams] : [];
5122
+ if (updated.agent && (updated.task || updated.lastQuery)) {
5123
+ const wsIdx = workstreams.findIndex((w) => updated.sessionId && w.sessionId === updated.sessionId || w.agent.toLowerCase() === updated.agent.toLowerCase());
5124
+ const wsEntry = {
5125
+ agent: updated.agent,
5126
+ sessionId: updated.sessionId,
5127
+ task: updated.task || updated.lastQuery || "Active task",
5128
+ status: updated.status || "IN-PROGRESS",
5129
+ lastActive: now,
5130
+ lastInstruction: updated.lastQuery
5131
+ };
5132
+ if (wsIdx >= 0) {
5133
+ workstreams[wsIdx] = { ...workstreams[wsIdx], ...wsEntry };
5134
+ } else {
5135
+ workstreams.push(wsEntry);
5136
+ }
5137
+ }
5045
5138
  writeCurrentFile(memoryDir, {
5046
5139
  constraints: current.constraints,
5047
- handoff: updated
5140
+ handoff: updated,
5141
+ workstreams
5048
5142
  });
5049
5143
  return updated;
5050
5144
  }
5145
+ function registerAgentWorkstream(memoryDir, workstream) {
5146
+ const current = parseCurrentFile(memoryDir);
5147
+ const now = new Date().toISOString();
5148
+ const workstreams = current.workstreams ? [...current.workstreams] : [];
5149
+ const entry = {
5150
+ agent: workstream.agent,
5151
+ sessionId: workstream.sessionId,
5152
+ task: workstream.task,
5153
+ targetScope: workstream.targetScope,
5154
+ status: workstream.status || "IN-PROGRESS",
5155
+ lastActive: workstream.lastActive || now,
5156
+ lastInstruction: workstream.lastInstruction
5157
+ };
5158
+ const idx = workstreams.findIndex((w) => entry.sessionId && w.sessionId === entry.sessionId || w.agent.toLowerCase() === entry.agent.toLowerCase());
5159
+ if (idx >= 0) {
5160
+ workstreams[idx] = { ...workstreams[idx], ...entry, lastActive: now };
5161
+ } else {
5162
+ workstreams.push(entry);
5163
+ }
5164
+ const nowMs = Date.now();
5165
+ const pruned = workstreams.filter((w) => {
5166
+ if (w.status === "COMPLETED") {
5167
+ const activeMs = Date.parse(w.lastActive) || 0;
5168
+ return nowMs - activeMs < 48 * 3600 * 1000;
5169
+ }
5170
+ return true;
5171
+ });
5172
+ current.workstreams = pruned;
5173
+ writeCurrentFile(memoryDir, current);
5174
+ return pruned;
5175
+ }
5051
5176
  function getSessionHandoff(memoryDir) {
5052
5177
  return parseCurrentFile(memoryDir).handoff;
5053
5178
  }
@@ -5062,6 +5187,15 @@ function markSessionCompleted(memoryDir, summary) {
5062
5187
  if (summary) {
5063
5188
  current.handoff.task = `[COMPLETED] ${summary}`;
5064
5189
  }
5190
+ if (current.workstreams && current.handoff.agent) {
5191
+ const ws = current.workstreams.find((w) => w.agent.toLowerCase() === current.handoff.agent.toLowerCase());
5192
+ if (ws) {
5193
+ ws.status = "COMPLETED";
5194
+ ws.lastActive = now;
5195
+ if (summary)
5196
+ ws.task = `[COMPLETED] ${summary}`;
5197
+ }
5198
+ }
5065
5199
  writeCurrentFile(memoryDir, current);
5066
5200
  }
5067
5201
  function getCurrent2(memoryDir) {
@@ -5079,6 +5213,27 @@ function setCurrent(memoryDir, text, project = "default") {
5079
5213
  }
5080
5214
  return current.constraints;
5081
5215
  }
5216
+ function isValidConstraintLine(text) {
5217
+ const trimmed = text.trim();
5218
+ if (trimmed.length < 5 || trimmed.length > 300)
5219
+ return false;
5220
+ if (trimmed.includes(`
5221
+ `))
5222
+ return false;
5223
+ if (/expect\(/i.test(trimmed) || /Ran\s+\d+\s+tests/i.test(trimmed))
5224
+ return false;
5225
+ if (trimmed.startsWith("Showing lines") || trimmed.startsWith("Created At:") || trimmed.startsWith("File Path:"))
5226
+ return false;
5227
+ if (trimmed.startsWith("MODEL PLANNER_RESPONSE") || trimmed.startsWith("</SYSTEM_MESSAGE>"))
5228
+ return false;
5229
+ if (trimmed.includes("<truncated") || trimmed.includes("User: That worked"))
5230
+ return false;
5231
+ if (trimmed.startsWith("total ") || /^\d+:\s+/.test(trimmed) || /^\d+\s*\|\s*/.test(trimmed))
5232
+ return false;
5233
+ if (trimmed.startsWith("The following code has been modified") || trimmed.startsWith("The above content does NOT"))
5234
+ return false;
5235
+ return true;
5236
+ }
5082
5237
  function syncConstraints(memoryDir, store, pruneContents = []) {
5083
5238
  const entries = list(store);
5084
5239
  const activeConstraintMemories = entries.filter((e) => e.type === "constraint" && (e.status === "active" || e.status === "confirmed"));
@@ -5090,24 +5245,42 @@ Stale:`)[0].split(`
5090
5245
  Superseded:`)[0].trim()).filter(Boolean);
5091
5246
  const current = parseCurrentFile(memoryDir);
5092
5247
  const keptManual = [];
5248
+ const seenNorms = new Set;
5093
5249
  for (const c of current.constraints) {
5250
+ if (!isValidConstraintLine(c))
5251
+ continue;
5094
5252
  if (pruneContents.some((p) => c.includes(p)))
5095
5253
  continue;
5096
5254
  if (inactiveConstraintContents.some((ic) => ic.length > 0 && (c.includes(ic) || ic.includes(c))))
5097
5255
  continue;
5256
+ const norm = c.toLowerCase().replace(/[^a-z0-9]/g, "");
5257
+ if (seenNorms.has(norm))
5258
+ continue;
5259
+ seenNorms.add(norm);
5098
5260
  keptManual.push(c);
5099
5261
  }
5100
5262
  const resultConstraints = [...keptManual];
5101
5263
  for (const m of activeConstraintMemories) {
5102
5264
  const rawContent = m.content.trim();
5103
- if (!resultConstraints.some((c) => c.includes(rawContent))) {
5104
- const stamp = `[${m.created_at || new Date().toISOString()}] (${m.project}) ${rawContent}`;
5265
+ if (rawContent.length < 5)
5266
+ continue;
5267
+ let constraintText = rawContent;
5268
+ if (rawContent.includes(`
5269
+ `) || rawContent.length > 300) {
5270
+ const firstLine = rawContent.split(`
5271
+ `)[0].trim().replace(/^[-*#0-9.:\s|]+/, "");
5272
+ constraintText = firstLine.length >= 10 && firstLine.length <= 300 ? firstLine : m.title.replace(/^[-*#0-9.:\s|]+/, "").slice(0, 200).trim();
5273
+ }
5274
+ const norm = constraintText.toLowerCase().replace(/[^a-z0-9]/g, "");
5275
+ if (constraintText.length >= 5 && isValidConstraintLine(constraintText) && !resultConstraints.some((c) => c.toLowerCase().replace(/[^a-z0-9]/g, "").includes(norm))) {
5276
+ const stamp = `[${m.created_at || new Date().toISOString()}] (${m.project}) ${constraintText}`;
5105
5277
  resultConstraints.push(stamp);
5106
5278
  }
5107
5279
  }
5108
5280
  writeCurrentFile(memoryDir, {
5109
5281
  constraints: resultConstraints,
5110
- handoff: current.handoff
5282
+ handoff: current.handoff,
5283
+ workstreams: current.workstreams
5111
5284
  });
5112
5285
  return resultConstraints;
5113
5286
  }
@@ -5303,6 +5476,9 @@ class WorkspaceGovernor {
5303
5476
  static checkpointSession(memoryDir, update) {
5304
5477
  return updateSessionHandoff(memoryDir, update);
5305
5478
  }
5479
+ static registerWorkstream(memoryDir, workstream) {
5480
+ return registerAgentWorkstream(memoryDir, workstream);
5481
+ }
5306
5482
  static completeSession(memoryDir, summary) {
5307
5483
  markSessionCompleted(memoryDir, summary);
5308
5484
  }
@@ -22028,6 +22204,253 @@ var init_mesh = __esm(() => {
22028
22204
  init_contracts();
22029
22205
  });
22030
22206
 
22207
+ // src/optimize.ts
22208
+ var exports_optimize = {};
22209
+ __export(exports_optimize, {
22210
+ isJunkFragment: () => isJunkFragment,
22211
+ isTestNoise: () => isTestNoise,
22212
+ maybeAutoOptimize: () => maybeAutoOptimize,
22213
+ optimizeStore: () => optimizeStore,
22214
+ readOptimizationMetadata: () => readOptimizationMetadata,
22215
+ shouldAutoOptimize: () => shouldAutoOptimize,
22216
+ touchActivity: () => touchActivity,
22217
+ writeOptimizationMetadata: () => writeOptimizationMetadata
22218
+ });
22219
+ import { existsSync as existsSync39, readFileSync as readFileSync33, writeFileSync as writeFileSync19, statSync as statSync14 } from "node:fs";
22220
+ import { join as join36 } from "node:path";
22221
+ function getMetaPath(memoryDir) {
22222
+ return join36(memoryDir, META_FILE_NAME);
22223
+ }
22224
+ function readOptimizationMetadata(memoryDir) {
22225
+ const metaPath = getMetaPath(memoryDir);
22226
+ if (!existsSync39(metaPath)) {
22227
+ return {
22228
+ last_optimized_at: new Date(0).toISOString(),
22229
+ last_activity_at: new Date().toISOString(),
22230
+ total_optimizations: 0
22231
+ };
22232
+ }
22233
+ try {
22234
+ const raw = readFileSync33(metaPath, "utf8");
22235
+ return JSON.parse(raw);
22236
+ } catch {
22237
+ return {
22238
+ last_optimized_at: new Date(0).toISOString(),
22239
+ last_activity_at: new Date().toISOString(),
22240
+ total_optimizations: 0
22241
+ };
22242
+ }
22243
+ }
22244
+ function writeOptimizationMetadata(memoryDir, meta) {
22245
+ const metaPath = getMetaPath(memoryDir);
22246
+ try {
22247
+ writeFileSync19(metaPath, JSON.stringify(meta, null, 2), "utf8");
22248
+ } catch {}
22249
+ }
22250
+ function touchActivity(memoryDir) {
22251
+ try {
22252
+ const meta = readOptimizationMetadata(memoryDir);
22253
+ meta.last_activity_at = new Date().toISOString();
22254
+ writeOptimizationMetadata(memoryDir, meta);
22255
+ } catch {}
22256
+ }
22257
+ function shouldAutoOptimize(memoryDir, options = {}) {
22258
+ const meta = readOptimizationMetadata(memoryDir);
22259
+ const now = Date.now();
22260
+ const daysThreshold = options.daysIntervalThreshold ?? 7;
22261
+ const daysMs = daysThreshold * 24 * 60 * 60 * 1000;
22262
+ const hoursThreshold = options.inactivityHoursThreshold ?? 48;
22263
+ const hoursMs = hoursThreshold * 60 * 60 * 1000;
22264
+ const lastOpt = Date.parse(meta.last_optimized_at) || 0;
22265
+ const lastAct = Date.parse(meta.last_activity_at) || now;
22266
+ if (now - lastOpt >= daysMs) {
22267
+ return {
22268
+ shouldRun: true,
22269
+ reason: `Scheduled ${daysThreshold}-day cadence reached (${Math.round((now - lastOpt) / (24 * 3600 * 1000))}d since last run)`
22270
+ };
22271
+ }
22272
+ if (now - lastAct >= hoursMs && now - lastOpt >= hoursMs) {
22273
+ return {
22274
+ shouldRun: true,
22275
+ reason: `Inactivity threshold reached (${Math.round((now - lastAct) / (3600 * 1000))}h idle)`
22276
+ };
22277
+ }
22278
+ return { shouldRun: false };
22279
+ }
22280
+ function isTestNoise(entry) {
22281
+ if (entry.status === "confirmed" && entry.verification?.level === "user-confirmed") {
22282
+ return false;
22283
+ }
22284
+ const text = `${entry.title} ${entry.content}`;
22285
+ return /error:\s*expect\(/i.test(text) || /expect\([^)]+\)\.toBe/i.test(text) || /expect\([^)]+\)\.toEqual/i.test(text) || /expect\([^)]+\)\.toBeGreaterThan/i.test(text) || /expect\(received\)/i.test(text) || /at\s+<anonymous>\s+\([^)]+\.test\.(ts|js)/i.test(text) || /Ran\s+\d+\s+tests\s+across/i.test(text) || /\.test\.(ts|js):\d+:\d+/i.test(text) || /TypeError:\s*store\./i.test(text) || /AssertionError:/i.test(text) || /✗\s+Universal Agent Transcript/i.test(text) || /\b\d+\s+pass\s+\d+\s+fail\b/i.test(text) || /✓\s+[^\n]+\[\d+\.?\d*ms\]/i.test(text);
22286
+ }
22287
+ function isJunkFragment(entry) {
22288
+ const title = (entry.title || "").trim();
22289
+ const content = (entry.content || "").trim();
22290
+ if (content.length <= 5 && (/^['"]?[0-9]+['"]?$/.test(title) || title === "+" || title === "-" || title === "|" || title === ">-")) {
22291
+ return true;
22292
+ }
22293
+ if (content.includes("The following code has been modified") || content.includes("The above content does NOT show the entire file contents") || content.includes("MODEL PLANNER_RESPONSE") || content.includes("</SYSTEM_MESSAGE>") || content.split(`
22294
+ `).length > 50 && content.includes("Completed At:") || content.includes("<truncated") || content.includes("expect(") && /expect\([^)]+\)\.toBe/i.test(content)) {
22295
+ return true;
22296
+ }
22297
+ if (entry.status === "confirmed")
22298
+ return false;
22299
+ if (title === "1" || title === "+" || title === "-" || title === "|" || title === ">-") {
22300
+ return true;
22301
+ }
22302
+ if (/^['"]?[0-9]+['"]?$/.test(title)) {
22303
+ return true;
22304
+ }
22305
+ if (content.length < 15) {
22306
+ return true;
22307
+ }
22308
+ if (content.includes("create mode 100644") || content.includes("File Path: `file://") || content.includes("Showing lines ")) {
22309
+ return true;
22310
+ }
22311
+ return false;
22312
+ }
22313
+ function optimizeStore(store, options = {}) {
22314
+ const startTime = Date.now();
22315
+ const memoryDir = options.memoryDir || store.memoryDir || ".memory";
22316
+ if (!options.force) {
22317
+ const autoCheck = shouldAutoOptimize(memoryDir, {
22318
+ inactivityHoursThreshold: options.inactivityHoursThreshold,
22319
+ daysIntervalThreshold: options.daysIntervalThreshold
22320
+ });
22321
+ if (!autoCheck.shouldRun) {
22322
+ return {
22323
+ timestamp: new Date().toISOString(),
22324
+ totalBefore: 0,
22325
+ totalAfter: 0,
22326
+ prunedNoise: 0,
22327
+ prunedJunk: 0,
22328
+ prunedDuplicates: 0,
22329
+ totalPruned: 0,
22330
+ spaceReclaimedBytes: 0,
22331
+ vacuumExecuted: false,
22332
+ skippedReason: "Optimization thresholds not met (7-day cadence or 48-hour inactivity)",
22333
+ durationMs: Date.now() - startTime
22334
+ };
22335
+ }
22336
+ }
22337
+ const allEntries = list(store, options.project ? { project: options.project } : undefined);
22338
+ const totalBefore = allEntries.length;
22339
+ const getDbSize = () => {
22340
+ try {
22341
+ const dbPath = join36(memoryDir, "memory.db");
22342
+ if (existsSync39(dbPath)) {
22343
+ return statSync14(dbPath).size;
22344
+ }
22345
+ } catch {}
22346
+ return 0;
22347
+ };
22348
+ const dbSizeBefore = getDbSize();
22349
+ const toDeleteNoise = [];
22350
+ const toDeleteJunk = [];
22351
+ const toDeleteDuplicates = [];
22352
+ const seenHashes = new Map;
22353
+ for (const entry of allEntries) {
22354
+ if (entry.status !== "confirmed" && isTestNoise(entry)) {
22355
+ toDeleteNoise.push(entry.id);
22356
+ continue;
22357
+ }
22358
+ if (isJunkFragment(entry)) {
22359
+ toDeleteJunk.push(entry.id);
22360
+ continue;
22361
+ }
22362
+ if (entry.status === "candidate") {
22363
+ const normKey = `${normalizeText(entry.title)}|${normalizeText(entry.content.slice(0, 120))}`;
22364
+ if (seenHashes.has(normKey)) {
22365
+ toDeleteDuplicates.push(entry.id);
22366
+ } else {
22367
+ seenHashes.set(normKey, entry.id);
22368
+ }
22369
+ }
22370
+ }
22371
+ const totalPruned = toDeleteNoise.length + toDeleteJunk.length + toDeleteDuplicates.length;
22372
+ if (!options.dryRun) {
22373
+ if (store.db) {
22374
+ try {
22375
+ store.db.exec("BEGIN TRANSACTION;");
22376
+ } catch {}
22377
+ }
22378
+ for (const id of toDeleteNoise) {
22379
+ deleteEntry(store, id, "Automated optimize: pruned test assertion noise");
22380
+ }
22381
+ for (const id of toDeleteJunk) {
22382
+ deleteEntry(store, id, "Automated optimize: pruned junk fragment");
22383
+ }
22384
+ for (const id of toDeleteDuplicates) {
22385
+ deleteEntry(store, id, "Automated optimize: pruned duplicate candidate");
22386
+ }
22387
+ if (store.db) {
22388
+ try {
22389
+ store.db.exec("COMMIT;");
22390
+ } catch {}
22391
+ }
22392
+ if (store.db) {
22393
+ try {
22394
+ store.db.exec("VACUUM;");
22395
+ store.db.exec("PRAGMA optimize;");
22396
+ } catch {}
22397
+ }
22398
+ try {
22399
+ syncConstraints(memoryDir, store);
22400
+ } catch {}
22401
+ }
22402
+ const dbSizeAfter = getDbSize();
22403
+ const spaceReclaimedBytes = Math.max(0, dbSizeBefore - dbSizeAfter);
22404
+ const remainingEntries = list(store, options.project ? { project: options.project } : undefined);
22405
+ const totalAfter = options.dryRun ? totalBefore - totalPruned : remainingEntries.length;
22406
+ const report = {
22407
+ timestamp: new Date().toISOString(),
22408
+ totalBefore,
22409
+ totalAfter,
22410
+ prunedNoise: toDeleteNoise.length,
22411
+ prunedJunk: toDeleteJunk.length,
22412
+ prunedDuplicates: toDeleteDuplicates.length,
22413
+ totalPruned,
22414
+ spaceReclaimedBytes,
22415
+ vacuumExecuted: !options.dryRun && !!store.db,
22416
+ durationMs: Date.now() - startTime
22417
+ };
22418
+ if (!options.dryRun) {
22419
+ recordAuditEvent(memoryDir, {
22420
+ operation: "optimize",
22421
+ entry_id: "store",
22422
+ project: options.project || "all",
22423
+ actor: "system:optimizer",
22424
+ reason: `Optimized store: pruned ${totalPruned} items, reclaimed ${spaceReclaimedBytes} bytes`
22425
+ });
22426
+ const meta = readOptimizationMetadata(memoryDir);
22427
+ meta.last_optimized_at = report.timestamp;
22428
+ meta.last_activity_at = report.timestamp;
22429
+ meta.total_optimizations = (meta.total_optimizations || 0) + 1;
22430
+ meta.last_report = report;
22431
+ writeOptimizationMetadata(memoryDir, meta);
22432
+ }
22433
+ return report;
22434
+ }
22435
+ function maybeAutoOptimize(store, memoryDir) {
22436
+ const dir = memoryDir || store.memoryDir || ".memory";
22437
+ const check = shouldAutoOptimize(dir);
22438
+ if (!check.shouldRun)
22439
+ return null;
22440
+ try {
22441
+ return optimizeStore(store, { memoryDir: dir, force: true });
22442
+ } catch {
22443
+ return null;
22444
+ }
22445
+ }
22446
+ var META_FILE_NAME = "optimization_meta.json";
22447
+ var init_optimize = __esm(() => {
22448
+ init_store();
22449
+ init_dedup();
22450
+ init_audit();
22451
+ init_governor();
22452
+ });
22453
+
22031
22454
  // src/ui.ts
22032
22455
  var exports_ui = {};
22033
22456
  __export(exports_ui, {
@@ -22327,6 +22750,42 @@ function startUiServer(opts) {
22327
22750
  }
22328
22751
  return;
22329
22752
  }
22753
+ if (pathname === "/api/optimize" && req.method === "POST") {
22754
+ try {
22755
+ const { optimizeStore: optimizeStore2 } = await Promise.resolve().then(() => (init_optimize(), exports_optimize));
22756
+ const body = await parseJsonBody(req);
22757
+ const report = optimizeStore2(opts.store, {
22758
+ memoryDir: opts.memoryDir,
22759
+ project: body.project ? String(body.project) : undefined,
22760
+ dryRun: body.dryRun === true,
22761
+ force: body.force !== false
22762
+ });
22763
+ res.writeHead(200, { "Content-Type": "application/json" });
22764
+ res.end(JSON.stringify({ success: true, report }));
22765
+ } catch (err) {
22766
+ res.writeHead(500, { "Content-Type": "application/json" });
22767
+ res.end(JSON.stringify({ error: String(err) }));
22768
+ }
22769
+ return;
22770
+ }
22771
+ if (pathname === "/api/optimize/status" && req.method === "GET") {
22772
+ try {
22773
+ const { readOptimizationMetadata: readOptimizationMetadata2, shouldAutoOptimize: shouldAutoOptimize2 } = await Promise.resolve().then(() => (init_optimize(), exports_optimize));
22774
+ const meta = readOptimizationMetadata2(opts.memoryDir);
22775
+ const autoCheck = shouldAutoOptimize2(opts.memoryDir);
22776
+ res.writeHead(200, { "Content-Type": "application/json" });
22777
+ res.end(JSON.stringify({
22778
+ success: true,
22779
+ meta,
22780
+ shouldAutoOptimize: autoCheck.shouldRun,
22781
+ autoOptimizeReason: autoCheck.reason
22782
+ }));
22783
+ } catch (err) {
22784
+ res.writeHead(500, { "Content-Type": "application/json" });
22785
+ res.end(JSON.stringify({ error: String(err) }));
22786
+ }
22787
+ return;
22788
+ }
22330
22789
  const workspaceRoot = opts.store.layout?.root || getStorageLayout(opts.memoryDir).root;
22331
22790
  if (pathname === "/api/health" && req.method === "GET") {
22332
22791
  try {
@@ -22828,6 +23287,10 @@ var MAX_BODY_SIZE, EMBEDDED_HTML = `<!DOCTYPE html>
22828
23287
  <span class="refresh-icon" id="refreshIcon">\uD83D\uDD04</span>
22829
23288
  <span id="refreshLabel">Refresh</span>
22830
23289
  </button>
23290
+ <button class="btn-icon btn-optimize" id="optimizeBtn" onclick="optimizeStoreDashboard()" title="Clean test noise, prune junk, deduplicate candidates, and defragment SQLite storage">
23291
+ <span class="optimize-icon" id="optimizeIcon">⚡</span>
23292
+ <span id="optimizeLabel">Optimize</span>
23293
+ </button>
22831
23294
  <div class="status-badge"><div class="status-dot"></div>[LIVE] Active</div>
22832
23295
  <button class="btn-icon" onclick="exportDataHtml()">⬇ Export HTML</button>
22833
23296
  </div>
@@ -23289,6 +23752,40 @@ var MAX_BODY_SIZE, EMBEDDED_HTML = `<!DOCTYPE html>
23289
23752
  }
23290
23753
  }
23291
23754
 
23755
+ async function optimizeStoreDashboard() {
23756
+ const icon = document.getElementById('optimizeIcon');
23757
+ const label = document.getElementById('optimizeLabel');
23758
+ const btn = document.getElementById('optimizeBtn');
23759
+ if (icon) icon.classList.add('spinning');
23760
+ if (label) label.textContent = 'Optimizing...';
23761
+ if (btn) btn.disabled = true;
23762
+
23763
+ try {
23764
+ const res = await fetch('/api/optimize', {
23765
+ method: 'POST',
23766
+ headers: { 'Content-Type': 'application/json' },
23767
+ body: JSON.stringify({ force: true }),
23768
+ });
23769
+ const data = await res.json();
23770
+ if (!data.success) throw new Error(data.error || 'Optimization failed');
23771
+ const rep = data.report;
23772
+ await loadData();
23773
+ const formatBytes = (b) => {
23774
+ if (b >= 1024 * 1024) return (b / (1024 * 1024)).toFixed(1) + ' MB';
23775
+ if (b >= 1024) return (b / 1024).toFixed(1) + ' KB';
23776
+ return b + ' B';
23777
+ };
23778
+ const spaceMsg = rep.spaceReclaimedBytes > 0 ? ' Reclaimed ' + formatBytes(rep.spaceReclaimedBytes) + '.' : '';
23779
+ flash('⚡ Optimization Complete! Pruned ' + rep.totalPruned + ' items (' + rep.prunedNoise + ' noise, ' + rep.prunedJunk + ' junk, ' + rep.prunedDuplicates + ' dupes).' + spaceMsg);
23780
+ } catch (err) {
23781
+ flash('Optimization failed: ' + (err && err.message ? err.message : String(err)), true);
23782
+ } finally {
23783
+ if (icon) icon.classList.remove('spinning');
23784
+ if (label) label.textContent = 'Optimize';
23785
+ if (btn) btn.disabled = false;
23786
+ }
23787
+ }
23788
+
23292
23789
  async function loadData() {
23293
23790
  try {
23294
23791
  if (window.STANDALONE_DATA) {
@@ -32596,8 +33093,8 @@ var init_loops = __esm(() => {
32596
33093
  });
32597
33094
 
32598
33095
  // src/distill.ts
32599
- import { existsSync as existsSync39, mkdirSync as mkdirSync21, writeFileSync as writeFileSync19 } from "node:fs";
32600
- import { join as join36 } from "node:path";
33096
+ import { existsSync as existsSync40, mkdirSync as mkdirSync21, writeFileSync as writeFileSync20 } from "node:fs";
33097
+ import { join as join37 } from "node:path";
32601
33098
  function fixTokens(e) {
32602
33099
  const bag = tokenBag(e.title, 2);
32603
33100
  mergeBag(bag, tokenBag((e.tags ?? []).join(" "), 2));
@@ -32608,7 +33105,7 @@ function distillSkills(store, workspaceRoot, options = {}) {
32608
33105
  const report = { created: [], skippedExisting: [], clustersBelowThreshold: 0 };
32609
33106
  const fixes = list(store).filter((e) => e.status === "confirmed" && e.type === "fix").sort((a, b) => Date.parse(a.created_at) - Date.parse(b.created_at));
32610
33107
  const clusters = clusterByTokenOverlap(fixes, fixTokens, 0.5);
32611
- const skillsDir = options.skillsDir ?? join36(workspaceRoot, ".agents", "skills");
33108
+ const skillsDir = options.skillsDir ?? join37(workspaceRoot, ".agents", "skills");
32612
33109
  for (const cluster of clusters) {
32613
33110
  if (cluster.length < minCount) {
32614
33111
  report.clustersBelowThreshold++;
@@ -32616,9 +33113,9 @@ function distillSkills(store, workspaceRoot, options = {}) {
32616
33113
  }
32617
33114
  const topic = dominantTopicTokens(cluster.map((e) => e.title));
32618
33115
  const slug = slugifyId(topic.join("-") || "skill");
32619
- const dir = join36(skillsDir, slug);
33116
+ const dir = join37(skillsDir, slug);
32620
33117
  const memberIds = cluster.map((e) => e.id);
32621
- if (existsSync39(dir)) {
33118
+ if (existsSync40(dir)) {
32622
33119
  report.skippedExisting.push({ slug, members: memberIds });
32623
33120
  continue;
32624
33121
  }
@@ -32629,9 +33126,9 @@ function distillSkills(store, workspaceRoot, options = {}) {
32629
33126
  }
32630
33127
  if (!options.dryRun) {
32631
33128
  mkdirSync21(dir, { recursive: true });
32632
- writeFileSync19(join36(dir, "SKILL.md"), md, "utf8");
33129
+ writeFileSync20(join37(dir, "SKILL.md"), md, "utf8");
32633
33130
  }
32634
- report.created.push({ slug, path: join36(dir, "SKILL.md"), members: memberIds });
33131
+ report.created.push({ slug, path: join37(dir, "SKILL.md"), members: memberIds });
32635
33132
  }
32636
33133
  return report;
32637
33134
  }
@@ -32681,18 +33178,18 @@ __export(exports_provenance, {
32681
33178
  loadSources: () => loadSources,
32682
33179
  saveSources: () => saveSources
32683
33180
  });
32684
- import { existsSync as existsSync40, readFileSync as readFileSync33, writeFileSync as writeFileSync20, mkdirSync as mkdirSync22 } from "node:fs";
32685
- import { join as join37 } from "node:path";
33181
+ import { existsSync as existsSync41, readFileSync as readFileSync34, writeFileSync as writeFileSync21, mkdirSync as mkdirSync22 } from "node:fs";
33182
+ import { join as join38 } from "node:path";
32686
33183
  function getSourcesFilePath(memoryDir) {
32687
- return join37(memoryDir, "sources.json");
33184
+ return join38(memoryDir, "sources.json");
32688
33185
  }
32689
33186
  function loadSources(memoryDir) {
32690
33187
  const filePath = getSourcesFilePath(memoryDir);
32691
- if (!existsSync40(filePath)) {
33188
+ if (!existsSync41(filePath)) {
32692
33189
  return [];
32693
33190
  }
32694
33191
  try {
32695
- const raw = readFileSync33(filePath, "utf-8");
33192
+ const raw = readFileSync34(filePath, "utf-8");
32696
33193
  const parsed = JSON.parse(raw);
32697
33194
  return Array.isArray(parsed) ? parsed : [];
32698
33195
  } catch {
@@ -32702,7 +33199,7 @@ function loadSources(memoryDir) {
32702
33199
  function saveSources(memoryDir, sources) {
32703
33200
  mkdirSync22(memoryDir, { recursive: true });
32704
33201
  const filePath = getSourcesFilePath(memoryDir);
32705
- writeFileSync20(filePath, JSON.stringify(sources, null, 2), "utf-8");
33202
+ writeFileSync21(filePath, JSON.stringify(sources, null, 2), "utf-8");
32706
33203
  }
32707
33204
  function addSource(memoryDir, input) {
32708
33205
  const textToScan = `${input.title}
@@ -32769,18 +33266,18 @@ __export(exports_claims, {
32769
33266
  recordClaim: () => recordClaim,
32770
33267
  saveClaims: () => saveClaims
32771
33268
  });
32772
- import { existsSync as existsSync41, readFileSync as readFileSync34, writeFileSync as writeFileSync21, mkdirSync as mkdirSync23 } from "node:fs";
32773
- import { join as join38 } from "node:path";
33269
+ import { existsSync as existsSync42, readFileSync as readFileSync35, writeFileSync as writeFileSync22, mkdirSync as mkdirSync23 } from "node:fs";
33270
+ import { join as join39 } from "node:path";
32774
33271
  function getClaimsFilePath(memoryDir) {
32775
- return join38(memoryDir, "claims.json");
33272
+ return join39(memoryDir, "claims.json");
32776
33273
  }
32777
33274
  function loadClaims(memoryDir) {
32778
33275
  const filePath = getClaimsFilePath(memoryDir);
32779
- if (!existsSync41(filePath)) {
33276
+ if (!existsSync42(filePath)) {
32780
33277
  return [];
32781
33278
  }
32782
33279
  try {
32783
- const raw = readFileSync34(filePath, "utf-8");
33280
+ const raw = readFileSync35(filePath, "utf-8");
32784
33281
  const parsed = JSON.parse(raw);
32785
33282
  return Array.isArray(parsed) ? parsed : [];
32786
33283
  } catch {
@@ -32790,7 +33287,7 @@ function loadClaims(memoryDir) {
32790
33287
  function saveClaims(memoryDir, claims) {
32791
33288
  mkdirSync23(memoryDir, { recursive: true });
32792
33289
  const filePath = getClaimsFilePath(memoryDir);
32793
- writeFileSync21(filePath, JSON.stringify(claims, null, 2), "utf-8");
33290
+ writeFileSync22(filePath, JSON.stringify(claims, null, 2), "utf-8");
32794
33291
  }
32795
33292
  function recordClaim(memoryDir, input) {
32796
33293
  const textToScan = `${input.claim}
@@ -32935,8 +33432,8 @@ ${result.stderr}`.trim().slice(0, 2000)
32935
33432
  return result;
32936
33433
  }
32937
33434
  function verifyStrictIntegrity(store, memoryDir, workspaceRoot, options = {}) {
32938
- const { existsSync: existsSync42, readFileSync: readFileSync35, readdirSync: readdirSync16 } = __require("node:fs");
32939
- const { join: join39 } = __require("node:path");
33435
+ const { existsSync: existsSync43, readFileSync: readFileSync36, readdirSync: readdirSync16 } = __require("node:fs");
33436
+ const { join: join40 } = __require("node:path");
32940
33437
  const { scanSecrets: scanSecrets2 } = (init_secrets(), __toCommonJS(exports_secrets));
32941
33438
  const { list: list2 } = (init_store(), __toCommonJS(exports_store));
32942
33439
  const { loadSources: loadSources2 } = (init_provenance(), __toCommonJS(exports_provenance));
@@ -32954,15 +33451,15 @@ ${(e.tags ?? []).join(" ")}`;
32954
33451
  secretErrors.push(`Secret detected in memory ${e.id}: ${found.join(", ")}`);
32955
33452
  }
32956
33453
  }
32957
- const currentPath = join39(memoryDir, "CURRENT.md");
32958
- if (existsSync42(currentPath)) {
32959
- const found = scanSecrets2(readFileSync35(currentPath, "utf-8"));
33454
+ const currentPath = join40(memoryDir, "CURRENT.md");
33455
+ if (existsSync43(currentPath)) {
33456
+ const found = scanSecrets2(readFileSync36(currentPath, "utf-8"));
32960
33457
  if (found.length > 0)
32961
33458
  secretErrors.push(`Secret detected in CURRENT.md: ${found.join(", ")}`);
32962
33459
  }
32963
- const userPath = join39(memoryDir, "USER.md");
32964
- if (existsSync42(userPath)) {
32965
- const found = scanSecrets2(readFileSync35(userPath, "utf-8"));
33460
+ const userPath = join40(memoryDir, "USER.md");
33461
+ if (existsSync43(userPath)) {
33462
+ const found = scanSecrets2(readFileSync36(userPath, "utf-8"));
32966
33463
  if (found.length > 0)
32967
33464
  secretErrors.push(`Secret detected in USER.md: ${found.join(", ")}`);
32968
33465
  }
@@ -33031,12 +33528,12 @@ ${(e.tags ?? []).join(" ")}`;
33031
33528
  errors: claimErrors.length > 0 ? claimErrors : undefined
33032
33529
  });
33033
33530
  const wikiErrors = [];
33034
- const wikiDir = join39(memoryDir, "wiki");
33035
- if (existsSync42(wikiDir)) {
33531
+ const wikiDir = join40(memoryDir, "wiki");
33532
+ if (existsSync43(wikiDir)) {
33036
33533
  let collectSlugs = function(dir) {
33037
33534
  const items = readdirSync16(dir, { withFileTypes: true });
33038
33535
  for (const it of items) {
33039
- const full = join39(dir, it.name);
33536
+ const full = join40(dir, it.name);
33040
33537
  if (it.isDirectory()) {
33041
33538
  collectSlugs(full);
33042
33539
  } else if (it.name.endsWith(".md")) {
@@ -33048,11 +33545,11 @@ ${(e.tags ?? []).join(" ")}`;
33048
33545
  }, scanWikilinks = function(dir) {
33049
33546
  const items = readdirSync16(dir, { withFileTypes: true });
33050
33547
  for (const it of items) {
33051
- const full = join39(dir, it.name);
33548
+ const full = join40(dir, it.name);
33052
33549
  if (it.isDirectory()) {
33053
33550
  scanWikilinks(full);
33054
33551
  } else if (it.name.endsWith(".md")) {
33055
- const content = readFileSync35(full, "utf-8");
33552
+ const content = readFileSync36(full, "utf-8");
33056
33553
  const matches = content.matchAll(/\[\[([a-zA-Z0-9_\-\./ ]+?)(?:\|[^\r\n\]]+)?\]\]/g);
33057
33554
  for (const m of matches) {
33058
33555
  const rawTarget = m[1].trim().toLowerCase();
@@ -33319,14 +33816,14 @@ var init_schema2 = __esm(() => {
33319
33816
  });
33320
33817
 
33321
33818
  // src/settings/loader.ts
33322
- import { existsSync as existsSync42, mkdirSync as mkdirSync24, readFileSync as readFileSync35, writeFileSync as writeFileSync22 } from "node:fs";
33323
- import { join as join39 } from "node:path";
33819
+ import { existsSync as existsSync43, mkdirSync as mkdirSync24, readFileSync as readFileSync36, writeFileSync as writeFileSync23 } from "node:fs";
33820
+ import { join as join40 } from "node:path";
33324
33821
  function getSettingsFilePath(memoryDir) {
33325
- return join39(memoryDir, "settings.json");
33822
+ return join40(memoryDir, "settings.json");
33326
33823
  }
33327
33824
  function loadSettings(memoryDir) {
33328
33825
  const filePath = getSettingsFilePath(memoryDir);
33329
- if (!existsSync42(filePath)) {
33826
+ if (!existsSync43(filePath)) {
33330
33827
  return {
33331
33828
  version: 1,
33332
33829
  global: JSON.parse(JSON.stringify(DEFAULT_SETTINGS)),
@@ -33334,7 +33831,7 @@ function loadSettings(memoryDir) {
33334
33831
  };
33335
33832
  }
33336
33833
  try {
33337
- const raw = readFileSync35(filePath, "utf8");
33834
+ const raw = readFileSync36(filePath, "utf8");
33338
33835
  const parsed = JSON.parse(raw);
33339
33836
  return {
33340
33837
  version: parsed.version || 1,
@@ -33352,7 +33849,7 @@ function loadSettings(memoryDir) {
33352
33849
  function saveSettings(store, memoryDir) {
33353
33850
  mkdirSync24(memoryDir, { recursive: true });
33354
33851
  const filePath = getSettingsFilePath(memoryDir);
33355
- writeFileSync22(filePath, JSON.stringify(store, null, 2), "utf8");
33852
+ writeFileSync23(filePath, JSON.stringify(store, null, 2), "utf8");
33356
33853
  }
33357
33854
  function getSettings(memoryDir) {
33358
33855
  return loadSettings(memoryDir).global;
@@ -33460,10 +33957,10 @@ var init_settings2 = __esm(() => {
33460
33957
  });
33461
33958
 
33462
33959
  // src/learning/observation.ts
33463
- import { existsSync as existsSync43, readFileSync as readFileSync36, appendFileSync as appendFileSync2, writeFileSync as writeFileSync23, mkdirSync as mkdirSync25 } from "node:fs";
33464
- import { join as join40 } from "node:path";
33960
+ import { existsSync as existsSync44, readFileSync as readFileSync37, appendFileSync as appendFileSync2, writeFileSync as writeFileSync24, mkdirSync as mkdirSync25 } from "node:fs";
33961
+ import { join as join41 } from "node:path";
33465
33962
  function observationsFilePath(memoryDir) {
33466
- return join40(memoryDir, "observations.jsonl");
33963
+ return join41(memoryDir, "observations.jsonl");
33467
33964
  }
33468
33965
  function recordObservation(store, obs) {
33469
33966
  if (!obs.raw || !obs.raw.trim()) {
@@ -33475,7 +33972,7 @@ function recordObservation(store, obs) {
33475
33972
  }
33476
33973
  const memoryDir = store.memoryDir || store.dir;
33477
33974
  const filePath = observationsFilePath(memoryDir);
33478
- if (!existsSync43(memoryDir)) {
33975
+ if (!existsSync44(memoryDir)) {
33479
33976
  mkdirSync25(memoryDir, { recursive: true });
33480
33977
  }
33481
33978
  const id = `obs_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
@@ -33496,9 +33993,9 @@ function recordObservation(store, obs) {
33496
33993
  function listObservations(store, options) {
33497
33994
  const memoryDir = store.memoryDir || store.dir;
33498
33995
  const filePath = observationsFilePath(memoryDir);
33499
- if (!existsSync43(filePath))
33996
+ if (!existsSync44(filePath))
33500
33997
  return [];
33501
- const lines = readFileSync36(filePath, "utf8").split(`
33998
+ const lines = readFileSync37(filePath, "utf8").split(`
33502
33999
  `).filter((l) => l.trim().length > 0);
33503
34000
  const results = [];
33504
34001
  for (const line of lines) {
@@ -33518,9 +34015,9 @@ function listObservations(store, options) {
33518
34015
  function markObservationProcessed(store, observationId, extractedCandidateId) {
33519
34016
  const memoryDir = store.memoryDir || store.dir;
33520
34017
  const filePath = observationsFilePath(memoryDir);
33521
- if (!existsSync43(filePath))
34018
+ if (!existsSync44(filePath))
33522
34019
  return false;
33523
- const lines = readFileSync36(filePath, "utf8").split(`
34020
+ const lines = readFileSync37(filePath, "utf8").split(`
33524
34021
  `).filter((l) => l.trim().length > 0);
33525
34022
  let updated = false;
33526
34023
  const newLines = [];
@@ -33539,7 +34036,7 @@ function markObservationProcessed(store, observationId, extractedCandidateId) {
33539
34036
  }
33540
34037
  }
33541
34038
  if (updated) {
33542
- writeFileSync23(filePath, `${newLines.join(`
34039
+ writeFileSync24(filePath, `${newLines.join(`
33543
34040
  `)}
33544
34041
  `, "utf8");
33545
34042
  }
@@ -33840,8 +34337,8 @@ var init_bidirectional = __esm(() => {
33840
34337
  });
33841
34338
 
33842
34339
  // src/intelligence/impact.ts
33843
- import { existsSync as existsSync44, readdirSync as readdirSync16, readFileSync as readFileSync37 } from "node:fs";
33844
- import { join as join41, basename as basename2 } from "node:path";
34340
+ import { existsSync as existsSync45, readdirSync as readdirSync16, readFileSync as readFileSync38 } from "node:fs";
34341
+ import { join as join42, basename as basename2 } from "node:path";
33845
34342
  async function analyzeMemoryCodeImpact(store, options) {
33846
34343
  const root = options.workspaceRoot || store.dir || process.cwd();
33847
34344
  const targetFile = options.filePath;
@@ -33919,10 +34416,10 @@ async function analyzeMemoryCodeImpact(store, options) {
33919
34416
  }
33920
34417
  }
33921
34418
  const activeConstraints = memoryRes.constraints.map((c) => c.title);
33922
- const currentMdPath = join41(store.memoryDir || join41(root, ".memory"), "CURRENT.md");
33923
- if (existsSync44(currentMdPath)) {
34419
+ const currentMdPath = join42(store.memoryDir || join42(root, ".memory"), "CURRENT.md");
34420
+ if (existsSync45(currentMdPath)) {
33924
34421
  try {
33925
- const currentContent = readFileSync37(currentMdPath, "utf8");
34422
+ const currentContent = readFileSync38(currentMdPath, "utf8");
33926
34423
  const lines = currentContent.split(`
33927
34424
  `);
33928
34425
  for (const line of lines) {
@@ -33942,14 +34439,14 @@ async function analyzeMemoryCodeImpact(store, options) {
33942
34439
  totalMemoryEntities: linkedMemories.length + matchedAdrs.length + negativeWarnings.length + activeConstraints.length
33943
34440
  };
33944
34441
  const relatedDocs = [];
33945
- const docsDir = join41(root, "docs");
33946
- if (existsSync44(docsDir)) {
34442
+ const docsDir = join42(root, "docs");
34443
+ if (existsSync45(docsDir)) {
33947
34444
  try {
33948
34445
  const docFiles = readdirSync16(docsDir, { recursive: true });
33949
34446
  for (const df of docFiles) {
33950
34447
  if (typeof df === "string" && (df.endsWith(".md") || df.endsWith(".mdx"))) {
33951
- const fullPath = join41(docsDir, df);
33952
- const content = readFileSync37(fullPath, "utf8").toLowerCase();
34448
+ const fullPath = join42(docsDir, df);
34449
+ const content = readFileSync38(fullPath, "utf8").toLowerCase();
33953
34450
  if (content.includes(fileBase) || targetSymbol && content.includes(targetSymbol.toLowerCase())) {
33954
34451
  relatedDocs.push(`docs/${df}`);
33955
34452
  }
@@ -33957,10 +34454,10 @@ async function analyzeMemoryCodeImpact(store, options) {
33957
34454
  }
33958
34455
  } catch {}
33959
34456
  }
33960
- const readmePath = join41(root, "README.md");
33961
- if (existsSync44(readmePath)) {
34457
+ const readmePath = join42(root, "README.md");
34458
+ if (existsSync45(readmePath)) {
33962
34459
  try {
33963
- const readmeContent = readFileSync37(readmePath, "utf8").toLowerCase();
34460
+ const readmeContent = readFileSync38(readmePath, "utf8").toLowerCase();
33964
34461
  if (readmeContent.includes(fileBase) || targetSymbol && readmeContent.includes(targetSymbol.toLowerCase())) {
33965
34462
  relatedDocs.push("README.md");
33966
34463
  }
@@ -34125,8 +34622,8 @@ var init_intelligence = __esm(() => {
34125
34622
  init_impact();
34126
34623
  });
34127
34624
  // src/compaction/engine.ts
34128
- import { existsSync as existsSync45, writeFileSync as writeFileSync24, mkdirSync as mkdirSync26 } from "node:fs";
34129
- import { join as join42 } from "node:path";
34625
+ import { existsSync as existsSync46, writeFileSync as writeFileSync25, mkdirSync as mkdirSync26 } from "node:fs";
34626
+ import { join as join43 } from "node:path";
34130
34627
  function evaluateContextUsage(usedTokens, maxTokens = DEFAULT_CONTEXT_MAX_TOKENS) {
34131
34628
  const usagePercent = Math.round(usedTokens / maxTokens * 100);
34132
34629
  const thresholdExceeded = usagePercent >= COMPACTION_THRESHOLD_PERCENT;
@@ -34218,12 +34715,12 @@ function generateSessionHandoff(memoryDir, invariants, options) {
34218
34715
  if (!invariants.highLevelGoal || !invariants.nextConcreteTask) {
34219
34716
  throw new Error("Cannot generate handoff: highLevelGoal and nextConcreteTask are mandatory");
34220
34717
  }
34221
- if (!existsSync45(memoryDir)) {
34718
+ if (!existsSync46(memoryDir)) {
34222
34719
  mkdirSync26(memoryDir, { recursive: true });
34223
34720
  }
34224
- const currentMdPath = join42(memoryDir, "CURRENT.md");
34721
+ const currentMdPath = join43(memoryDir, "CURRENT.md");
34225
34722
  const markdownContent = renderCurrentMdContent(invariants, options);
34226
- writeFileSync24(currentMdPath, markdownContent, "utf8");
34723
+ writeFileSync25(currentMdPath, markdownContent, "utf8");
34227
34724
  recordAuditEvent(memoryDir, {
34228
34725
  operation: "checkpoint",
34229
34726
  entry_id: "CURRENT.md",
@@ -34363,8 +34860,8 @@ var init_harvester2 = __esm(() => {
34363
34860
 
34364
34861
  // src/compaction/pr-context.ts
34365
34862
  import { execFileSync } from "node:child_process";
34366
- import { existsSync as existsSync46, readFileSync as readFileSync38 } from "node:fs";
34367
- import { join as join43, basename as basename3 } from "node:path";
34863
+ import { existsSync as existsSync47, readFileSync as readFileSync39 } from "node:fs";
34864
+ import { join as join44, basename as basename3 } from "node:path";
34368
34865
  async function generatePrContext(store, options = {}) {
34369
34866
  const root = options.workspaceRoot || store.dir || process.cwd();
34370
34867
  const rawBase = options.baseBranch || "main";
@@ -34435,10 +34932,10 @@ async function generatePrContext(store, options = {}) {
34435
34932
  } catch {}
34436
34933
  }
34437
34934
  const activeConstraints = [];
34438
- const currentMdPath = join43(store.memoryDir || join43(root, ".memory"), "CURRENT.md");
34439
- if (existsSync46(currentMdPath)) {
34935
+ const currentMdPath = join44(store.memoryDir || join44(root, ".memory"), "CURRENT.md");
34936
+ if (existsSync47(currentMdPath)) {
34440
34937
  try {
34441
- const lines = readFileSync38(currentMdPath, "utf8").split(`
34938
+ const lines = readFileSync39(currentMdPath, "utf8").split(`
34442
34939
  `);
34443
34940
  for (const line of lines) {
34444
34941
  const trimmed = line.trim();
@@ -34591,8 +35088,6 @@ var init_anchors = __esm(() => {
34591
35088
  init_resolver();
34592
35089
  });
34593
35090
  // src/orchestrator/context.ts
34594
- import { existsSync as existsSync47, readFileSync as readFileSync39 } from "node:fs";
34595
- import { join as join44 } from "node:path";
34596
35091
  function estimateTokens(text) {
34597
35092
  return Math.max(1, Math.ceil(text.length / 4));
34598
35093
  }
@@ -34619,18 +35114,29 @@ async function resolveMuseContext(store, workspaceRoot, input) {
34619
35114
  const compositeQuery = queryParts.join(" ") || "active constraints and architecture";
34620
35115
  const activeConstraints = [];
34621
35116
  if (store.memoryDir) {
34622
- const currentPath = join44(store.memoryDir, "CURRENT.md");
34623
- if (existsSync47(currentPath)) {
34624
- const currentMd = readFileSync39(currentPath, "utf8");
34625
- const constraintMatch = currentMd.match(/## Active Working Constraints & Open Loops([\s\S]*?)(?:##|$)/);
34626
- if (constraintMatch && constraintMatch[1].trim()) {
35117
+ try {
35118
+ const currentData = parseCurrentFile(store.memoryDir);
35119
+ if (currentData.constraints.length > 0) {
34627
35120
  activeConstraints.push({
34628
35121
  id: "current_md_constraints",
34629
35122
  title: "Session Working Constraints",
34630
- content: constraintMatch[1].trim()
35123
+ content: currentData.constraints.join(`
35124
+ `)
34631
35125
  });
34632
35126
  }
34633
- }
35127
+ if (currentData.workstreams && currentData.workstreams.length > 0) {
35128
+ const activeWs = currentData.workstreams.filter((w) => w.status === "IN-PROGRESS" || w.status === "BLOCKED");
35129
+ if (activeWs.length > 0) {
35130
+ const wsSummary = activeWs.map((w) => `- Agent \`${w.agent}\` [${w.status}]: ${w.task}${w.targetScope ? ` (Scope: ${w.targetScope})` : ""}`).join(`
35131
+ `);
35132
+ activeConstraints.push({
35133
+ id: "concurrent_workstreams",
35134
+ title: "Active Concurrent Agent Workstreams",
35135
+ content: wsSummary
35136
+ });
35137
+ }
35138
+ }
35139
+ } catch {}
34634
35140
  }
34635
35141
  const allEntries = list(store);
34636
35142
  const constraintEntries = allEntries.filter((e) => (e.type === "constraint" || e.temporal_mode === "timeless") && e.status !== "archived" && e.status !== "superseded" && e.status !== "rejected");
@@ -34746,6 +35252,7 @@ ${c.content}`);
34746
35252
  var init_context = __esm(() => {
34747
35253
  init_store();
34748
35254
  init_ranking();
35255
+ init_governor();
34749
35256
  });
34750
35257
 
34751
35258
  // src/orchestrator/profiles.ts
@@ -34884,7 +35391,7 @@ var init_orchestrator = __esm(() => {
34884
35391
  });
34885
35392
 
34886
35393
  // src/prompts.ts
34887
- import { existsSync as existsSync48, readFileSync as readFileSync40, writeFileSync as writeFileSync25, mkdirSync as mkdirSync27, readdirSync as readdirSync17 } from "node:fs";
35394
+ import { existsSync as existsSync48, readFileSync as readFileSync40, writeFileSync as writeFileSync26, mkdirSync as mkdirSync27, readdirSync as readdirSync17 } from "node:fs";
34888
35395
  import { join as join45 } from "node:path";
34889
35396
  function getPromptsDir(memoryDir) {
34890
35397
  if (!memoryDir)
@@ -35073,7 +35580,7 @@ Period: {{period}}
35073
35580
  });
35074
35581
 
35075
35582
  // src/compounding/temporal.ts
35076
- import { existsSync as existsSync49, readFileSync as readFileSync41, writeFileSync as writeFileSync26, mkdirSync as mkdirSync28 } from "node:fs";
35583
+ import { existsSync as existsSync49, readFileSync as readFileSync41, writeFileSync as writeFileSync27, mkdirSync as mkdirSync28 } from "node:fs";
35077
35584
  import { join as join46 } from "node:path";
35078
35585
  function getPeriodKey(dateInput, period) {
35079
35586
  const date4 = typeof dateInput === "string" ? new Date(dateInput) : dateInput;
@@ -35143,7 +35650,7 @@ function compileHotCache(store, memoryDir) {
35143
35650
  `;
35144
35651
  const hotPath = join46(memoryDir, "HOT.md");
35145
35652
  mkdirSync28(memoryDir, { recursive: true });
35146
- writeFileSync26(hotPath, hotContent, "utf-8");
35653
+ writeFileSync27(hotPath, hotContent, "utf-8");
35147
35654
  return hotPath;
35148
35655
  }
35149
35656
  function rollupTemporal(store, options) {
@@ -35197,7 +35704,7 @@ function rollupTemporal(store, options) {
35197
35704
  const rollupDir = join46(memoryDir, "wiki", "rollups");
35198
35705
  mkdirSync28(rollupDir, { recursive: true });
35199
35706
  const filePath = join46(rollupDir, `${periodKey}.md`);
35200
- writeFileSync26(filePath, lines.join(`
35707
+ writeFileSync27(filePath, lines.join(`
35201
35708
  `) + `
35202
35709
  `, "utf-8");
35203
35710
  const hotMdPath = compileHotCache(store, memoryDir);
@@ -35214,7 +35721,7 @@ var init_temporal = __esm(() => {
35214
35721
  });
35215
35722
 
35216
35723
  // src/iterations.ts
35217
- import { existsSync as existsSync50, readFileSync as readFileSync42, appendFileSync as appendFileSync3, writeFileSync as writeFileSync27, mkdirSync as mkdirSync29 } from "node:fs";
35724
+ import { existsSync as existsSync50, readFileSync as readFileSync42, appendFileSync as appendFileSync3, writeFileSync as writeFileSync28, mkdirSync as mkdirSync29 } from "node:fs";
35218
35725
  import { join as join47 } from "node:path";
35219
35726
  function getIterationsFilePath(memoryDir) {
35220
35727
  return join47(memoryDir, "iterations.jsonl");
@@ -35257,7 +35764,7 @@ function listIterations(memoryDir) {
35257
35764
  function clearIterations(memoryDir) {
35258
35765
  const filePath = getIterationsFilePath(memoryDir);
35259
35766
  if (existsSync50(filePath)) {
35260
- writeFileSync27(filePath, "", "utf-8");
35767
+ writeFileSync28(filePath, "", "utf-8");
35261
35768
  }
35262
35769
  }
35263
35770
  function detectIterationStatus(memoryDir) {
@@ -35318,7 +35825,7 @@ __export(exports_plasticity, {
35318
35825
  recordCoActivation: () => recordCoActivation,
35319
35826
  saveHebbianGraph: () => saveHebbianGraph
35320
35827
  });
35321
- import { existsSync as existsSync51, readFileSync as readFileSync43, writeFileSync as writeFileSync28 } from "node:fs";
35828
+ import { existsSync as existsSync51, readFileSync as readFileSync43, writeFileSync as writeFileSync29 } from "node:fs";
35322
35829
  import { join as join48 } from "node:path";
35323
35830
  function getPlasticityPath(memoryDir) {
35324
35831
  return join48(memoryDir, "hebbian-plasticity.json");
@@ -35336,7 +35843,7 @@ function loadHebbianGraph(memoryDir) {
35336
35843
  function saveHebbianGraph(memoryDir, graph) {
35337
35844
  const p = getPlasticityPath(memoryDir);
35338
35845
  try {
35339
- writeFileSync28(p, JSON.stringify(graph, null, 2), "utf8");
35846
+ writeFileSync29(p, JSON.stringify(graph, null, 2), "utf8");
35340
35847
  } catch {}
35341
35848
  }
35342
35849
  function recordCoActivation(memoryIds, memoryDir) {
@@ -38156,7 +38663,7 @@ var init_daemon = () => {};
38156
38663
 
38157
38664
  // src/cli/ecosystem.ts
38158
38665
  import { join as join51 } from "node:path";
38159
- import { existsSync as existsSync54, mkdirSync as mkdirSync30, writeFileSync as writeFileSync29, readFileSync as readFileSync44 } from "node:fs";
38666
+ import { existsSync as existsSync54, mkdirSync as mkdirSync30, writeFileSync as writeFileSync30, readFileSync as readFileSync44 } from "node:fs";
38160
38667
  import { homedir as homedir7 } from "node:os";
38161
38668
  function ensureProjectAgentInstructions(targetDir) {
38162
38669
  const agentsMdPath = join51(targetDir, "AGENTS.md");
@@ -38165,9 +38672,9 @@ function ensureProjectAgentInstructions(targetDir) {
38165
38672
  const existing = readFileSync44(agentsMdPath, "utf8");
38166
38673
  if (existing.includes("<!-- agentmemory:start -->")) {
38167
38674
  const updated = existing.replace(/<!-- agentmemory:start -->[\s\S]*?<!-- agentmemory:end -->/, MUSE_MEMORY_DIRECTIVE);
38168
- writeFileSync29(agentsMdPath, updated, "utf8");
38675
+ writeFileSync30(agentsMdPath, updated, "utf8");
38169
38676
  } else if (!existing.includes("<!-- musememory:start -->") && !existing.includes("Muse Memory")) {
38170
- writeFileSync29(agentsMdPath, `${existing.trim()}
38677
+ writeFileSync30(agentsMdPath, `${existing.trim()}
38171
38678
 
38172
38679
  ${MUSE_MEMORY_DIRECTIVE}
38173
38680
  `, "utf8");
@@ -38178,7 +38685,7 @@ ${MUSE_MEMORY_DIRECTIVE}
38178
38685
 
38179
38686
  ${MUSE_MEMORY_DIRECTIVE}
38180
38687
  `;
38181
- writeFileSync29(agentsMdPath, initialContent, "utf8");
38688
+ writeFileSync30(agentsMdPath, initialContent, "utf8");
38182
38689
  }
38183
38690
  }
38184
38691
  async function handleInstallCommand({ positional, flags }) {
@@ -38190,7 +38697,7 @@ async function handleInstallCommand({ positional, flags }) {
38190
38697
  mkdirSync30(join51(globalDir, "memories"), { recursive: true });
38191
38698
  const currentPath = join51(memoryDir, "CURRENT.md");
38192
38699
  if (!existsSync54(currentPath)) {
38193
- writeFileSync29(currentPath, `# Active Project Constraints
38700
+ writeFileSync30(currentPath, `# Active Project Constraints
38194
38701
  `, "utf8");
38195
38702
  }
38196
38703
  const globalUserPath = userFilePath(globalDir);
@@ -38216,7 +38723,7 @@ async function handleInstallCommand({ positional, flags }) {
38216
38723
  const existing = readFileSync44(globalAgentsMd, "utf8");
38217
38724
  if (existing.includes("<!-- agentmemory:start -->")) {
38218
38725
  const updated = existing.replace(/<!-- agentmemory:start -->[\s\S]*?<!-- agentmemory:end -->/, MUSE_MEMORY_DIRECTIVE);
38219
- writeFileSync29(globalAgentsMd, updated, "utf8");
38726
+ writeFileSync30(globalAgentsMd, updated, "utf8");
38220
38727
  }
38221
38728
  } catch {}
38222
38729
  }
@@ -38375,7 +38882,7 @@ async function handleInitCommand({ positional, flags }) {
38375
38882
  mkdirSync30(join51(memoryDir, "memories"), { recursive: true });
38376
38883
  const currentPath = join51(memoryDir, "CURRENT.md");
38377
38884
  if (!existsSync54(currentPath)) {
38378
- writeFileSync29(currentPath, `# Active Project Constraints
38885
+ writeFileSync30(currentPath, `# Active Project Constraints
38379
38886
  `, "utf8");
38380
38887
  }
38381
38888
  if (!isGlobal) {
@@ -39338,7 +39845,7 @@ var init_entities2 = __esm(() => {
39338
39845
  });
39339
39846
 
39340
39847
  // src/cli/settings.ts
39341
- import { writeFileSync as writeFileSync30, readFileSync as readFileSync46 } from "node:fs";
39848
+ import { writeFileSync as writeFileSync31, readFileSync as readFileSync46 } from "node:fs";
39342
39849
  function handleSettingsCommand(parsed) {
39343
39850
  const ctx = requireRoot(parsed.flags);
39344
39851
  if (!ctx)
@@ -39420,7 +39927,7 @@ function handleSettingsCommand(parsed) {
39420
39927
  const out = parsed.flags.out;
39421
39928
  const json2 = exportSettings(memoryDir);
39422
39929
  if (out) {
39423
- writeFileSync30(out, json2, "utf8");
39930
+ writeFileSync31(out, json2, "utf8");
39424
39931
  console.log(`Exported settings to ${out}`);
39425
39932
  } else {
39426
39933
  console.log(json2);
@@ -39504,7 +40011,7 @@ var init_routines = __esm(() => {
39504
40011
  });
39505
40012
 
39506
40013
  // src/cli/lifecycle.ts
39507
- import { writeFileSync as writeFileSync31, readFileSync as readFileSync48, existsSync as existsSync58 } from "node:fs";
40014
+ import { writeFileSync as writeFileSync32, readFileSync as readFileSync48, existsSync as existsSync58 } from "node:fs";
39508
40015
  async function handleProposeCommand({ positional, flags }) {
39509
40016
  const ctx = requireRoot(flags);
39510
40017
  if (!ctx)
@@ -39653,7 +40160,7 @@ async function handleExportCommand({ flags }) {
39653
40160
  const snapshot = exportSnapshot(ctx.store);
39654
40161
  const outPath = flags["out"];
39655
40162
  if (outPath) {
39656
- writeFileSync31(outPath, JSON.stringify(snapshot, null, 2), "utf8");
40163
+ writeFileSync32(outPath, JSON.stringify(snapshot, null, 2), "utf8");
39657
40164
  console.log(`exported ${snapshot.total} memories to ${outPath}`);
39658
40165
  } else {
39659
40166
  console.log(JSON.stringify(snapshot, null, 2));
@@ -39853,6 +40360,58 @@ async function handleConsolidateCommand({ flags }) {
39853
40360
  }
39854
40361
  return 0;
39855
40362
  }
40363
+ async function handleOptimizeCommand({ flags }) {
40364
+ const ctx = requireRoot(flags);
40365
+ if (!ctx)
40366
+ return 1;
40367
+ const isDryRun = flags["dry-run"] === "true";
40368
+ const force = flags["force"] !== "false";
40369
+ const project = flags["project"];
40370
+ console.log(`
40371
+ ====================================================`);
40372
+ console.log(` ⚡ Muse Memory Optimizer ${isDryRun ? "(DRY-RUN)" : ""}`);
40373
+ console.log(`====================================================`);
40374
+ if (project)
40375
+ console.log(`Scope: Project '${project}'`);
40376
+ console.log(`Store: ${ctx.memoryDir}
40377
+ `);
40378
+ const report = optimizeStore(ctx.store, {
40379
+ project,
40380
+ dryRun: isDryRun,
40381
+ force,
40382
+ memoryDir: ctx.memoryDir
40383
+ });
40384
+ if (report.skippedReason) {
40385
+ console.log(`ℹ️ Optimization skipped: ${report.skippedReason}`);
40386
+ console.log(`Tip: Pass --force to run immediately regardless of cadence.`);
40387
+ return 0;
40388
+ }
40389
+ const formatBytes = (bytes) => {
40390
+ if (bytes >= 1024 * 1024)
40391
+ return `${(bytes / (1024 * 1024)).toFixed(2)} MB`;
40392
+ if (bytes >= 1024)
40393
+ return `${(bytes / 1024).toFixed(1)} KB`;
40394
+ return `${bytes} B`;
40395
+ };
40396
+ console.log(`Results:`);
40397
+ console.log(` - Pruned Test Noise: ${report.prunedNoise} items`);
40398
+ console.log(` - Pruned Junk Fragments: ${report.prunedJunk} items`);
40399
+ console.log(` - Pruned Duplicates: ${report.prunedDuplicates} items`);
40400
+ console.log(` -----------------------------------------`);
40401
+ console.log(` - Total Items Pruned: ${report.totalPruned} items`);
40402
+ console.log(` - Total Before: ${report.totalBefore} items`);
40403
+ console.log(` - Total After: ${report.totalAfter} items`);
40404
+ if (report.spaceReclaimedBytes > 0) {
40405
+ console.log(` - Storage Reclaimed: ${formatBytes(report.spaceReclaimedBytes)}`);
40406
+ }
40407
+ if (report.vacuumExecuted) {
40408
+ console.log(` - SQLite Vacuum: Executed (Defragmented)`);
40409
+ }
40410
+ console.log(` - Duration: ${report.durationMs}ms
40411
+ `);
40412
+ console.log(`✅ Optimization successfully completed.`);
40413
+ return 0;
40414
+ }
39856
40415
  async function handleTraceCommand({ positional, flags }) {
39857
40416
  const ctx = requireRoot(flags);
39858
40417
  if (!ctx)
@@ -40023,6 +40582,7 @@ var init_lifecycle = __esm(() => {
40023
40582
  init_store();
40024
40583
  init_retrieval();
40025
40584
  init_consolidate();
40585
+ init_optimize();
40026
40586
  init_trace();
40027
40587
  init_loops();
40028
40588
  init_nudge();
@@ -40636,9 +41196,9 @@ async function handlePrContextCommand(parsed) {
40636
41196
  });
40637
41197
  const outFile = parsed.flags["out"];
40638
41198
  if (outFile) {
40639
- const { writeFileSync: writeFileSync32 } = await import("node:fs");
41199
+ const { writeFileSync: writeFileSync33 } = await import("node:fs");
40640
41200
  const { resolve: resolve4 } = await import("node:path");
40641
- writeFileSync32(resolve4(root, outFile), result.bodyMarkdown, "utf8");
41201
+ writeFileSync33(resolve4(root, outFile), result.bodyMarkdown, "utf8");
40642
41202
  console.log(`[+] Wrote PR context description to ${outFile}`);
40643
41203
  return 0;
40644
41204
  }
@@ -40658,7 +41218,7 @@ var init_health2 = __esm(() => {
40658
41218
  });
40659
41219
 
40660
41220
  // src/cli/sync.ts
40661
- import { writeFileSync as writeFileSync32, readFileSync as readFileSync49 } from "node:fs";
41221
+ import { writeFileSync as writeFileSync33, readFileSync as readFileSync49 } from "node:fs";
40662
41222
  import { resolve as resolve4 } from "node:path";
40663
41223
  async function handleSyncCommand(parsed) {
40664
41224
  const ctx = requireRoot(parsed.flags);
@@ -40675,7 +41235,7 @@ async function handleSyncCommand(parsed) {
40675
41235
  });
40676
41236
  if (parsed.flags.out) {
40677
41237
  const outPath = resolve4(process.cwd(), parsed.flags.out);
40678
- writeFileSync32(outPath, JSON.stringify(packet2, null, 2), "utf-8");
41238
+ writeFileSync33(outPath, JSON.stringify(packet2, null, 2), "utf-8");
40679
41239
  console.log(`\x1B[32m✓ Broadcast packet saved to '${outPath}' (${packet2.payload.memories.length} memories)\x1B[0m`);
40680
41240
  } else {
40681
41241
  console.log(JSON.stringify(packet2, null, 2));
@@ -41021,6 +41581,8 @@ async function main(argv) {
41021
41581
  return handleStaleCommand(parsed);
41022
41582
  case "consolidate":
41023
41583
  return handleConsolidateCommand(parsed);
41584
+ case "optimize":
41585
+ return handleOptimizeCommand(parsed);
41024
41586
  case "trace":
41025
41587
  return handleTraceCommand(parsed);
41026
41588
  case "loops":
@@ -41103,6 +41665,7 @@ Core Memory Lifecycle Commands:
41103
41665
  stats Display total memory counts and status/type distribution
41104
41666
  stale [--days N] List entries exceeding staleness policy
41105
41667
  consolidate [--project P] [--dry-run] Cluster confirmed memories into scene rollups
41668
+ optimize [--dry-run] [--project P] [--force] Prune test noise, junk, duplicates & vacuum SQLite DB
41106
41669
  trace <id> [--depth N] Walk causal graph pathways from an entry (default depth 5)
41107
41670
  loops Prioritized open-loop report: git state, stale candidates, constraints
41108
41671
  nudge Proactive attention list: overdue/due-soon entries, stale-by-policy, open loops