dotmem 0.0.4 → 0.0.5

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/mcp.js CHANGED
@@ -1,4 +1,4 @@
1
- import { store, hlc, DEV, idb, session, state, dispatch, temporal } from 'memorio';
1
+ import { store as store$1, hlc, DEV, dispatch, idb, session, state, temporal } from 'memorio';
2
2
  import process2 from 'process';
3
3
 
4
4
  var __defProp = Object.defineProperty;
@@ -5057,13 +5057,13 @@ var init_mem_repository = __esm({
5057
5057
  });
5058
5058
  }
5059
5059
  async loadSources(sourceIds) {
5060
- const { readFile: readFile2 } = await nodeFs4();
5060
+ const { readFile: readFile5 } = await nodeFs4();
5061
5061
  const ids = sourceIds ?? await this.discover();
5062
5062
  const sources = [];
5063
5063
  for (const sourceId of ids) {
5064
5064
  const filePath = memFilePath(this.directoryPath, sourceId);
5065
5065
  try {
5066
- const decoded = await parseMemFile(await readFile2(filePath), sourceId);
5066
+ const decoded = await parseMemFile(await readFile5(filePath), sourceId);
5067
5067
  sources.push({
5068
5068
  id: sourceId,
5069
5069
  filePath,
@@ -5147,10 +5147,10 @@ var init_mem_repository = __esm({
5147
5147
  * valid package, so the backup is always a version this library can read.
5148
5148
  */
5149
5149
  async keepLastValidVersion(filePath) {
5150
- const { readFile: readFile2, copyFile, rename, rm } = await nodeFs4();
5150
+ const { readFile: readFile5, copyFile, rename, rm } = await nodeFs4();
5151
5151
  let current;
5152
5152
  try {
5153
- current = await readFile2(filePath);
5153
+ current = await readFile5(filePath);
5154
5154
  } catch {
5155
5155
  return;
5156
5156
  }
@@ -5183,7 +5183,7 @@ var init_mem_repository = __esm({
5183
5183
  }
5184
5184
  }
5185
5185
  async writeSource(filePath, state2, preserved, preservedPackage) {
5186
- const { mkdir, rename, rm, open: open2, readFile: readFile2 } = await nodeFs4();
5186
+ const { mkdir, rename, rm, open: open2, readFile: readFile5 } = await nodeFs4();
5187
5187
  if (!Number.isInteger(state2.version) || state2.version < 0) throw new Error("Invalid writable .mem knowledge version");
5188
5188
  for (const claim2 of state2.claims) validateClaim(claim2);
5189
5189
  await mkdir(parentPath(filePath), { recursive: true });
@@ -5205,7 +5205,7 @@ var init_mem_repository = __esm({
5205
5205
  } finally {
5206
5206
  await handle.close();
5207
5207
  }
5208
- await decodeMemArtifact(await readFile2(temporary));
5208
+ await decodeMemArtifact(await readFile5(temporary));
5209
5209
  await this.keepLastValidVersion(filePath);
5210
5210
  for (let attempt = 0; attempt < 5; attempt++) {
5211
5211
  try {
@@ -5233,8 +5233,8 @@ var init_mem_repository = __esm({
5233
5233
  // core/knowledge/project-anchor.ts
5234
5234
  async function projectAnchorExists(projectId) {
5235
5235
  try {
5236
- const { readFile: readFile2 } = await import('fs/promises');
5237
- await readFile2(resolveUserProjectMemoryPath(projectId));
5236
+ const { readFile: readFile5 } = await import('fs/promises');
5237
+ await readFile5(resolveUserProjectMemoryPath(projectId));
5238
5238
  return true;
5239
5239
  } catch {
5240
5240
  return false;
@@ -5270,7 +5270,7 @@ var init_project_anchor = __esm({
5270
5270
  var configureUserIdentityStore;
5271
5271
  var init_user_identity = __esm({
5272
5272
  "core/knowledge/user-identity.ts"() {
5273
- configureUserIdentityStore = /* @__PURE__ */ __name((store5) => {
5273
+ configureUserIdentityStore = /* @__PURE__ */ __name((store6) => {
5274
5274
  }, "configureUserIdentityStore");
5275
5275
  }
5276
5276
  });
@@ -5874,9 +5874,155 @@ var init_staging = __esm({
5874
5874
  });
5875
5875
 
5876
5876
  // core/knowledge/loops.ts
5877
+ function joinPath3(base, child) {
5878
+ const separator3 = process.platform === "win32" ? "\\" : "/";
5879
+ return `${base.replace(/[\\/]+/g, separator3)}${separator3}${child}`;
5880
+ }
5881
+ function resolveLoopsFilePath() {
5882
+ return joinPath3(resolveUserDotMemPath(), LOOPS_FILE_NAME);
5883
+ }
5884
+ async function readFile(path) {
5885
+ try {
5886
+ const fs = await import('fs/promises');
5887
+ return await fs.readFile(path, "utf8");
5888
+ } catch {
5889
+ return null;
5890
+ }
5891
+ }
5892
+ async function writeFile(path, content) {
5893
+ const fs = await import('fs/promises');
5894
+ const dir = path.replace(/[\\/][^\\/]+$/, "");
5895
+ await fs.mkdir(dir, { recursive: true });
5896
+ const temporary = `${path}.${process.pid}.${Date.now().toString(36)}.tmp`;
5897
+ try {
5898
+ await fs.writeFile(temporary, content, "utf8");
5899
+ await fs.rename(temporary, path);
5900
+ } catch {
5901
+ await fs.rm(temporary, { force: true }).catch(() => void 0);
5902
+ throw new Error(`Failed to write loops file at ${path}`);
5903
+ }
5904
+ }
5905
+ function emptyDocument() {
5906
+ return { version: LOOPS_FORMAT_VERSION, loops: {} };
5907
+ }
5908
+ function validateDocument(value) {
5909
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
5910
+ throw new Error("Loops document must be an object");
5911
+ }
5912
+ const document = value;
5913
+ if (document.version !== LOOPS_FORMAT_VERSION) {
5914
+ throw new Error(`Unsupported loops document version: ${String(document.version)}`);
5915
+ }
5916
+ if (!document.loops || typeof document.loops !== "object" || Array.isArray(document.loops)) {
5917
+ throw new Error("Loops document loops must be an object");
5918
+ }
5919
+ const loops = {};
5920
+ for (const [id, loopValue] of Object.entries(document.loops)) {
5921
+ const loop = validateLoop(loopValue, id);
5922
+ loops[loop.id] = loop;
5923
+ }
5924
+ return { version: LOOPS_FORMAT_VERSION, loops };
5925
+ }
5926
+ function validateLoop(value, id) {
5927
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
5928
+ throw new Error(`Loop ${id} must be an object`);
5929
+ }
5930
+ const loop = value;
5931
+ if (typeof loop.id !== "string" || !loop.id) {
5932
+ throw new Error(`Loop ${id} requires an id`);
5933
+ }
5934
+ if (typeof loop.text !== "string" || !loop.text) {
5935
+ throw new Error(`Loop ${id} requires non-empty text`);
5936
+ }
5937
+ if (typeof loop.waitor !== "string" || !loop.waitor) {
5938
+ throw new Error(`Loop ${id} requires a waitor`);
5939
+ }
5940
+ if (typeof loop.openedAt !== "string" || !loop.openedAt) {
5941
+ throw new Error(`Loop ${id} requires an openedAt timestamp`);
5942
+ }
5943
+ const result = {
5944
+ id: loop.id,
5945
+ text: loop.text,
5946
+ waitor: loop.waitor,
5947
+ openedAt: loop.openedAt
5948
+ };
5949
+ if (typeof loop.closedAt === "string") result.closedAt = loop.closedAt;
5950
+ if (typeof loop.closedBy === "string") result.closedBy = loop.closedBy;
5951
+ if (typeof loop.closeNote === "string") result.closeNote = loop.closeNote;
5952
+ return result;
5953
+ }
5954
+ async function loadLoops() {
5955
+ const raw = await readFile(resolveLoopsFilePath());
5956
+ if (!raw) return emptyDocument();
5957
+ try {
5958
+ return validateDocument(JSON.parse(raw));
5959
+ } catch {
5960
+ return emptyDocument();
5961
+ }
5962
+ }
5963
+ async function saveLoops(document) {
5964
+ await writeFile(resolveLoopsFilePath(), JSON.stringify(document, null, 2) + "\n");
5965
+ }
5966
+ async function addLoop(input2) {
5967
+ const document = await loadLoops();
5968
+ if (document.loops[input2.id]) {
5969
+ throw new Error(`Loop ${input2.id} already exists`);
5970
+ }
5971
+ const loop = {
5972
+ id: input2.id,
5973
+ text: input2.text,
5974
+ waitor: input2.waitor,
5975
+ openedAt: input2.openedAt ?? (/* @__PURE__ */ new Date()).toISOString()
5976
+ };
5977
+ document.loops[loop.id] = loop;
5978
+ await saveLoops(document);
5979
+ return loop;
5980
+ }
5981
+ async function listLoops(openOnly = true) {
5982
+ const document = await loadLoops();
5983
+ const all = Object.values(document.loops);
5984
+ if (openOnly) {
5985
+ return all.filter((loop) => loop.closedAt === void 0);
5986
+ }
5987
+ return all;
5988
+ }
5989
+ async function closeLoop(id, input2) {
5990
+ const document = await loadLoops();
5991
+ const existing = document.loops[id];
5992
+ if (!existing) {
5993
+ throw new Error(`Loop ${id} not found`);
5994
+ }
5995
+ if (existing.closedAt) {
5996
+ throw new Error(`Loop ${id} is already closed`);
5997
+ }
5998
+ const closed = {
5999
+ ...existing,
6000
+ closedAt: input2.closedAt ?? (/* @__PURE__ */ new Date()).toISOString(),
6001
+ closedBy: input2.by,
6002
+ ...input2.note ? { closeNote: input2.note } : {}
6003
+ };
6004
+ document.loops[id] = closed;
6005
+ await saveLoops(document);
6006
+ return closed;
6007
+ }
6008
+ var LOOPS_FILE_NAME, LOOPS_FORMAT_VERSION;
5877
6009
  var init_loops = __esm({
5878
6010
  "core/knowledge/loops.ts"() {
5879
6011
  init_user_paths();
6012
+ LOOPS_FILE_NAME = "loops.json";
6013
+ LOOPS_FORMAT_VERSION = 1;
6014
+ __name(joinPath3, "joinPath");
6015
+ __name(resolveLoopsFilePath, "resolveLoopsFilePath");
6016
+ __name(readFile, "readFile");
6017
+ __name(writeFile, "writeFile");
6018
+ __name(emptyDocument, "emptyDocument");
6019
+ __name(validateDocument, "validateDocument");
6020
+ __name(validateLoop, "validateLoop");
6021
+ __name(loadLoops, "loadLoops");
6022
+ __name(saveLoops, "saveLoops");
6023
+ __name(addLoop, "addLoop");
6024
+ __name(listLoops, "listLoops");
6025
+ __name(closeLoop, "closeLoop");
5880
6026
  }
5881
6027
  });
5882
6028
 
@@ -6005,14 +6151,14 @@ var init_violations = __esm({
6005
6151
  });
6006
6152
 
6007
6153
  // core/knowledge/session.ts
6008
- function joinPath3(base, child) {
6154
+ function joinPath4(base, child) {
6009
6155
  const separator3 = process.platform === "win32" ? "\\" : "/";
6010
6156
  return `${base.replace(/[\\/]+/g, separator3)}${separator3}${child}`;
6011
6157
  }
6012
6158
  function resolveSessionFilePath() {
6013
- return joinPath3(resolveUserDotMemPath(), SESSION_FILE_NAME);
6159
+ return joinPath4(resolveUserDotMemPath(), SESSION_FILE_NAME);
6014
6160
  }
6015
- async function readFile(path) {
6161
+ async function readFile2(path) {
6016
6162
  try {
6017
6163
  const fs = await import('fs/promises');
6018
6164
  return await fs.readFile(path, "utf8");
@@ -6021,7 +6167,7 @@ async function readFile(path) {
6021
6167
  }
6022
6168
  }
6023
6169
  async function loadSession() {
6024
- const raw = await readFile(resolveSessionFilePath());
6170
+ const raw = await readFile2(resolveSessionFilePath());
6025
6171
  if (!raw) return { ...DEFAULT_SESSION };
6026
6172
  try {
6027
6173
  const parsed = JSON.parse(raw);
@@ -6043,9 +6189,9 @@ var init_session = __esm({
6043
6189
  "core/knowledge/session.ts"() {
6044
6190
  init_user_paths();
6045
6191
  SESSION_FILE_NAME = "session.json";
6046
- __name(joinPath3, "joinPath");
6192
+ __name(joinPath4, "joinPath");
6047
6193
  __name(resolveSessionFilePath, "resolveSessionFilePath");
6048
- __name(readFile, "readFile");
6194
+ __name(readFile2, "readFile");
6049
6195
  DEFAULT_SESSION = {
6050
6196
  doing: "",
6051
6197
  changedFiles: [],
@@ -6058,16 +6204,368 @@ var init_session = __esm({
6058
6204
  });
6059
6205
 
6060
6206
  // core/knowledge/exemplars.ts
6207
+ function joinPath5(base, child) {
6208
+ const separator3 = process.platform === "win32" ? "\\" : "/";
6209
+ return `${base.replace(/[\\/]+/g, separator3)}${separator3}${child}`;
6210
+ }
6211
+ function resolveExemplarsPath() {
6212
+ return joinPath5(resolveUserDotMemPath(), EXEMPLARS_FILE_NAME);
6213
+ }
6214
+ async function readFile3(path) {
6215
+ try {
6216
+ const fs = await import('fs/promises');
6217
+ return await fs.readFile(path, "utf8");
6218
+ } catch {
6219
+ return null;
6220
+ }
6221
+ }
6222
+ async function writeFile2(path, content) {
6223
+ const fs = await import('fs/promises');
6224
+ const dir = path.replace(/[\\/][^\\/]+$/, "");
6225
+ await fs.mkdir(dir, { recursive: true });
6226
+ const temporary = `${path}.${process.pid}.${Date.now().toString(36)}.tmp`;
6227
+ try {
6228
+ await fs.writeFile(temporary, content, "utf8");
6229
+ await fs.rename(temporary, path);
6230
+ } catch {
6231
+ await fs.rm(temporary, { force: true }).catch(() => void 0);
6232
+ throw new Error(`Failed to write exemplars file at ${path}`);
6233
+ }
6234
+ }
6235
+ function emptyStore() {
6236
+ return { version: EXEMPLARS_FORMAT_VERSION, exemplars: {} };
6237
+ }
6238
+ function validateExemplar(value) {
6239
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
6240
+ throw new Error("Exemplar must be an object");
6241
+ }
6242
+ const e = value;
6243
+ if (typeof e.id !== "string" || !e.id) throw new Error("Exemplar requires non-empty id");
6244
+ if (typeof e.pattern !== "string" || !e.pattern) {
6245
+ throw new Error(`Exemplar ${e.id} requires non-empty pattern`);
6246
+ }
6247
+ const source = e.source ?? {};
6248
+ if (typeof source.conversationId !== "string" || !source.conversationId) {
6249
+ throw new Error(`Exemplar ${e.id} requires source.conversationId`);
6250
+ }
6251
+ const now2 = (/* @__PURE__ */ new Date()).toISOString();
6252
+ return {
6253
+ id: e.id,
6254
+ type: "interaction-exemplar",
6255
+ source: {
6256
+ conversationId: source.conversationId,
6257
+ messageIds: Array.isArray(source.messageIds) ? source.messageIds.map(String) : [],
6258
+ ...typeof source.timestamp === "string" ? { timestamp: source.timestamp } : {}
6259
+ },
6260
+ pattern: e.pattern,
6261
+ originalContent: typeof e.originalContent === "string" ? e.originalContent : null,
6262
+ sourceReference: typeof e.sourceReference === "string" ? e.sourceReference : null,
6263
+ retrievalHints: Array.isArray(e.retrievalHints) ? e.retrievalHints.map(String) : [],
6264
+ significance: typeof e.significance === "number" && e.significance >= 0 ? e.significance : 0,
6265
+ confidence: typeof e.confidence === "number" && e.confidence >= 0 && e.confidence <= 1 ? e.confidence : 0,
6266
+ provenance: ["human-stated", "observed", "inferred"].includes(
6267
+ e.provenance
6268
+ ) ? e.provenance : "observed",
6269
+ createdAt: typeof e.createdAt === "string" ? e.createdAt : now2,
6270
+ revision: typeof e.revision === "number" && e.revision > 0 ? e.revision : 1
6271
+ };
6272
+ }
6273
+ function validateStore(value) {
6274
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
6275
+ throw new Error("Exemplars document must be an object");
6276
+ }
6277
+ const doc = value;
6278
+ if (doc.version !== EXEMPLARS_FORMAT_VERSION) {
6279
+ throw new Error(`Unsupported exemplars version: ${String(doc.version)}`);
6280
+ }
6281
+ const exemplars = {};
6282
+ if (doc.exemplars && typeof doc.exemplars === "object" && !Array.isArray(doc.exemplars)) {
6283
+ for (const [_, exemplarValue] of Object.entries(doc.exemplars)) {
6284
+ const exemplar = validateExemplar(exemplarValue);
6285
+ exemplars[exemplar.id] = exemplar;
6286
+ }
6287
+ }
6288
+ return { version: EXEMPLARS_FORMAT_VERSION, exemplars };
6289
+ }
6290
+ async function loadExemplars() {
6291
+ const raw = await readFile3(resolveExemplarsPath());
6292
+ if (raw === null) return emptyStore();
6293
+ try {
6294
+ return validateStore(JSON.parse(raw));
6295
+ } catch {
6296
+ return emptyStore();
6297
+ }
6298
+ }
6299
+ async function saveExemplars(store6) {
6300
+ const validated = validateStore(store6);
6301
+ await writeFile2(resolveExemplarsPath(), JSON.stringify(validated, null, 2));
6302
+ }
6303
+ async function addExemplar(exemplar) {
6304
+ const store6 = await loadExemplars();
6305
+ if (store6.exemplars[exemplar.id]) {
6306
+ throw new Error(`Exemplar ${exemplar.id} already exists`);
6307
+ }
6308
+ if (exemplar.sourceReference) {
6309
+ const existingRef = Object.values(store6.exemplars).find(
6310
+ (e) => e.sourceReference === exemplar.sourceReference
6311
+ );
6312
+ if (existingRef) {
6313
+ throw new Error(`Exemplar with source reference ${exemplar.sourceReference} already exists (id: ${existingRef.id})`);
6314
+ }
6315
+ }
6316
+ const full = {
6317
+ ...exemplar,
6318
+ type: "interaction-exemplar",
6319
+ revision: 1
6320
+ };
6321
+ store6.exemplars[exemplar.id] = full;
6322
+ await saveExemplars(store6);
6323
+ return full;
6324
+ }
6325
+ async function updateExemplar(id, updates) {
6326
+ const store6 = await loadExemplars();
6327
+ const existing = store6.exemplars[id];
6328
+ if (!existing) {
6329
+ throw new Error(`Exemplar ${id} not found`);
6330
+ }
6331
+ const updated = {
6332
+ ...existing,
6333
+ ...updates,
6334
+ id: existing.id,
6335
+ type: "interaction-exemplar",
6336
+ createdAt: existing.createdAt,
6337
+ revision: (updates.revision ?? existing.revision) + 1
6338
+ };
6339
+ store6.exemplars[id] = updated;
6340
+ await saveExemplars(store6);
6341
+ return updated;
6342
+ }
6343
+ var EXEMPLARS_FILE_NAME, EXEMPLARS_FORMAT_VERSION;
6061
6344
  var init_exemplars = __esm({
6062
6345
  "core/knowledge/exemplars.ts"() {
6063
6346
  init_user_paths();
6347
+ EXEMPLARS_FILE_NAME = "exemplars.json";
6348
+ EXEMPLARS_FORMAT_VERSION = 1;
6349
+ __name(joinPath5, "joinPath");
6350
+ __name(resolveExemplarsPath, "resolveExemplarsPath");
6351
+ __name(readFile3, "readFile");
6352
+ __name(writeFile2, "writeFile");
6353
+ __name(emptyStore, "emptyStore");
6354
+ __name(validateExemplar, "validateExemplar");
6355
+ __name(validateStore, "validateStore");
6356
+ __name(loadExemplars, "loadExemplars");
6357
+ __name(saveExemplars, "saveExemplars");
6358
+ __name(addExemplar, "addExemplar");
6359
+ __name(updateExemplar, "updateExemplar");
6064
6360
  }
6065
6361
  });
6066
6362
 
6067
6363
  // core/knowledge/personality-anchor.ts
6364
+ function joinPath6(base, child) {
6365
+ const separator3 = process.platform === "win32" ? "\\" : "/";
6366
+ return `${base.replace(/[\\/]+/g, separator3)}${separator3}${child}`;
6367
+ }
6368
+ function resolvePersonalityAnchorPath() {
6369
+ return joinPath6(resolveUserDotMemPath(), PERSONALITY_ANCHOR_FILE_NAME);
6370
+ }
6371
+ async function readFile4(path) {
6372
+ try {
6373
+ const fs = await import('fs/promises');
6374
+ return await fs.readFile(path, "utf8");
6375
+ } catch {
6376
+ return null;
6377
+ }
6378
+ }
6379
+ async function writeFile3(path, content) {
6380
+ const fs = await import('fs/promises');
6381
+ const dir = path.replace(/[\\/][^\\/]+$/, "");
6382
+ await fs.mkdir(dir, { recursive: true });
6383
+ const temporary = `${path}.${process.pid}.${Date.now().toString(36)}.tmp`;
6384
+ try {
6385
+ await fs.writeFile(temporary, content, "utf8");
6386
+ await fs.rename(temporary, path);
6387
+ } catch {
6388
+ await fs.rm(temporary, { force: true }).catch(() => void 0);
6389
+ throw new Error(`Failed to write personality anchor at ${path}`);
6390
+ }
6391
+ }
6392
+ function emptyAnchor() {
6393
+ const epoch = "1970-01-01T00:00:00.000Z";
6394
+ return {
6395
+ version: PERSONALITY_ANCHOR_FORMAT_VERSION,
6396
+ identity: {
6397
+ communicationStyle: [],
6398
+ durablePreferences: [],
6399
+ interactionBoundaries: []
6400
+ },
6401
+ metadata: {
6402
+ createdAt: epoch,
6403
+ updatedAt: epoch,
6404
+ revision: 1,
6405
+ sourceReferences: []
6406
+ }
6407
+ };
6408
+ }
6409
+ function validateCommunicationStyle(value) {
6410
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
6411
+ throw new Error("communicationStyle entry must be an object");
6412
+ }
6413
+ const style = value;
6414
+ if (typeof style.description !== "string" || !style.description) {
6415
+ throw new Error("communicationStyle entry requires non-empty description");
6416
+ }
6417
+ const confidence = style.confidence ?? "inferred";
6418
+ if (!["inferred", "observed", "human-stated"].includes(confidence)) {
6419
+ throw new Error(`Invalid confidence value: ${String(style.confidence)}`);
6420
+ }
6421
+ const evidence = Array.isArray(style.evidence) ? style.evidence.map(String) : [];
6422
+ return {
6423
+ description: style.description,
6424
+ confidence,
6425
+ evidence,
6426
+ lastObserved: typeof style.lastObserved === "string" ? style.lastObserved : (/* @__PURE__ */ new Date()).toISOString()
6427
+ };
6428
+ }
6429
+ function validateDurablePreference(value) {
6430
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
6431
+ throw new Error("durablePreference entry must be an object");
6432
+ }
6433
+ const pref = value;
6434
+ if (typeof pref.id !== "string" || !pref.id) {
6435
+ throw new Error("durablePreference entry requires non-empty id");
6436
+ }
6437
+ if (typeof pref.statement !== "string" || !pref.statement) {
6438
+ throw new Error(`durablePreference ${pref.id} requires non-empty statement`);
6439
+ }
6440
+ const confidence = pref.confidence ?? "inferred";
6441
+ if (!["inferred", "observed", "human-stated"].includes(confidence)) {
6442
+ throw new Error(`Invalid confidence value: ${String(pref.confidence)}`);
6443
+ }
6444
+ const evidence = Array.isArray(pref.evidence) ? pref.evidence.map(String) : [];
6445
+ const now2 = (/* @__PURE__ */ new Date()).toISOString();
6446
+ return {
6447
+ id: pref.id,
6448
+ statement: pref.statement,
6449
+ confidence,
6450
+ evidence,
6451
+ firstObserved: typeof pref.firstObserved === "string" ? pref.firstObserved : now2,
6452
+ lastConfirmed: typeof pref.lastConfirmed === "string" ? pref.lastConfirmed : now2,
6453
+ ...typeof pref.supersededBy === "string" ? { supersededBy: pref.supersededBy } : {}
6454
+ };
6455
+ }
6456
+ function validateInteractionBoundary(value) {
6457
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
6458
+ throw new Error("interactionBoundary entry must be an object");
6459
+ }
6460
+ const boundary = value;
6461
+ if (typeof boundary.id !== "string" || !boundary.id) {
6462
+ throw new Error("interactionBoundary entry requires non-empty id");
6463
+ }
6464
+ if (typeof boundary.rule !== "string" || !boundary.rule) {
6465
+ throw new Error(`interactionBoundary ${boundary.id} requires non-empty rule`);
6466
+ }
6467
+ const confidence = boundary.confidence ?? "inferred";
6468
+ if (!["inferred", "observed", "human-stated"].includes(confidence)) {
6469
+ throw new Error(`Invalid confidence value: ${String(boundary.confidence)}`);
6470
+ }
6471
+ const evidence = Array.isArray(boundary.evidence) ? boundary.evidence.map(String) : [];
6472
+ const source = boundary.source ?? "conversation";
6473
+ if (!["profile", "memory", "conversation"].includes(source)) {
6474
+ throw new Error(`Invalid boundary source: ${String(boundary.source)}`);
6475
+ }
6476
+ return {
6477
+ id: boundary.id,
6478
+ rule: boundary.rule,
6479
+ confidence,
6480
+ evidence,
6481
+ source,
6482
+ lastConfirmed: typeof boundary.lastConfirmed === "string" ? boundary.lastConfirmed : (/* @__PURE__ */ new Date()).toISOString()
6483
+ };
6484
+ }
6485
+ function validateAnchor(value) {
6486
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
6487
+ throw new Error("Personality anchor document must be an object");
6488
+ }
6489
+ const doc = value;
6490
+ if (doc.version !== PERSONALITY_ANCHOR_FORMAT_VERSION) {
6491
+ throw new Error(`Unsupported personality anchor version: ${String(doc.version)}`);
6492
+ }
6493
+ const identity = doc.identity ?? {};
6494
+ const metadata = doc.metadata ?? {};
6495
+ const communicationStyle = Array.isArray(identity.communicationStyle) ? identity.communicationStyle.map(validateCommunicationStyle) : [];
6496
+ const durablePreferences = Array.isArray(identity.durablePreferences) ? identity.durablePreferences.map(validateDurablePreference) : [];
6497
+ const interactionBoundaries = Array.isArray(identity.interactionBoundaries) ? identity.interactionBoundaries.map(validateInteractionBoundary) : [];
6498
+ const sourceRefs = Array.isArray(metadata.sourceReferences) ? metadata.sourceReferences.map(String) : [];
6499
+ return {
6500
+ version: PERSONALITY_ANCHOR_FORMAT_VERSION,
6501
+ identity: {
6502
+ communicationStyle,
6503
+ durablePreferences,
6504
+ interactionBoundaries
6505
+ },
6506
+ metadata: {
6507
+ createdAt: typeof metadata.createdAt === "string" ? metadata.createdAt : (/* @__PURE__ */ new Date()).toISOString(),
6508
+ updatedAt: typeof metadata.updatedAt === "string" ? metadata.updatedAt : (/* @__PURE__ */ new Date()).toISOString(),
6509
+ revision: typeof metadata.revision === "number" && metadata.revision > 0 ? metadata.revision : 1,
6510
+ sourceReferences: sourceRefs
6511
+ }
6512
+ };
6513
+ }
6514
+ async function loadPersonalityAnchor() {
6515
+ const raw = await readFile4(resolvePersonalityAnchorPath());
6516
+ if (raw === null) return emptyAnchor();
6517
+ try {
6518
+ const parsed = JSON.parse(raw);
6519
+ return validateAnchor(parsed);
6520
+ } catch {
6521
+ return emptyAnchor();
6522
+ }
6523
+ }
6524
+ async function savePersonalityAnchor(anchor2) {
6525
+ const validated = validateAnchor(anchor2);
6526
+ const dirPath = resolveUserDotMemPath();
6527
+ const fs = await import('fs/promises');
6528
+ await fs.mkdir(dirPath, { recursive: true });
6529
+ await writeFile3(resolvePersonalityAnchorPath(), JSON.stringify(validated, null, 2));
6530
+ }
6531
+ async function updatePersonalityAnchor(updates) {
6532
+ const existing = await loadPersonalityAnchor();
6533
+ const now2 = (/* @__PURE__ */ new Date()).toISOString();
6534
+ const updated = {
6535
+ ...existing,
6536
+ identity: {
6537
+ communicationStyle: updates.communicationStyle ?? existing.identity.communicationStyle,
6538
+ durablePreferences: updates.durablePreferences ?? existing.identity.durablePreferences,
6539
+ interactionBoundaries: updates.interactionBoundaries ?? existing.identity.interactionBoundaries
6540
+ },
6541
+ metadata: {
6542
+ ...existing.metadata,
6543
+ updatedAt: now2,
6544
+ revision: existing.metadata.revision + 1,
6545
+ sourceReferences: updates.sourceReferences ? [.../* @__PURE__ */ new Set([...existing.metadata.sourceReferences, ...updates.sourceReferences])] : existing.metadata.sourceReferences
6546
+ }
6547
+ };
6548
+ await savePersonalityAnchor(updated);
6549
+ return updated;
6550
+ }
6551
+ var PERSONALITY_ANCHOR_FILE_NAME, PERSONALITY_ANCHOR_FORMAT_VERSION;
6068
6552
  var init_personality_anchor = __esm({
6069
6553
  "core/knowledge/personality-anchor.ts"() {
6070
6554
  init_user_paths();
6555
+ PERSONALITY_ANCHOR_FILE_NAME = "personality-anchor.json";
6556
+ PERSONALITY_ANCHOR_FORMAT_VERSION = 1;
6557
+ __name(joinPath6, "joinPath");
6558
+ __name(resolvePersonalityAnchorPath, "resolvePersonalityAnchorPath");
6559
+ __name(readFile4, "readFile");
6560
+ __name(writeFile3, "writeFile");
6561
+ __name(emptyAnchor, "emptyAnchor");
6562
+ __name(validateCommunicationStyle, "validateCommunicationStyle");
6563
+ __name(validateDurablePreference, "validateDurablePreference");
6564
+ __name(validateInteractionBoundary, "validateInteractionBoundary");
6565
+ __name(validateAnchor, "validateAnchor");
6566
+ __name(loadPersonalityAnchor, "loadPersonalityAnchor");
6567
+ __name(savePersonalityAnchor, "savePersonalityAnchor");
6568
+ __name(updatePersonalityAnchor, "updatePersonalityAnchor");
6071
6569
  }
6072
6570
  });
6073
6571
 
@@ -42218,7 +42716,7 @@ var StdioServerTransport = class {
42218
42716
 
42219
42717
  // package.json
42220
42718
  var package_default = {
42221
- version: "0.0.4"};
42719
+ version: "0.0.5"};
42222
42720
  var g = globalThis;
42223
42721
  function namespace() {
42224
42722
  const cfg = g.dotmemSyncConfig;
@@ -42257,19 +42755,19 @@ var journal = {
42257
42755
  hlc: entry.hlc || hlc.serialize(hlc.tick())
42258
42756
  };
42259
42757
  const key = `${STORE_PREFIX(ns)}${row.id}`;
42260
- store.set(key, row);
42261
- const idx = store.get(INDEX_KEY(ns)) || [];
42758
+ store$1.set(key, row);
42759
+ const idx = store$1.get(INDEX_KEY(ns)) || [];
42262
42760
  if (!idx.includes(row.id)) idx.push(row.id);
42263
- store.set(INDEX_KEY(ns), idx);
42761
+ store$1.set(INDEX_KEY(ns), idx);
42264
42762
  return row;
42265
42763
  },
42266
42764
  /** All pending (not-yet-synced) entries for the current namespace. */
42267
42765
  async pending() {
42268
42766
  const ns = namespace();
42269
42767
  const out = [];
42270
- const idx = store.get(INDEX_KEY(ns)) || [];
42768
+ const idx = store$1.get(INDEX_KEY(ns)) || [];
42271
42769
  for (const id of idx) {
42272
- const raw = store.get(`${STORE_PREFIX(ns)}${id}`);
42770
+ const raw = store$1.get(`${STORE_PREFIX(ns)}${id}`);
42273
42771
  if (!raw) continue;
42274
42772
  const e = parseEntry(raw);
42275
42773
  if (e && e.sync !== "synced") out.push(e);
@@ -42292,31 +42790,31 @@ var journal = {
42292
42790
  if (!ids.length) return 0;
42293
42791
  const ns = namespace();
42294
42792
  let count = 0;
42295
- const idx = store.get(INDEX_KEY(ns)) || [];
42793
+ const idx = store$1.get(INDEX_KEY(ns)) || [];
42296
42794
  for (const id of idx) {
42297
42795
  if (!ids.includes(id)) continue;
42298
42796
  const key = `${STORE_PREFIX(ns)}${id}`;
42299
- const raw = store.get(key);
42797
+ const raw = store$1.get(key);
42300
42798
  if (!raw) continue;
42301
42799
  const e = parseEntry(raw);
42302
42800
  if (!e || e.sync === "synced") continue;
42303
42801
  e.sync = "synced";
42304
- store.set(key, e);
42802
+ store$1.set(key, e);
42305
42803
  count++;
42306
42804
  }
42307
42805
  return count;
42308
42806
  },
42309
42807
  async get(id) {
42310
42808
  const ns = namespace();
42311
- const raw = store.get(`${STORE_PREFIX(ns)}${id}`);
42809
+ const raw = store$1.get(`${STORE_PREFIX(ns)}${id}`);
42312
42810
  return parseEntry(raw ?? "");
42313
42811
  },
42314
42812
  /** Remove all journal rows for the current namespace. */
42315
42813
  async clear() {
42316
42814
  const ns = namespace();
42317
- const idx = store.get(INDEX_KEY(ns)) || [];
42318
- for (const id of idx) store.remove(`${STORE_PREFIX(ns)}${id}`);
42319
- store.remove(INDEX_KEY(ns));
42815
+ const idx = store$1.get(INDEX_KEY(ns)) || [];
42816
+ for (const id of idx) store$1.remove(`${STORE_PREFIX(ns)}${id}`);
42817
+ store$1.remove(INDEX_KEY(ns));
42320
42818
  },
42321
42819
  /**
42322
42820
  * Reconcile the local journal against the configured provider. Pushes pending
@@ -42395,7 +42893,7 @@ var journal = {
42395
42893
  */
42396
42894
  async status() {
42397
42895
  try {
42398
- const capabilities = store.capabilities?.();
42896
+ const capabilities = store$1.capabilities?.();
42399
42897
  return capabilities?.persistent ? "store" : "memory";
42400
42898
  } catch {
42401
42899
  return "memory";
@@ -42456,7 +42954,7 @@ var StoreKnowledgeRepository = class {
42456
42954
  __name(this, "StoreKnowledgeRepository");
42457
42955
  }
42458
42956
  async load() {
42459
- const raw = store.get(KNOWLEDGE_STATE_KEY);
42957
+ const raw = store$1.get(KNOWLEDGE_STATE_KEY);
42460
42958
  if (!raw) return { version: 0, claims: [] };
42461
42959
  return typeof raw === "string" ? JSON.parse(raw) : raw;
42462
42960
  }
@@ -42466,7 +42964,7 @@ var StoreKnowledgeRepository = class {
42466
42964
  if (current.version !== expectedVersion) {
42467
42965
  throw new Error(`Stale update: expected persisted version ${expectedVersion}, received ${current.version}`);
42468
42966
  }
42469
- store.set(KNOWLEDGE_STATE_KEY, state2);
42967
+ store$1.set(KNOWLEDGE_STATE_KEY, state2);
42470
42968
  }, "write");
42471
42969
  const previous = knowledgeSaveQueue;
42472
42970
  knowledgeSaveQueue = previous.then(write, write);
@@ -42717,27 +43215,27 @@ var auditPolicyAction = /* @__PURE__ */ __name((action, key) => {
42717
43215
  }
42718
43216
  }, "auditPolicyAction");
42719
43217
  var resolveOverrides = /* @__PURE__ */ __name(async (namespace2, now2 = () => /* @__PURE__ */ new Date()) => {
42720
- const store5 = await getPolicyStore();
43218
+ const store6 = await getPolicyStore();
42721
43219
  const namespaces = namespace2 ? [namespace2] : POLICY_NAMESPACES;
42722
- const documents = await Promise.all(namespaces.map((entry) => store5.load(entry)));
43220
+ const documents = await Promise.all(namespaces.map((entry) => store6.load(entry)));
42723
43221
  return documents.flatMap((document) => document.overrides.map(
42724
43222
  (override) => resolveOverrideState(override, document.records.find((record2) => record2.id === override.targetPolicyId), now2)
42725
43223
  )).sort((left, right) => left.override.id.localeCompare(right.override.id));
42726
43224
  }, "resolveOverrides");
42727
43225
  var policy = {
42728
43226
  async assign(input2, namespace2 = "operator", basedOnRevision) {
42729
- const store5 = await getPolicyStore();
42730
- const record2 = await store5.assign(input2, namespace2, basedOnRevision);
43227
+ const store6 = await getPolicyStore();
43228
+ const record2 = await store6.assign(input2, namespace2, basedOnRevision);
42731
43229
  auditPolicyAction("policy.assign", record2.id);
42732
43230
  return record2;
42733
43231
  },
42734
43232
  async list() {
42735
- const store5 = await getPolicyStore();
42736
- return store5.list();
43233
+ const store6 = await getPolicyStore();
43234
+ return store6.list();
42737
43235
  },
42738
43236
  async remove(id, namespace2 = "operator", basedOnRevision) {
42739
- const store5 = await getPolicyStore();
42740
- await store5.remove(id, namespace2, basedOnRevision);
43237
+ const store6 = await getPolicyStore();
43238
+ await store6.remove(id, namespace2, basedOnRevision);
42741
43239
  auditPolicyAction("policy.remove", id);
42742
43240
  },
42743
43241
  /**
@@ -42751,16 +43249,16 @@ var policy = {
42751
43249
  * the durable audit trail with a terminal CLEAR entry.
42752
43250
  */
42753
43251
  async clear(authority) {
42754
- const store5 = await getPolicyStore();
42755
- await store5.clear(authority);
43252
+ const store6 = await getPolicyStore();
43253
+ await store6.clear(authority);
42756
43254
  auditPolicyAction("policy.clear", "policy");
42757
43255
  },
42758
43256
  async evaluate(event, payload) {
42759
- const store5 = await getPolicyStore();
43257
+ const store6 = await getPolicyStore();
42760
43258
  const [state2, policies, overrides] = await Promise.all([
42761
43259
  loadCombinedKnowledgeState(),
42762
- store5.list(),
42763
- store5.listOverrides()
43260
+ store6.list(),
43261
+ store6.listOverrides()
42764
43262
  ]);
42765
43263
  const claims = activeClaims(state2);
42766
43264
  return evaluatePolicies({ event, claims, policies, overrides, payload });
@@ -42782,14 +43280,14 @@ var policy = {
42782
43280
  */
42783
43281
  override: {
42784
43282
  async grant(input2, namespace2 = "operator", basedOnRevision) {
42785
- const store5 = await getPolicyStore();
42786
- const override = await store5.grantOverride(input2, namespace2, basedOnRevision);
43283
+ const store6 = await getPolicyStore();
43284
+ const override = await store6.grantOverride(input2, namespace2, basedOnRevision);
42787
43285
  auditPolicyAction("policy.override", override.id);
42788
43286
  return override;
42789
43287
  },
42790
43288
  async revoke(input2, namespace2 = "operator", basedOnRevision) {
42791
- const store5 = await getPolicyStore();
42792
- const override = await store5.revokeOverride(input2, namespace2, basedOnRevision);
43289
+ const store6 = await getPolicyStore();
43290
+ const override = await store6.revokeOverride(input2, namespace2, basedOnRevision);
42793
43291
  auditPolicyAction("policy.revoke", override.id);
42794
43292
  return override;
42795
43293
  },
@@ -42797,8 +43295,8 @@ var policy = {
42797
43295
  return resolveOverrides(namespace2);
42798
43296
  },
42799
43297
  async effective(event, namespace2) {
42800
- const store5 = await getPolicyStore();
42801
- const states = await store5.effectiveState(namespace2);
43298
+ const store6 = await getPolicyStore();
43299
+ const states = await store6.effectiveState(namespace2);
42802
43300
  if (event === void 0) return states;
42803
43301
  const canonical = event.trim();
42804
43302
  return states.filter((state2) => state2.event === canonical);
@@ -42811,8 +43309,8 @@ var policy = {
42811
43309
  * additional best-effort sink, and this is the durable record.
42812
43310
  */
42813
43311
  async audit(namespace2) {
42814
- const store5 = await getPolicyStore();
42815
- return store5.auditTrail(namespace2);
43312
+ const store6 = await getPolicyStore();
43313
+ return store6.auditTrail(namespace2);
42816
43314
  },
42817
43315
  contract() {
42818
43316
  return MEMORY_PROJECTION_CONTRACT;
@@ -42958,7 +43456,7 @@ async function saveToScope(entry) {
42958
43456
  session.set(storageKey, serialized);
42959
43457
  break;
42960
43458
  case "local":
42961
- store.set(storageKey, serialized);
43459
+ store$1.set(storageKey, serialized);
42962
43460
  break;
42963
43461
  case "durable":
42964
43462
  await idb.set("memories", storageKey, serialized);
@@ -42980,7 +43478,7 @@ async function loadFromScope(id, scope, isSuperseded = false) {
42980
43478
  raw = session.get(storageKey);
42981
43479
  break;
42982
43480
  case "local":
42983
- raw = store.get(storageKey);
43481
+ raw = store$1.get(storageKey);
42984
43482
  break;
42985
43483
  case "durable":
42986
43484
  raw = await idb.get("memories", storageKey);
@@ -43024,7 +43522,7 @@ async function removeFromScope(id, scope, isSuperseded = false) {
43024
43522
  session.remove(storageKey);
43025
43523
  break;
43026
43524
  case "local":
43027
- store.remove(storageKey);
43525
+ store$1.remove(storageKey);
43028
43526
  break;
43029
43527
  case "durable":
43030
43528
  await idb.deleteKey("memories", storageKey);
@@ -43035,7 +43533,7 @@ async function removeFromScope(id, scope, isSuperseded = false) {
43035
43533
  __name(removeFromScope, "removeFromScope");
43036
43534
  async function getAllIndexes() {
43037
43535
  try {
43038
- const raw = store.get(MEMORY_INDEX_KEY);
43536
+ const raw = store$1.get(MEMORY_INDEX_KEY);
43039
43537
  if (!raw) return {};
43040
43538
  return JSON.parse(raw);
43041
43539
  } catch (err2) {
@@ -43047,7 +43545,7 @@ __name(getAllIndexes, "getAllIndexes");
43047
43545
  async function updateIndex(id, scope, isSuperseded = false) {
43048
43546
  const index = await getAllIndexes();
43049
43547
  index[id] = { scope, superseded: isSuperseded };
43050
- store.set(MEMORY_INDEX_KEY, JSON.stringify(index));
43548
+ store$1.set(MEMORY_INDEX_KEY, JSON.stringify(index));
43051
43549
  }
43052
43550
  __name(updateIndex, "updateIndex");
43053
43551
  async function removeFromIndex(id, isSuperseded = false) {
@@ -43060,7 +43558,7 @@ async function removeFromIndex(id, isSuperseded = false) {
43060
43558
  delete index[id];
43061
43559
  }
43062
43560
  }
43063
- store.set(MEMORY_INDEX_KEY, JSON.stringify(index));
43561
+ store$1.set(MEMORY_INDEX_KEY, JSON.stringify(index));
43064
43562
  }
43065
43563
  __name(removeFromIndex, "removeFromIndex");
43066
43564
  async function loadAll() {
@@ -43276,7 +43774,7 @@ var entries = {
43276
43774
  for (const [id, info] of Object.entries(index)) {
43277
43775
  await removeFromScope(id, info.scope, info.superseded);
43278
43776
  }
43279
- store.remove(MEMORY_INDEX_KEY);
43777
+ store$1.remove(MEMORY_INDEX_KEY);
43280
43778
  },
43281
43779
  async _getEntry(key) {
43282
43780
  return getEntry(key);
@@ -43718,6 +44216,778 @@ var injectJoySeed = /* @__PURE__ */ __name(async (opts) => {
43718
44216
  return { id: seedId, action: "stored" };
43719
44217
  }, "injectJoySeed");
43720
44218
 
44219
+ // core/memory/capture-engine.ts
44220
+ init_exemplars();
44221
+ init_loops();
44222
+ init_personality_anchor();
44223
+ var CAPTURE_STATE_KEY = "__dotmem_capture_state__";
44224
+ var DEFAULT_CONFIG = {
44225
+ minSignificance: 0.3,
44226
+ maxItemsPerConversation: 50,
44227
+ dedupSimilarityThreshold: 0.75,
44228
+ preserveConflicts: true,
44229
+ tempContextTtlMs: 24 * 60 * 60 * 1e3,
44230
+ autoCreateExemplars: true,
44231
+ autoCreateLoops: true,
44232
+ autoCreateClaims: true
44233
+ };
44234
+ var CATEGORY_KEYWORDS = {
44235
+ fact: [
44236
+ "is",
44237
+ "are",
44238
+ "was",
44239
+ "were",
44240
+ "uses",
44241
+ "built with",
44242
+ "depends on",
44243
+ "located at",
44244
+ "named",
44245
+ "called",
44246
+ "version",
44247
+ "language",
44248
+ "framework",
44249
+ "test",
44250
+ "testing"
44251
+ ],
44252
+ decision: [
44253
+ "decided",
44254
+ "decision",
44255
+ "agreed",
44256
+ "chose",
44257
+ "selected",
44258
+ "adopt",
44259
+ "going with",
44260
+ "will use",
44261
+ "commit to",
44262
+ "resolve",
44263
+ "settled"
44264
+ ],
44265
+ experience: [
44266
+ "remember when",
44267
+ "we talked about",
44268
+ "discussed",
44269
+ "experienced",
44270
+ "encountered",
44271
+ "faced",
44272
+ "went through",
44273
+ "session",
44274
+ "conversation"
44275
+ ],
44276
+ question: [
44277
+ "?",
44278
+ "how do",
44279
+ "what is",
44280
+ "why",
44281
+ "when",
44282
+ "where",
44283
+ "which",
44284
+ "can you",
44285
+ "should we",
44286
+ "is it possible"
44287
+ ],
44288
+ open_loop: [
44289
+ "still need to",
44290
+ "pending",
44291
+ "waiting for",
44292
+ "todo",
44293
+ "to do",
44294
+ "open",
44295
+ "unresolved",
44296
+ "outstanding",
44297
+ "follow up",
44298
+ "blocked"
44299
+ ],
44300
+ preference: [
44301
+ "prefer",
44302
+ "prefers",
44303
+ "like",
44304
+ "likes",
44305
+ "favorite",
44306
+ "always",
44307
+ "never",
44308
+ "don't like",
44309
+ "dislike",
44310
+ "style",
44311
+ "habit"
44312
+ ],
44313
+ project_context: [
44314
+ "project",
44315
+ "repository",
44316
+ "codebase",
44317
+ "architecture",
44318
+ "stack",
44319
+ "deploy",
44320
+ "ci",
44321
+ "pipeline",
44322
+ "package"
44323
+ ],
44324
+ temporary_context: [
44325
+ "for now",
44326
+ "just for",
44327
+ "temporary",
44328
+ "this session",
44329
+ "currently",
44330
+ "right now",
44331
+ "at the moment",
44332
+ "for this task"
44333
+ ],
44334
+ inference: [
44335
+ "probably",
44336
+ "likely",
44337
+ "maybe",
44338
+ "perhaps",
44339
+ "seems",
44340
+ "appears",
44341
+ "suggests",
44342
+ "indicates",
44343
+ "implies",
44344
+ "might",
44345
+ "could be"
44346
+ ]
44347
+ };
44348
+ var REMEMBER_PATTERNS = [
44349
+ /remember this/i,
44350
+ /remember that/i,
44351
+ /keep this in mind/i,
44352
+ /don't forget/i,
44353
+ /do not forget/i,
44354
+ /store this/i,
44355
+ /save this/i
44356
+ ];
44357
+ var DO_NOT_REMEMBER_PATTERNS = [
44358
+ /don't remember/i,
44359
+ /do not remember/i,
44360
+ /forget this/i,
44361
+ /don't store/i,
44362
+ /do not store/i,
44363
+ /not relevant/i,
44364
+ /ignore this/i,
44365
+ /temporary only/i,
44366
+ /this session only/i
44367
+ ];
44368
+ function generateId() {
44369
+ return `capture-${hlc.serialize(hlc.tick())}-${Math.random().toString(36).slice(2, 10)}`;
44370
+ }
44371
+ __name(generateId, "generateId");
44372
+ function nowIso() {
44373
+ return (/* @__PURE__ */ new Date()).toISOString();
44374
+ }
44375
+ __name(nowIso, "nowIso");
44376
+ function normalizeText(text) {
44377
+ return text.normalize("NFKC").toLocaleLowerCase("en-US").replace(/[^\w\s]/g, " ").replace(/\s+/g, " ").trim();
44378
+ }
44379
+ __name(normalizeText, "normalizeText");
44380
+ function tokenize(text) {
44381
+ return new Set(normalizeText(text).split(" ").filter((t) => t.length > 2));
44382
+ }
44383
+ __name(tokenize, "tokenize");
44384
+ function jaccardSimilarity(a, b) {
44385
+ const ta = tokenize(a);
44386
+ const tb = tokenize(b);
44387
+ if (ta.size === 0 && tb.size === 0) return 1;
44388
+ if (ta.size === 0 || tb.size === 0) return 0;
44389
+ const intersection2 = new Set([...ta].filter((x2) => tb.has(x2)));
44390
+ const union2 = /* @__PURE__ */ new Set([...ta, ...tb]);
44391
+ return intersection2.size / union2.size;
44392
+ }
44393
+ __name(jaccardSimilarity, "jaccardSimilarity");
44394
+ function containsPhrase2(text, phrase) {
44395
+ const t = normalizeText(text);
44396
+ const p = normalizeText(phrase);
44397
+ return t.includes(p);
44398
+ }
44399
+ __name(containsPhrase2, "containsPhrase");
44400
+ function detectExplicitInstructions(text, source) {
44401
+ const instructions = [];
44402
+ for (const pattern of REMEMBER_PATTERNS) {
44403
+ if (pattern.test(text)) {
44404
+ instructions.push({
44405
+ type: "remember",
44406
+ content: text,
44407
+ source,
44408
+ timestamp: nowIso()
44409
+ });
44410
+ break;
44411
+ }
44412
+ }
44413
+ for (const pattern of DO_NOT_REMEMBER_PATTERNS) {
44414
+ if (pattern.test(text)) {
44415
+ instructions.push({
44416
+ type: "do-not-remember",
44417
+ content: text,
44418
+ source,
44419
+ timestamp: nowIso()
44420
+ });
44421
+ break;
44422
+ }
44423
+ }
44424
+ return instructions;
44425
+ }
44426
+ __name(detectExplicitInstructions, "detectExplicitInstructions");
44427
+ function classifyCategory(text, explicitInstructions) {
44428
+ const lower = text.toLocaleLowerCase("en-US");
44429
+ if (explicitInstructions.some((i2) => i2.type === "do-not-remember")) {
44430
+ return "temporary_context";
44431
+ }
44432
+ if (explicitInstructions.some((i2) => i2.type === "remember")) {
44433
+ if (/prefer|prefers|like|likes|favorite|always|never/i.test(lower)) {
44434
+ return "preference";
44435
+ }
44436
+ if (/decided|decision|agreed|chose|adopt/i.test(lower)) {
44437
+ return "decision";
44438
+ }
44439
+ return "fact";
44440
+ }
44441
+ const scores = {};
44442
+ for (const cat of Object.keys(CATEGORY_KEYWORDS)) {
44443
+ scores[cat] = CATEGORY_KEYWORDS[cat].filter((kw) => containsPhrase2(lower, kw)).length;
44444
+ }
44445
+ if (/probably|likely|maybe|perhaps|seems|appears|might|could be/i.test(lower)) {
44446
+ scores.inference += 3;
44447
+ }
44448
+ if (text.includes("?")) {
44449
+ scores.question += 3;
44450
+ }
44451
+ if (/decided|decision|agreed|chose|adopt|will use|going with|resolve|settled/i.test(lower)) {
44452
+ scores.decision += 3;
44453
+ }
44454
+ if (/prefer|prefers|like|likes|favorite|always|never|don.t like|dislike/i.test(lower)) {
44455
+ scores.preference += 3;
44456
+ }
44457
+ if (/still need to|pending|waiting for|todo|to do|unresolved|outstanding|follow.?up|blocked/i.test(lower)) {
44458
+ scores.open_loop += 3;
44459
+ }
44460
+ if (/remember when|we talked about|discussed|experienced|encountered|session|conversation/i.test(lower)) {
44461
+ scores.experience += 2;
44462
+ }
44463
+ if (/repository|architecture|deploy|ci|pipeline/i.test(lower)) {
44464
+ scores.project_context += 2;
44465
+ }
44466
+ if (/just for|this session|for now|temporary/i.test(lower)) {
44467
+ scores.temporary_context += 3;
44468
+ }
44469
+ if (scores.fact > 0 && scores.project_context > 0 && scores.fact === scores.project_context) {
44470
+ scores.fact += 1;
44471
+ }
44472
+ let bestCategory = "fact";
44473
+ let bestScore = -1;
44474
+ for (const [cat, score] of Object.entries(scores)) {
44475
+ if (score > bestScore) {
44476
+ bestScore = score;
44477
+ bestCategory = cat;
44478
+ }
44479
+ }
44480
+ if (bestScore === 0) return "fact";
44481
+ return bestCategory;
44482
+ }
44483
+ __name(classifyCategory, "classifyCategory");
44484
+ function determineEpistemicType(category, text, explicitInstructions) {
44485
+ if (explicitInstructions.some((i2) => i2.type === "remember")) {
44486
+ return "human-stated";
44487
+ }
44488
+ if (category === "inference" || /probably|likely|maybe|perhaps|seems|appears/i.test(text)) {
44489
+ return "inferred";
44490
+ }
44491
+ if (category === "question") return "observed";
44492
+ return "observed";
44493
+ }
44494
+ __name(determineEpistemicType, "determineEpistemicType");
44495
+ function determineConfidence(category, epistemicType, _text) {
44496
+ if (epistemicType === "human-stated") return "high";
44497
+ if (epistemicType === "inferred") return "low";
44498
+ if (category === "decision" || category === "preference") return "medium";
44499
+ if (category === "question") return "medium";
44500
+ if (category === "fact") return "medium";
44501
+ return "low";
44502
+ }
44503
+ __name(determineConfidence, "determineConfidence");
44504
+ function extractEntities(text) {
44505
+ const entities = [];
44506
+ const seen = /* @__PURE__ */ new Set();
44507
+ const capitalizedMatches = text.match(/\b[A-Z][a-zA-Z]+(?:\s+[A-Z][a-zA-Z]+)*\b/g) || [];
44508
+ for (const match of capitalizedMatches) {
44509
+ if (seen.has(match)) continue;
44510
+ seen.add(match);
44511
+ entities.push({
44512
+ id: `entity-${normalizeText(match)}`,
44513
+ type: "concept",
44514
+ name: match,
44515
+ aliases: [],
44516
+ relationships: []
44517
+ });
44518
+ }
44519
+ const quotedMatches = text.match(/["'`]([^"`']{2,})["'`]/g) || [];
44520
+ for (const match of quotedMatches) {
44521
+ const clean = match.replace(/["'`]/g, "");
44522
+ if (seen.has(clean)) continue;
44523
+ seen.add(clean);
44524
+ entities.push({
44525
+ id: `entity-${normalizeText(clean)}`,
44526
+ type: "concept",
44527
+ name: clean,
44528
+ aliases: [],
44529
+ relationships: []
44530
+ });
44531
+ }
44532
+ return entities;
44533
+ }
44534
+ __name(extractEntities, "extractEntities");
44535
+ function extractRelationships(_text, entities) {
44536
+ const relationships = [];
44537
+ if (entities.length < 2) return relationships;
44538
+ for (let i2 = 0; i2 < entities.length - 1; i2++) {
44539
+ for (let j = i2 + 1; j < entities.length; j++) {
44540
+ relationships.push({
44541
+ from: entities[i2].id,
44542
+ to: entities[j].id,
44543
+ type: "related-to",
44544
+ confidence: 0.5
44545
+ });
44546
+ }
44547
+ }
44548
+ return relationships;
44549
+ }
44550
+ __name(extractRelationships, "extractRelationships");
44551
+ async function findExistingSimilarItems(statement, category, existingItems, threshold) {
44552
+ const matches2 = [];
44553
+ for (const existing of existingItems) {
44554
+ if (existing.category !== category) continue;
44555
+ const similarity = jaccardSimilarity(statement, existing.statement);
44556
+ if (similarity >= threshold) {
44557
+ matches2.push({
44558
+ existingId: existing.id,
44559
+ existingStatement: existing.statement,
44560
+ similarity,
44561
+ matchType: similarity >= 0.95 ? "exact" : "semantic",
44562
+ category: existing.category
44563
+ });
44564
+ }
44565
+ }
44566
+ return matches2;
44567
+ }
44568
+ __name(findExistingSimilarItems, "findExistingSimilarItems");
44569
+ async function findExistingMemoryEntries(statement, category) {
44570
+ const matches2 = [];
44571
+ try {
44572
+ const all = await entries._loadAll();
44573
+ for (const entry of all) {
44574
+ if (entry.status !== "active") continue;
44575
+ if (entry.type !== category && entry.type !== "fact") continue;
44576
+ const entryText = typeof entry.value === "string" ? entry.value : JSON.stringify(entry.value);
44577
+ const similarity = jaccardSimilarity(statement, entryText);
44578
+ if (similarity >= DEFAULT_CONFIG.dedupSimilarityThreshold) {
44579
+ matches2.push({
44580
+ existingId: entry.id,
44581
+ existingStatement: entryText,
44582
+ similarity,
44583
+ matchType: similarity >= 0.95 ? "exact" : "semantic",
44584
+ category
44585
+ });
44586
+ }
44587
+ }
44588
+ } catch {
44589
+ }
44590
+ return matches2;
44591
+ }
44592
+ __name(findExistingMemoryEntries, "findExistingMemoryEntries");
44593
+ function shouldStoreInCoreMemory(category, epistemicType) {
44594
+ return category === "preference" && epistemicType === "human-stated";
44595
+ }
44596
+ __name(shouldStoreInCoreMemory, "shouldStoreInCoreMemory");
44597
+ async function routeToStorage(item, adapters, config2) {
44598
+ const { category, epistemicType, statement, entities, provenance, confidence } = item;
44599
+ const memKey = `capture:${item.id}`;
44600
+ await entries.remember(memKey, {
44601
+ id: item.id,
44602
+ category,
44603
+ statement,
44604
+ entities,
44605
+ relationships: item.relationships,
44606
+ provenance,
44607
+ confidence,
44608
+ epistemicType,
44609
+ capturedAt: provenance.capturedAt
44610
+ }, {
44611
+ id: item.id,
44612
+ type: category === "preference" ? "preference" : category === "decision" ? "decision" : category === "fact" ? "fact" : "context",
44613
+ confidence: confidence === "high" ? 1 : confidence === "medium" ? 0.7 : 0.4,
44614
+ scope: category === "temporary_context" ? "session" : "local",
44615
+ tags: [category, provenance.epistemicType, provenance.source.conversationId],
44616
+ source: `capture:${provenance.source.conversationId}`
44617
+ });
44618
+ if (shouldStoreInCoreMemory(category, epistemicType)) {
44619
+ try {
44620
+ const anchor2 = await loadPersonalityAnchor();
44621
+ const existingPref = anchor2.identity.durablePreferences.find((p) => p.statement === statement);
44622
+ if (!existingPref) {
44623
+ await updatePersonalityAnchor({
44624
+ durablePreferences: [
44625
+ ...anchor2.identity.durablePreferences,
44626
+ {
44627
+ id: item.id,
44628
+ statement,
44629
+ confidence: epistemicType,
44630
+ evidence: [provenance.source.conversationId],
44631
+ firstObserved: provenance.capturedAt,
44632
+ lastConfirmed: provenance.capturedAt
44633
+ }
44634
+ ]
44635
+ });
44636
+ }
44637
+ } catch {
44638
+ }
44639
+ }
44640
+ if (category === "open_loop" && config2.autoCreateLoops) {
44641
+ try {
44642
+ const existingLoops = await listLoops(true);
44643
+ const alreadyExists = existingLoops.some((l) => l.text === statement);
44644
+ if (!alreadyExists) {
44645
+ await addLoop({
44646
+ id: item.id,
44647
+ text: statement,
44648
+ waitor: "joy",
44649
+ openedAt: provenance.capturedAt
44650
+ });
44651
+ }
44652
+ } catch {
44653
+ }
44654
+ }
44655
+ if (category === "experience" && config2.autoCreateExemplars) {
44656
+ try {
44657
+ await addExemplar({
44658
+ id: item.id,
44659
+ source: {
44660
+ conversationId: provenance.source.conversationId,
44661
+ messageIds: provenance.source.messageIds
44662
+ },
44663
+ pattern: statement,
44664
+ originalContent: statement,
44665
+ sourceReference: `capture:${item.id}`,
44666
+ retrievalHints: [statement, ...entities.map((e) => e.name)],
44667
+ significance: confidence === "high" ? 0.8 : confidence === "medium" ? 0.5 : 0.3,
44668
+ confidence: confidence === "high" ? 1 : confidence === "medium" ? 0.7 : 0.4,
44669
+ provenance: epistemicType,
44670
+ createdAt: provenance.capturedAt
44671
+ });
44672
+ } catch {
44673
+ }
44674
+ }
44675
+ if (config2.autoCreateClaims && (category === "fact" || category === "decision")) {
44676
+ try {
44677
+ await acquire.acquire({
44678
+ id: `claim-${item.id}`,
44679
+ knowledge: { statement, category },
44680
+ applicability: { area: "project" },
44681
+ evidence: [{
44682
+ id: `ev-${item.id}`,
44683
+ source: provenance.source.conversationId,
44684
+ observedAt: provenance.capturedAt,
44685
+ supports: statement
44686
+ }],
44687
+ epistemicType,
44688
+ provenance: { source: "conversation-capture", detail: `category:${category}` },
44689
+ acquiredAt: provenance.capturedAt,
44690
+ scope: "project"
44691
+ });
44692
+ } catch {
44693
+ }
44694
+ }
44695
+ dispatch.set("dotmem:capture:item-captured", {
44696
+ detail: { id: item.id, category, statement }
44697
+ });
44698
+ }
44699
+ __name(routeToStorage, "routeToStorage");
44700
+ var CaptureEngine = class {
44701
+ static {
44702
+ __name(this, "CaptureEngine");
44703
+ }
44704
+ config;
44705
+ adapters;
44706
+ sessionContexts = /* @__PURE__ */ new Map();
44707
+ constructor(config2 = {}, adapters) {
44708
+ this.config = { ...DEFAULT_CONFIG, ...config2 };
44709
+ this.adapters = {
44710
+ remember: entries.remember.bind(entries),
44711
+ recall: entries.recall.bind(entries),
44712
+ update: entries.update.bind(entries),
44713
+ addExemplar: addExemplar.bind(null),
44714
+ updateExemplar: updateExemplar.bind(null),
44715
+ addLoop: addLoop.bind(null),
44716
+ closeLoop: closeLoop.bind(null),
44717
+ updatePersonalityAnchor: updatePersonalityAnchor.bind(null),
44718
+ ...adapters
44719
+ };
44720
+ }
44721
+ /**
44722
+ * Capture information from a conversation turn.
44723
+ * Processes a single message or turn of conversation.
44724
+ */
44725
+ async captureTurn(text, options) {
44726
+ const source = {
44727
+ conversationId: options.conversationId,
44728
+ messageIds: options.messageIds ?? [],
44729
+ timestamp: nowIso(),
44730
+ turnIndex: 0
44731
+ };
44732
+ const instructions = detectExplicitInstructions(text, source);
44733
+ const hasDoNotRemember = instructions.some((i2) => i2.type === "do-not-remember");
44734
+ const hasExplicitRemember = instructions.some((i2) => i2.type === "remember");
44735
+ let created = 0, linked = 0, ignored = 0;
44736
+ if (hasDoNotRemember && !hasExplicitRemember) {
44737
+ const item2 = {
44738
+ id: generateId(),
44739
+ category: "temporary_context",
44740
+ statement: text,
44741
+ content: { text },
44742
+ entities: [],
44743
+ relationships: [],
44744
+ provenance: {
44745
+ source,
44746
+ classification: "temporary_context",
44747
+ confidence: "low",
44748
+ epistemicType: "observed",
44749
+ capturedAt: nowIso(),
44750
+ method: "automatic"
44751
+ },
44752
+ confidence: "low",
44753
+ epistemicType: "observed"
44754
+ };
44755
+ await this.storeSessionContext(options.conversationId, [item2], instructions);
44756
+ ignored++;
44757
+ return { items: [item2], instructions, created: 0, linked: 0, ignored: 1, dedupMatches: [] };
44758
+ }
44759
+ const category = classifyCategory(text, instructions);
44760
+ const epistemicType = determineEpistemicType(category, text, instructions);
44761
+ const confidence = determineConfidence(category, epistemicType);
44762
+ const entities = extractEntities(text);
44763
+ const relationships = extractRelationships(text, entities);
44764
+ const provenance = {
44765
+ source,
44766
+ classification: category,
44767
+ confidence,
44768
+ epistemicType,
44769
+ capturedAt: nowIso(),
44770
+ method: hasExplicitRemember ? "explicit" : "automatic"
44771
+ };
44772
+ const item = {
44773
+ id: generateId(),
44774
+ category,
44775
+ statement: text,
44776
+ content: { text },
44777
+ entities,
44778
+ relationships,
44779
+ provenance,
44780
+ confidence,
44781
+ epistemicType
44782
+ };
44783
+ const sessionCtx = this.sessionContexts.get(options.conversationId);
44784
+ const existingItems = sessionCtx ? sessionCtx.items : [];
44785
+ const dedupMatches = await findExistingSimilarItems(
44786
+ text,
44787
+ category,
44788
+ existingItems,
44789
+ this.config.dedupSimilarityThreshold
44790
+ );
44791
+ const memoryMatches = await findExistingMemoryEntries(text, category);
44792
+ const allMatches = [...dedupMatches, ...memoryMatches];
44793
+ let decision = "create";
44794
+ if (allMatches.length > 0) {
44795
+ const exactMatch = allMatches.find((m) => m.matchType === "exact");
44796
+ if (exactMatch) {
44797
+ decision = "link";
44798
+ linked++;
44799
+ } else {
44800
+ decision = "create";
44801
+ created++;
44802
+ }
44803
+ } else {
44804
+ created++;
44805
+ }
44806
+ const finalItem = { ...item };
44807
+ const shouldStore = decision === "create" || decision === "link";
44808
+ if (shouldStore) {
44809
+ await routeToStorage(finalItem, this.adapters, this.config);
44810
+ }
44811
+ await this.storeSessionContext(options.conversationId, [finalItem], instructions);
44812
+ return { items: [finalItem], instructions, created, linked, ignored, dedupMatches: allMatches };
44813
+ }
44814
+ /**
44815
+ * Capture information from a full conversation (array of messages).
44816
+ * Processes each message and returns aggregated results.
44817
+ */
44818
+ async captureConversation(messages, options) {
44819
+ const allItems = [];
44820
+ const allInstructions = [];
44821
+ let created = 0, updated = 0, linked = 0, ignored = 0;
44822
+ const allDedupMatches = [];
44823
+ for (const [index, msg] of messages.entries()) {
44824
+ const source = {
44825
+ conversationId: options.conversationId,
44826
+ messageIds: [msg.id ?? `msg-${index}`],
44827
+ timestamp: msg.timestamp ?? nowIso(),
44828
+ turnIndex: index
44829
+ };
44830
+ const instructions = detectExplicitInstructions(msg.content, source);
44831
+ allInstructions.push(...instructions);
44832
+ const hasDoNotRemember = instructions.some((i2) => i2.type === "do-not-remember");
44833
+ const hasExplicitRemember = instructions.some((i2) => i2.type === "remember");
44834
+ if (hasDoNotRemember && !hasExplicitRemember) {
44835
+ const item2 = {
44836
+ id: generateId(),
44837
+ category: "temporary_context",
44838
+ statement: msg.content,
44839
+ content: { text: msg.content, role: msg.role },
44840
+ entities: [],
44841
+ relationships: [],
44842
+ provenance: {
44843
+ source,
44844
+ classification: "temporary_context",
44845
+ confidence: "low",
44846
+ epistemicType: "observed",
44847
+ capturedAt: nowIso(),
44848
+ method: "automatic"
44849
+ },
44850
+ confidence: "low",
44851
+ epistemicType: "observed"
44852
+ };
44853
+ allItems.push(item2);
44854
+ ignored++;
44855
+ continue;
44856
+ }
44857
+ const category = classifyCategory(msg.content, instructions);
44858
+ const epistemicType = determineEpistemicType(category, msg.content, instructions);
44859
+ const confidence = determineConfidence(category, epistemicType, msg.content);
44860
+ const entities = extractEntities(msg.content);
44861
+ const relationships = extractRelationships(msg.content, entities);
44862
+ const provenance = {
44863
+ source,
44864
+ classification: category,
44865
+ confidence,
44866
+ epistemicType,
44867
+ capturedAt: nowIso(),
44868
+ method: hasExplicitRemember ? "explicit" : "automatic"
44869
+ };
44870
+ const item = {
44871
+ id: generateId(),
44872
+ category,
44873
+ statement: msg.content,
44874
+ content: { text: msg.content, role: msg.role },
44875
+ entities,
44876
+ relationships,
44877
+ provenance,
44878
+ confidence,
44879
+ epistemicType
44880
+ };
44881
+ const dedupMatches = await findExistingSimilarItems(
44882
+ msg.content,
44883
+ category,
44884
+ allItems,
44885
+ this.config.dedupSimilarityThreshold
44886
+ );
44887
+ const memoryMatches = await findExistingMemoryEntries(msg.content, category);
44888
+ const allMatches = [...dedupMatches, ...memoryMatches];
44889
+ allDedupMatches.push(...allMatches);
44890
+ let decision = "create";
44891
+ if (allMatches.length > 0) {
44892
+ const exactMatch = allMatches.find((m) => m.matchType === "exact");
44893
+ if (exactMatch) {
44894
+ decision = "link";
44895
+ linked++;
44896
+ } else {
44897
+ decision = "create";
44898
+ created++;
44899
+ }
44900
+ } else {
44901
+ created++;
44902
+ }
44903
+ const shouldStore = decision === "create" || decision === "link";
44904
+ if (shouldStore) {
44905
+ await routeToStorage(item, this.adapters, this.config);
44906
+ }
44907
+ if (!shouldStore) ignored++;
44908
+ allItems.push(item);
44909
+ }
44910
+ await this.storeSessionContext(options.conversationId, allItems, allInstructions);
44911
+ return {
44912
+ items: allItems,
44913
+ created,
44914
+ updated,
44915
+ linked,
44916
+ ignored,
44917
+ dedupMatches: allDedupMatches,
44918
+ provenance: allItems.map((i2) => i2.provenance)
44919
+ };
44920
+ }
44921
+ /**
44922
+ * Retrieve captured items for a conversation.
44923
+ */
44924
+ async getCapturedItems(conversationId) {
44925
+ const ctx = this.sessionContexts.get(conversationId);
44926
+ return ctx ? ctx.items : [];
44927
+ }
44928
+ /**
44929
+ * Get all captured items across all conversations.
44930
+ */
44931
+ async getAllCapturedItems() {
44932
+ const all = [];
44933
+ for (const ctx of this.sessionContexts.values()) {
44934
+ all.push(...ctx.items);
44935
+ }
44936
+ return all;
44937
+ }
44938
+ /**
44939
+ * Clear session context (for testing / cleanup).
44940
+ */
44941
+ clearSession(conversationId) {
44942
+ this.sessionContexts.delete(conversationId);
44943
+ }
44944
+ /**
44945
+ * Get capture engine configuration.
44946
+ */
44947
+ getConfig() {
44948
+ return { ...this.config };
44949
+ }
44950
+ // ---------------------------------------------------------------------------
44951
+ // Private
44952
+ // ---------------------------------------------------------------------------
44953
+ async storeSessionContext(conversationId, items, instructions) {
44954
+ let ctx = this.sessionContexts.get(conversationId);
44955
+ if (!ctx) {
44956
+ ctx = {
44957
+ conversationId,
44958
+ startedAt: nowIso(),
44959
+ items: [],
44960
+ explicitInstructions: []
44961
+ };
44962
+ this.sessionContexts.set(conversationId, ctx);
44963
+ }
44964
+ ctx.items.push(...items);
44965
+ ctx.explicitInstructions.push(...instructions);
44966
+ try {
44967
+ const stateKey = `${CAPTURE_STATE_KEY}:${conversationId}`;
44968
+ const existing = store.get(stateKey);
44969
+ let prior = [];
44970
+ if (existing) {
44971
+ try {
44972
+ prior = JSON.parse(existing);
44973
+ } catch {
44974
+ }
44975
+ }
44976
+ store.set(stateKey, JSON.stringify([...prior, ...items]));
44977
+ } catch {
44978
+ }
44979
+ }
44980
+ };
44981
+ var captureEngine = new CaptureEngine();
44982
+ async function captureConversation(messages, options) {
44983
+ return captureEngine.captureConversation(messages, options);
44984
+ }
44985
+ __name(captureConversation, "captureConversation");
44986
+ async function captureTurn(text, options) {
44987
+ return captureEngine.captureTurn(text, options);
44988
+ }
44989
+ __name(captureTurn, "captureTurn");
44990
+
43721
44991
  // core/memory/index.ts
43722
44992
  init_detection_events();
43723
44993
  init_detection_journal();
@@ -43827,7 +45097,7 @@ var memory = {
43827
45097
  */
43828
45098
  async clear() {
43829
45099
  await entries.clearEntries();
43830
- store.remove("__dotmem_acquired_knowledge_state__");
45100
+ store$1.remove("__dotmem_acquired_knowledge_state__");
43831
45101
  await resetKnowledgeRuntimeCaches();
43832
45102
  resetBrainPathCache();
43833
45103
  resetPolicyStoreCache();
@@ -43905,6 +45175,25 @@ var memory = {
43905
45175
  async getSeedId() {
43906
45176
  return SEED_ID;
43907
45177
  }
45178
+ },
45179
+ /** Automatic conversational capture engine (Phase 2 — Workstream B). */
45180
+ capture: {
45181
+ engine: captureEngine,
45182
+ async conversation(messages, options) {
45183
+ return captureConversation(messages, options);
45184
+ },
45185
+ async turn(text, options) {
45186
+ return captureTurn(text, options);
45187
+ },
45188
+ async getItems(conversationId) {
45189
+ return captureEngine.getCapturedItems(conversationId);
45190
+ },
45191
+ async getAllItems() {
45192
+ return captureEngine.getAllCapturedItems();
45193
+ },
45194
+ clearSession(conversationId) {
45195
+ captureEngine.clearSession(conversationId);
45196
+ }
43908
45197
  }
43909
45198
  };
43910
45199