@unblocklabs/unblock-memory 0.10.0 → 0.10.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/dist/src/abortable.d.ts +2 -0
  2. package/dist/src/abortable.js +4 -0
  3. package/dist/src/agent-paths.d.ts +5 -0
  4. package/dist/src/agent-paths.js +10 -0
  5. package/dist/src/analysis.js +13 -18
  6. package/dist/src/cluster-review.js +9 -7
  7. package/dist/src/config.js +2 -2
  8. package/dist/src/curation.js +3 -10
  9. package/dist/src/emotion-baselines.d.ts +12 -1
  10. package/dist/src/emotion-baselines.js +67 -47
  11. package/dist/src/evidence-review.js +2 -1
  12. package/dist/src/extraction-chunk.js +3 -4
  13. package/dist/src/extraction-index.d.ts +2 -0
  14. package/dist/src/extraction-index.js +4 -2
  15. package/dist/src/extraction-runtime.js +3 -3
  16. package/dist/src/extraction-store.js +7 -19
  17. package/dist/src/extraction-worker.js +3 -2
  18. package/dist/src/guards.d.ts +6 -0
  19. package/dist/src/guards.js +12 -0
  20. package/dist/src/inside-out-runtime.js +4 -3
  21. package/dist/src/inside-out-store.d.ts +28 -4
  22. package/dist/src/inside-out-store.js +50 -19
  23. package/dist/src/inside-out.js +6 -6
  24. package/dist/src/json-hash.d.ts +2 -0
  25. package/dist/src/json-hash.js +6 -0
  26. package/dist/src/manager.js +62 -91
  27. package/dist/src/memory-database.d.ts +3 -0
  28. package/dist/src/memory-database.js +18 -1
  29. package/dist/src/people-hooks.js +3 -6
  30. package/dist/src/people-primer-tool.js +0 -2
  31. package/dist/src/people-primer.js +3 -6
  32. package/dist/src/people-store.d.ts +2 -1
  33. package/dist/src/people-store.js +29 -82
  34. package/dist/src/people-tools.js +4 -5
  35. package/dist/src/plugin.js +20 -13
  36. package/dist/src/quality-audit.js +2 -2
  37. package/dist/src/query-generator.js +1 -1
  38. package/dist/src/response-audit.js +7 -8
  39. package/dist/src/response-episodes.js +5 -8
  40. package/dist/src/response-judge.js +2 -3
  41. package/dist/src/response-reviews.js +8 -18
  42. package/dist/src/response-runtime.js +4 -3
  43. package/dist/src/response-stages.js +4 -4
  44. package/dist/src/response-store.js +15 -44
  45. package/dist/src/response-text.d.ts +1 -0
  46. package/dist/src/response-text.js +6 -4
  47. package/dist/src/runtime.js +9 -8
  48. package/dist/src/safety-whisperer.js +4 -12
  49. package/dist/src/session-projector.js +7 -14
  50. package/dist/src/session-sync.d.ts +1 -0
  51. package/dist/src/session-sync.js +13 -17
  52. package/dist/src/skill-whisperer.js +3 -9
  53. package/dist/src/slack-directory.js +1 -5
  54. package/dist/src/sources.js +17 -37
  55. package/dist/src/tool-context.d.ts +2 -0
  56. package/dist/src/tool-context.js +5 -1
  57. package/dist/src/training-input.d.ts +0 -1
  58. package/dist/src/training-input.js +3 -6
  59. package/dist/src/training-queries.d.ts +1 -1
  60. package/dist/src/training-queries.js +9 -8
  61. package/dist/src/training-retrieval.js +2 -2
  62. package/dist/src/training-runtime.js +3 -3
  63. package/dist/src/training-store.js +14 -25
  64. package/dist/src/typesafe-client.d.ts +8 -0
  65. package/dist/src/typesafe-client.js +7 -1
  66. package/dist/src/typesafe-review.d.ts +1 -1
  67. package/dist/src/typesafe-review.js +1 -3
  68. package/dist/src/typesafe.js +4 -7
  69. package/docs/configuration.md +17 -7
  70. package/docs/retrieval.md +2 -1
  71. package/openclaw.plugin.json +2 -3
  72. package/package.json +1 -1
@@ -1,13 +1,12 @@
1
- import { createHash } from "node:crypto";
2
1
  import { readdirSync, readFileSync, realpathSync, statSync } from "node:fs";
3
2
  import { mkdir, stat } from "node:fs/promises";
4
3
  import { basename, dirname, relative, resolve, sep } from "node:path";
5
- import { EXTRACTED_COLLECTION, extractedRecords, extractedPath, extractedHit, syncExtractedIndex } from "./extraction-index.js";
4
+ import { EXTRACTED_COLLECTION, EXTRACTED_PREFIX, extractedRecords, extractedPath, extractedHit, extractedUri, syncExtractedIndex } from "./extraction-index.js";
6
5
  import chokidar from "chokidar";
7
6
  import picomatch from "picomatch";
8
7
  import { ensureMemoryAnalysisSchema, latestAnalysisCollections, latestAnalysisRunId, markMemoryAnalysisStale, readAnalysisSummary, readCluster, readClusters, runAnalysisWorker, } from "./analysis.js";
9
8
  import { CurationStore, chunkFingerprint, } from "./curation.js";
10
- import { readSessionManifest, sessionMetadataByPath, syncSessionProjections, PROJECTOR_VERSION, } from "./session-sync.js";
9
+ import { projectionHash, readSessionManifest, sessionMetadataByPath, syncSessionProjections, PROJECTOR_VERSION, } from "./session-sync.js";
11
10
  import { parseSessionMessageSpans, sessionContextSpans, sessionSnippetMessages } from "./session-projector.js";
12
11
  import { parseSafeVirtualPath, sourceMatchesPath } from "./sources.js";
13
12
  import { auditQualityPage } from "./quality-audit.js";
@@ -211,8 +210,13 @@ export class QmdMemoryManager {
211
210
  #dbPath;
212
211
  #workspaceDir;
213
212
  #curationPath;
214
- #extraction;
213
+ /** Present only when extracted memories are published into search. */
214
+ #publishedExtraction;
215
215
  #sources;
216
+ /** Non-skill sources: the QMD-indexed, analyzable corpora. */
217
+ #indexSources;
218
+ #indexCollections;
219
+ #hasSkills;
216
220
  #storeFactory;
217
221
  #keepModelsWarm;
218
222
  #analysisExecutable;
@@ -264,9 +268,12 @@ export class QmdMemoryManager {
264
268
  constructor(params) {
265
269
  this.#dbPath = params.dbPath;
266
270
  this.#curationPath = params.curationPath ?? `${params.dbPath}.curation.sqlite`;
267
- this.#extraction = params.extraction;
271
+ this.#publishedExtraction = params.extraction?.enabled && params.extraction.publish ? params.extraction : undefined;
268
272
  this.#workspaceDir = params.workspaceDir;
269
273
  this.#sources = new Map(params.sources.map((source) => [source.collection, source]));
274
+ this.#indexSources = [...this.#sources.values()].filter((source) => source.kind !== "skills");
275
+ this.#indexCollections = this.#indexSources.map((source) => source.collection);
276
+ this.#hasSkills = [...this.#sources.values()].some((source) => source.kind === "skills");
270
277
  this.#storeFactory = params.storeFactory;
271
278
  this.#keepModelsWarm = params.keepModelsWarm ?? true;
272
279
  this.#analysisExecutable = params.analysisExecutable;
@@ -360,7 +367,7 @@ export class QmdMemoryManager {
360
367
  const store = this.#store;
361
368
  if (store.internal) {
362
369
  ensureMemoryAnalysisSchema(store.internal.db);
363
- markStaleForAnalysisCollectionChange(store.internal.db, this.#analysisCollectionNames(), this.#skillCollectionNames().length > 0);
370
+ markStaleForAnalysisCollectionChange(store.internal.db, this.#indexCollections, this.#hasSkills);
364
371
  }
365
372
  return this.#store;
366
373
  }
@@ -369,36 +376,31 @@ export class QmdMemoryManager {
369
376
  dbPath: this.#dbPath,
370
377
  keepModelsWarm: this.#keepModelsWarm,
371
378
  config: {
372
- collections: Object.fromEntries([...this.#qmdSources().map((source) => [
379
+ collections: Object.fromEntries([...this.#indexSources.map((source) => [
373
380
  source.collection,
374
381
  { path: source.root, pattern: source.pattern },
375
- ]), ...(this.#extraction?.enabled && this.#extraction.publish
382
+ ]), ...(this.#publishedExtraction
376
383
  ? [[EXTRACTED_COLLECTION, { path: dirname(this.#dbPath), pattern: ".no-extracted-files", includeByDefault: false }]] : [])]),
377
384
  },
378
385
  });
379
386
  try {
380
387
  enableSecureDelete(store);
381
388
  ensureMemoryAnalysisSchema(store.internal.db);
382
- markStaleForAnalysisCollectionChange(store.internal.db, this.#analysisCollectionNames(), this.#skillCollectionNames().length > 0);
383
- const configuredCollections = new Set(this.#qmdSources().map((source) => source.collection));
384
- if (this.#extraction?.enabled && this.#extraction.publish)
385
- configuredCollections.add(EXTRACTED_COLLECTION);
389
+ markStaleForAnalysisCollectionChange(store.internal.db, this.#indexCollections, this.#hasSkills);
390
+ const configuredCollections = new Set(this.#collectionNames());
386
391
  const staleCollections = (await store.getStatus()).collections
387
392
  .map((collection) => collection.name)
388
393
  .filter((collection) => !configuredCollections.has(collection));
394
+ const latestRunId = latestAnalysisRunId(store.internal.db);
389
395
  const appearsInAnalysis = store.internal.db.prepare(`
390
396
  SELECT 1
391
397
  FROM memory_analysis_memberships membership
392
398
  JOIN documents document ON document.hash = membership.hash
393
- WHERE membership.run_id = (
394
- SELECT id FROM memory_analysis_runs
395
- WHERE completed_at IS NOT NULL
396
- ORDER BY completed_at DESC, created_at DESC, id DESC
397
- LIMIT 1
398
- ) AND document.collection = ?
399
+ WHERE membership.run_id = ? AND document.collection = ?
399
400
  LIMIT 1
400
401
  `);
401
- const prunedAnalysisInput = staleCollections.some((collection) => appearsInAnalysis.get(collection));
402
+ const prunedAnalysisInput = latestRunId !== undefined &&
403
+ staleCollections.some((collection) => appearsInAnalysis.get(latestRunId, collection));
402
404
  const prunedDocuments = await pruneStaleCollections(store, configuredCollections);
403
405
  if (prunedDocuments > 0 && prunedAnalysisInput)
404
406
  markMemoryAnalysisStale(store.internal.db);
@@ -414,69 +416,64 @@ export class QmdMemoryManager {
414
416
  this.#store = store;
415
417
  return store;
416
418
  }
417
- #qmdSources() {
418
- return [...this.#sources.values()].filter((source) => source.kind !== "skills");
419
- }
420
- #analysisCollectionNames() {
421
- return [...this.#sources.values()]
422
- .filter((source) => source.kind !== "skills")
423
- .map((source) => source.collection);
424
- }
425
- #skillCollectionNames() {
426
- return [...this.#sources.values()]
427
- .filter((source) => source.kind === "skills")
428
- .map((source) => source.collection);
429
- }
430
419
  #collectionNames(corpora) {
431
- const publicSources = [...this.#sources.values()].filter((source) => source.kind !== "skills");
432
- const extracted = this.#extraction?.enabled && this.#extraction.publish ? [EXTRACTED_COLLECTION] : [];
420
+ const extracted = this.#publishedExtraction ? [EXTRACTED_COLLECTION] : [];
433
421
  if (corpora === undefined)
434
- return [...publicSources.map((source) => source.collection), ...extracted];
422
+ return [...this.#indexCollections, ...extracted];
435
423
  if (corpora.length === 0)
436
424
  throw new Error("memory_search corpora must not be empty");
437
425
  const selected = new Set(corpora);
438
426
  if (selected.has("all")) {
439
427
  if (selected.size > 1)
440
428
  throw new Error('memory_search corpus "all" must be used alone');
441
- return [...publicSources.map((source) => source.collection), ...extracted];
429
+ return [...this.#indexCollections, ...extracted];
442
430
  }
443
- const known = new Set(publicSources.map((source) => source.corpus));
431
+ const known = new Set(this.#indexSources.map((source) => source.corpus));
444
432
  if (extracted.length)
445
433
  known.add("extracted");
446
434
  const unknown = [...selected].find((corpus) => !known.has(corpus));
447
435
  if (unknown)
448
436
  throw new Error(`memory_search unknown corpus: ${unknown}`);
449
- return [...publicSources
437
+ return [...this.#indexSources
450
438
  .filter((source) => selected.has(source.corpus))
451
439
  .map((source) => source.collection), ...(selected.has("extracted") ? extracted : [])];
452
440
  }
453
441
  syncExtracted() {
454
442
  return this.#enqueue(async () => {
455
- if (!this.#extraction?.enabled || !this.#extraction.publish)
443
+ if (!this.#publishedExtraction)
456
444
  return;
457
445
  const store = await this.#getAnalysisStore();
458
- const records = extractedRecords(this.#curationPath).filter(r => this.#extraction.chatTypes.includes(r.metadata.chatType));
459
- await syncExtractedIndex(store, records);
446
+ await syncExtractedIndex(store, this.#currentExtracted());
460
447
  await this.#refreshIndexStatus(store);
461
448
  });
462
449
  }
463
450
  #currentExtracted(paths, filter) {
464
- if (!this.#extraction?.enabled || !this.#extraction.publish)
451
+ const extraction = this.#publishedExtraction;
452
+ if (!extraction)
465
453
  return [];
466
- const records = extractedRecords(this.#curationPath, paths?.filter(path => path.startsWith(`qmd://${EXTRACTED_COLLECTION}/`))
467
- .map(path => path.slice(`qmd://${EXTRACTED_COLLECTION}/`.length)))
468
- .filter(r => this.#extraction.chatTypes.includes(r.metadata.chatType));
454
+ const records = extractedRecords(this.#curationPath, paths?.filter(path => path.startsWith(EXTRACTED_PREFIX))
455
+ .map(path => path.slice(EXTRACTED_PREFIX.length)))
456
+ .filter(r => extraction.chatTypes.includes(r.metadata.chatType));
469
457
  if (!filter)
470
458
  return records;
471
459
  const allowed = new Set(sessionAllowedPaths(new Map(records.map(r => [extractedPath(r), r.metadata])), EXTRACTED_COLLECTION, filter)[EXTRACTED_COLLECTION]);
472
460
  return records.filter(r => allowed.has(extractedPath(r)));
473
461
  }
462
+ /** Search scope: session-filtered transcripts plus currently published extracted memories. */
463
+ #allowedPaths(collections, filter) {
464
+ const sessions = this.#sessions;
465
+ const allowed = filter && sessions && collections.includes(sessions.collection)
466
+ ? sessionAllowedPaths(this.#sessionMetadata, sessions.collection, filter) : undefined;
467
+ return collections.includes(EXTRACTED_COLLECTION)
468
+ ? { ...allowed, [EXTRACTED_COLLECTION]: this.#currentExtracted(undefined, filter).map(extractedPath) }
469
+ : allowed;
470
+ }
474
471
  async #updateAndEmbed(store, collections, force) {
475
472
  // Extracted facts are DB projections, not files: never run filesystem sync on them.
476
473
  const analysisStore = store;
477
474
  let changedDocuments = 0;
478
475
  try {
479
- const update = await store.update({ collections: collections ? [...collections] : this.#qmdSources().map(source => source.collection) });
476
+ const update = await store.update({ collections: [...(collections ?? this.#indexCollections)] });
480
477
  changedDocuments = update.updated + update.removed;
481
478
  if ((update.indexed + changedDocuments > 0 || update.needsEmbedding > 0 || force) && analysisStore.internal) {
482
479
  markMemoryAnalysisStale(analysisStore.internal.db);
@@ -517,7 +514,7 @@ export class QmdMemoryManager {
517
514
  const run = async () => {
518
515
  const store = await this.#getStore();
519
516
  this.#dirty = true;
520
- const collections = affectedCollections ?? this.#qmdSources().filter((source) => source.kind !== "sessions").map(source => source.collection);
517
+ const collections = affectedCollections ?? this.#indexSources.filter((source) => source.kind !== "sessions").map(source => source.collection);
521
518
  await this.#updateAndEmbed(store, collections.length ? collections : undefined, params?.force);
522
519
  await this.#refreshIndexStatus(store);
523
520
  };
@@ -565,7 +562,7 @@ export class QmdMemoryManager {
565
562
  await this.#analysisRunner({
566
563
  executable: this.#analysisExecutable,
567
564
  dbPath: this.#dbPath,
568
- collections: this.#analysisCollectionNames(),
565
+ collections: this.#indexCollections,
569
566
  options,
570
567
  signal,
571
568
  });
@@ -810,19 +807,9 @@ export class QmdMemoryManager {
810
807
  if (sessions && collections.includes(sessions.collection)) {
811
808
  await this.#refreshSessionMetadata();
812
809
  }
813
- let allowedPaths = opts?.sessionFilter && sessions && collections.includes(sessions.collection)
814
- ? sessionAllowedPaths(this.#sessionMetadata, sessions.collection, opts.sessionFilter)
815
- : undefined;
816
810
  const store = await this.#getStore();
817
811
  opts?.signal?.throwIfAborted();
818
- const currentRecords = (paths) => {
819
- if (!collections.includes(EXTRACTED_COLLECTION))
820
- return [];
821
- return this.#currentExtracted(paths, opts?.sessionFilter);
822
- };
823
- if (collections.includes(EXTRACTED_COLLECTION)) {
824
- allowedPaths = { ...allowedPaths, [EXTRACTED_COLLECTION]: currentRecords().map(extractedPath) };
825
- }
812
+ const allowedPaths = this.#allowedPaths(collections, opts?.sessionFilter);
826
813
  const hits = await store.vsearch(query, {
827
814
  collection: collections,
828
815
  limit: opts?.maxResults ?? 5,
@@ -850,13 +837,7 @@ export class QmdMemoryManager {
850
837
  if (timings && !signal?.aborted)
851
838
  timings.metadataReloads = Number(reloaded);
852
839
  }
853
- const sessions = this.#sessions;
854
- let allowed = opts.sessionFilter && sessions && collections.includes(sessions.collection)
855
- ? sessionAllowedPaths(this.#sessionMetadata, sessions.collection, opts.sessionFilter) : undefined;
856
- if (collections.includes(EXTRACTED_COLLECTION)) {
857
- allowed = { ...allowed, [EXTRACTED_COLLECTION]: this.#currentExtracted(undefined, opts.sessionFilter).map(extractedPath) };
858
- }
859
- return allowed;
840
+ return this.#allowedPaths(collections, opts.sessionFilter);
860
841
  });
861
842
  const store = await timeStage("storeSetupMs", timings, signal, () => this.#getAnalysisStore());
862
843
  const hits = new Map();
@@ -890,7 +871,7 @@ export class QmdMemoryManager {
890
871
  async #renderSearchHits(hits, store, opts, whisperer = false) {
891
872
  const tokenizer = store.internal?.llm;
892
873
  const results = [];
893
- const current = new Map(this.#currentExtracted(hits.map(hit => hit.file), opts?.sessionFilter).map(r => [`qmd://${EXTRACTED_COLLECTION}/${extractedPath(r)}`, r]));
874
+ const current = new Map(this.#currentExtracted(hits.map(hit => hit.file), opts?.sessionFilter).map(r => [extractedUri(r), r]));
894
875
  for (const hit of hits) {
895
876
  opts?.signal?.throwIfAborted();
896
877
  // Proactive hints must retain the entire matched chunk, even when expanded
@@ -917,7 +898,7 @@ export class QmdMemoryManager {
917
898
  // Never apply offsets from a newer projection to an older indexed snapshot.
918
899
  const messages = corpus === "sessions"
919
900
  ? projection?.messages && projection.documentPath === relativePath &&
920
- projection.projectionHash === createHash("sha256").update(hit.body).digest("hex")
901
+ projection.projectionHash === projectionHash(hit.body)
921
902
  ? projection.messages : parseSessionMessageSpans(hit.body)
922
903
  : undefined;
923
904
  const messageTimestamp = messages
@@ -945,12 +926,11 @@ export class QmdMemoryManager {
945
926
  });
946
927
  }
947
928
  // Expansion above can yield; recheck only derived hits once more before returning.
948
- const finalPaths = new Set(this.#currentExtracted(results.map(hit => hit.path), opts?.sessionFilter).map(r => `qmd://${EXTRACTED_COLLECTION}/${extractedPath(r)}`));
949
- return results.filter(hit => !hit.path.startsWith(`qmd://${EXTRACTED_COLLECTION}/`) || finalPaths.has(hit.path));
929
+ const finalPaths = new Set(this.#currentExtracted(results.map(hit => hit.path), opts?.sessionFilter).map(extractedUri));
930
+ return results.filter(hit => !hit.path.startsWith(EXTRACTED_PREFIX) || finalPaths.has(hit.path));
950
931
  }
951
932
  async searchSkills(query, minScore, limit) {
952
- const collections = this.#skillCollectionNames();
953
- if (collections.length === 0)
933
+ if (!this.#hasSkills)
954
934
  return [];
955
935
  await this.#operationChain;
956
936
  const store = await this.#getStore();
@@ -961,29 +941,22 @@ export class QmdMemoryManager {
961
941
  let skillIndex = this.#skillIndex;
962
942
  if (!skillIndex) {
963
943
  const pending = (async () => {
964
- const sourceOrder = new Map([...this.#sources.keys()].map((collection, index) => [collection, index]));
965
- const metadata = new Map();
944
+ // Sources iterate in configuration order, so the first skill of a name wins.
945
+ const byName = new Map();
966
946
  for (const source of this.#sources.values()) {
967
947
  if (source.kind !== "skills")
968
948
  continue;
969
949
  for (const document of readSkillDocuments(source)) {
970
950
  const name = frontmatterValue(document.body, "name") || basename(dirname(document.path));
971
- const description = frontmatterValue(document.body, "description") ?? "";
972
951
  const key = name.toLowerCase();
973
- const order = sourceOrder.get(source.collection) ?? Number.MAX_SAFE_INTEGER;
974
- const current = metadata.get(key);
975
- if (!current || order < current.sourceOrder) {
976
- metadata.set(key, {
977
- candidate: { name, description, path: document.path },
978
- description,
979
- sourceOrder: order,
980
- });
981
- }
952
+ if (byName.has(key))
953
+ continue;
954
+ byName.set(key, { name, description: frontmatterValue(document.body, "description") ?? "", path: document.path });
982
955
  }
983
956
  }
984
- const skills = [...metadata.values()];
985
- const embeddings = await llm.embedBatch(skills.map(({ candidate, description }) => formatDocForEmbedding(description, candidate.name, llm.embedModelName)));
986
- return skills.flatMap(({ candidate }, index) => {
957
+ const skills = [...byName.values()];
958
+ const embeddings = await llm.embedBatch(skills.map((candidate) => formatDocForEmbedding(candidate.description, candidate.name, llm.embedModelName)));
959
+ return skills.flatMap((candidate, index) => {
987
960
  const embedding = embeddings[index]?.embedding;
988
961
  return embedding ? [{ ...candidate, score: 0, embedding }] : [];
989
962
  });
@@ -1009,10 +982,8 @@ export class QmdMemoryManager {
1009
982
  .slice(0, limit);
1010
983
  }
1011
984
  async readFile(params) {
1012
- if (params.relPath.startsWith(`qmd://${EXTRACTED_COLLECTION}/`)) {
1013
- const record = this.#extraction?.enabled && this.#extraction.publish
1014
- ? extractedRecords(this.#curationPath, [params.relPath.slice(`qmd://${EXTRACTED_COLLECTION}/`.length)]).find(r => this.#extraction.chatTypes.includes(r.metadata.chatType) &&
1015
- params.relPath === `qmd://${EXTRACTED_COLLECTION}/${extractedPath(r)}`) : undefined;
985
+ if (params.relPath.startsWith(EXTRACTED_PREFIX)) {
986
+ const record = this.#currentExtracted([params.relPath]).find(r => params.relPath === extractedUri(r));
1016
987
  return record ? buildReadResult({ content: `${record.text}\nObserved: ${new Date(record.observedAt).toISOString()}\nSource: ${extractedHit(record, 1).citation}`,
1017
988
  path: params.relPath, from: params.from, lines: params.lines }) : { status: "not_found", text: "", path: params.relPath };
1018
989
  }
@@ -2,5 +2,8 @@ import { DatabaseSync } from "node:sqlite";
2
2
  export declare const MEMORY_DATABASE = "unblock-memory.sqlite";
3
3
  /** Separate domain stores share settings, not a monolithic data-access API. */
4
4
  export declare function openMemoryDatabase(path: string): DatabaseSync;
5
+ /** Runs synchronous writes atomically; never pass an async callback. */
6
+ export declare function immediateTransaction<T>(db: DatabaseSync, fn: () => T): T;
7
+ export declare function tableExists(db: DatabaseSync, name: string): boolean;
5
8
  /** File existence no longer tells us which feature has initialized its tables. */
6
9
  export declare function hasMemoryTable(path: string, table: string): boolean;
@@ -1,6 +1,7 @@
1
1
  import { closeSync, constants, existsSync, fchmodSync, lstatSync, mkdirSync, openSync } from "node:fs";
2
2
  import { basename, dirname, join } from "node:path";
3
3
  import { DatabaseSync } from "node:sqlite";
4
+ // Loaded by the Inside Out baseline worker (see inside-out-store.ts): keep this module free of `openclaw`.
4
5
  export const MEMORY_DATABASE = "unblock-memory.sqlite";
5
6
  const legacyStores = [
6
7
  { file: "curation.sqlite", component: "curation", tables: [
@@ -66,6 +67,19 @@ export function openMemoryDatabase(path) {
66
67
  throw error;
67
68
  }
68
69
  }
70
+ /** Runs synchronous writes atomically; never pass an async callback. */
71
+ export function immediateTransaction(db, fn) {
72
+ db.exec("BEGIN IMMEDIATE");
73
+ try {
74
+ const result = fn();
75
+ db.exec("COMMIT");
76
+ return result;
77
+ }
78
+ catch (error) {
79
+ db.exec("ROLLBACK");
80
+ throw error;
81
+ }
82
+ }
69
83
  function consolidate(db, directory) {
70
84
  const completed = () => {
71
85
  const version = db.prepare("SELECT version FROM memory_schema WHERE component='storage'").get()?.version;
@@ -159,6 +173,9 @@ function consolidate(db, directory) {
159
173
  db.exec(`DETACH DATABASE ${identifier(alias)}`);
160
174
  }
161
175
  }
176
+ export function tableExists(db, name) {
177
+ return Boolean(db.prepare("SELECT 1 FROM sqlite_schema WHERE type='table' AND name=?").get(name));
178
+ }
162
179
  /** File existence no longer tells us which feature has initialized its tables. */
163
180
  export function hasMemoryTable(path, table) {
164
181
  if (!existsSync(path) && !(basename(path) === MEMORY_DATABASE &&
@@ -166,7 +183,7 @@ export function hasMemoryTable(path, table) {
166
183
  return false;
167
184
  const db = openMemoryDatabase(path);
168
185
  try {
169
- return Boolean(db.prepare("SELECT 1 FROM sqlite_schema WHERE type='table' AND name=?").get(table));
186
+ return tableExists(db, table);
170
187
  }
171
188
  finally {
172
189
  db.close();
@@ -1,7 +1,5 @@
1
1
  import { parseAgentSessionKey } from "openclaw/plugin-sdk/routing";
2
- function nonBlank(value) {
3
- return typeof value === "string" && value.trim() ? value.trim() : undefined;
4
- }
2
+ import { nonBlank } from "./guards.js";
5
3
  function identifier(value) {
6
4
  if (typeof value === "number" && Number.isFinite(value))
7
5
  return String(value);
@@ -101,10 +99,9 @@ export function registerPeopleHooks(api, stores, config) {
101
99
  const identityKey = promptIdentityKey(sessionKey, accountScope, externalId);
102
100
  const mappedThreadKey = threadByRun.get(runId);
103
101
  const pendingThreadKey = mappedThreadKey ? undefined : pendingThreadByIdentity.get(identityKey);
104
- if (!mappedThreadKey && pendingThreadByIdentity.has(identityKey)) {
102
+ if (!mappedThreadKey)
105
103
  pendingThreadByIdentity.delete(identityKey);
106
- }
107
- const threadKey = mappedThreadKey ?? pendingThreadKey ?? undefined;
104
+ const threadKey = mappedThreadKey ?? pendingThreadKey;
108
105
  if (!threadKey)
109
106
  return;
110
107
  if (typeof pendingThreadKey === "string") {
@@ -44,7 +44,6 @@ export function registerPeoplePrimerTool(api, runtime, stores, config) {
44
44
  try {
45
45
  combined.throwIfAborted();
46
46
  const apiKey = await abortable(resolveTypeSafeApiKey(config.typesafe), combined);
47
- combined.throwIfAborted();
48
47
  if (!apiKey)
49
48
  return jsonResult({ status: "unavailable", reason: "TypeSafe API key not configured" });
50
49
  const store = stores.get(active.agentId);
@@ -55,7 +54,6 @@ export function registerPeoplePrimerTool(api, runtime, stores, config) {
55
54
  if (identities.length && identities.every(i => i.isBot === true || i.isDeactivated))
56
55
  return jsonResult({ status: "unavailable", reason: "No active human identity" });
57
56
  const { manager } = await abortable(runtime.getMemorySearchManager(active), combined);
58
- combined.throwIfAborted();
59
57
  if (!manager)
60
58
  return jsonResult({ status: "unavailable", reason: "Memory unavailable" });
61
59
  const agentName = resolveAgentIdentity(active.cfg, active.agentId)?.name?.trim() || suppliedName?.trim() || "the assistant";
@@ -1,12 +1,9 @@
1
- import { createHash } from "node:crypto";
2
- import { Type } from "typebox";
3
1
  import { Value } from "typebox/value";
4
- import { requestTypeSafe, TYPESAFE_NOUL_SCHEMA } from "./typesafe-client.js";
5
- import { TYPESAFE_REVIEW_MODEL } from "./typesafe-review.js";
2
+ import { requestTypeSafe, TYPESAFE_MODEL, TYPESAFE_NOUL_ANSWERS_SCHEMA as answerSchema } from "./typesafe-client.js";
6
3
  import { abortable } from "./abortable.js";
4
+ import { jsonHash } from "./json-hash.js";
7
5
  const VERSION = "people-primer-background-v4";
8
6
  const MAX_EXCERPT_CHARS = 6000;
9
- const answerSchema = Type.Object({ answers: Type.Record(Type.String(), TYPESAFE_NOUL_SCHEMA) });
10
7
  function questionsFor(name, agent) {
11
8
  return [
12
9
  { id: "role", question: `Who is ${name}? What is their explicitly stated role and organization?` },
@@ -102,7 +99,7 @@ export async function primePersonDossier(params) {
102
99
  false: "Only a topic/name match, activity summary, behavioral profile, ambiguous attribution or no explicit background answer." },
103
100
  }])),
104
101
  };
105
- const key = createHash("sha256").update(JSON.stringify([VERSION, TYPESAFE_REVIEW_MODEL, person.id, state, questions])).digest("hex");
102
+ const key = jsonHash([VERSION, TYPESAFE_MODEL, person.id, state, questions]);
106
103
  const expectedKeys = Object.keys(questions);
107
104
  const valid = (value) => Value.Check(answerSchema, value) &&
108
105
  Object.keys(value.answers).length === expectedKeys.length && expectedKeys.every(k => Object.hasOwn(value.answers, k));
@@ -153,7 +153,8 @@ export declare class PeopleStore {
153
153
  }[];
154
154
  };
155
155
  getDossierRevision(personId: string): string | null;
156
- replaceDossier(personId: string, reasonInput: string, input: unknown, expectedRevision?: string | null): PersonDossier;
156
+ /** Returns undefined when the person does not exist. */
157
+ replaceDossier(personId: string, reasonInput: string, input: unknown, expectedRevision?: string | null): PersonDossier | undefined;
157
158
  deleteDossier(personId: string, reasonInput: string): boolean;
158
159
  getWhisperReceipt(threadKey: string, personId: string): {
159
160
  runId: string;