hippo-memory 3.4.0 → 3.5.1

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 (95) hide show
  1. package/README.md +4 -4
  2. package/dist/api/callers.d.ts +4 -1
  3. package/dist/api/context/context-plan.js +3 -0
  4. package/dist/api/context/context-pools.js +2 -0
  5. package/dist/api/objects/object-kinds.d.ts +1 -4
  6. package/dist/api/objects/object-kinds.js +1 -5
  7. package/dist/api/session-end.d.ts +3 -2
  8. package/dist/api/session-end.js +8 -4
  9. package/dist/api/sharing.d.ts +4 -3
  10. package/dist/api/sharing.js +2 -2
  11. package/dist/api/sleep/auto-sleep.d.ts +3 -2
  12. package/dist/api/sleep/auto-sleep.js +16 -3
  13. package/dist/api/sleep/one-sleep.d.ts +23 -0
  14. package/dist/api/sleep/one-sleep.js +53 -0
  15. package/dist/api/sleep/sleep.d.ts +5 -0
  16. package/dist/api/sleep/sleep.js +2 -1
  17. package/dist/base/config/config-keys.js +1 -0
  18. package/dist/base/config/config.d.ts +2 -0
  19. package/dist/base/config/config.js +1 -0
  20. package/dist/base/embeddings/local.d.ts +1 -1
  21. package/dist/base/embeddings/local.js +2 -3
  22. package/dist/base/ports/store/capture.d.ts +2 -0
  23. package/dist/base/ports/store/consolidation.d.ts +15 -0
  24. package/dist/base/ports/store/consolidation.js +2 -0
  25. package/dist/base/ports/store/context-reads.d.ts +2 -0
  26. package/dist/base/ports/store/objects.d.ts +15 -4
  27. package/dist/base/ports/store/store-effects.d.ts +2 -0
  28. package/dist/base/ports/store.d.ts +1 -1
  29. package/dist/base/scope/read-admission.d.ts +2 -0
  30. package/dist/base/scope/read-admission.js +8 -2
  31. package/dist/base/util/version.d.ts +1 -1
  32. package/dist/base/util/version.js +1 -1
  33. package/dist/db/migrations/index.d.ts +1 -1
  34. package/dist/db/migrations/index.js +3 -1
  35. package/dist/db/migrations/v63.d.ts +3 -0
  36. package/dist/db/migrations/v63.js +9 -0
  37. package/dist/domain/consolidate/merge.js +6 -6
  38. package/dist/domain/consolidate/tombstones.d.ts +3 -4
  39. package/dist/domain/consolidate/tombstones.js +3 -3
  40. package/dist/domain/objects/decisions.d.ts +4 -7
  41. package/dist/domain/objects/decisions.js +1 -9
  42. package/dist/domain/objects/descriptor.d.ts +2 -0
  43. package/dist/domain/objects/lifecycle.js +8 -2
  44. package/dist/domain/sharing/share.d.ts +16 -4
  45. package/dist/domain/sharing/share.js +33 -17
  46. package/dist/entry/store-kit.js +2 -1
  47. package/dist/infra/local-embedder.js +14 -2
  48. package/dist/infra/spool-claims.d.ts +2 -2
  49. package/dist/infra/spool-claims.js +4 -3
  50. package/dist/infra/spool-import.js +1 -1
  51. package/dist/infra/spool-record.d.ts +3 -1
  52. package/dist/store/sqlite/capture/compaction-hooks.js +14 -6
  53. package/dist/store/sqlite/capture/spool-request-id.d.ts +3 -0
  54. package/dist/store/sqlite/capture/spool-request-id.js +12 -0
  55. package/dist/store/sqlite/consolidation/consolidation.js +2 -0
  56. package/dist/store/sqlite/consolidation/sleep-lock.d.ts +4 -0
  57. package/dist/store/sqlite/consolidation/sleep-lock.js +69 -0
  58. package/dist/store/sqlite/entries/entry-filter.js +1 -2
  59. package/dist/store/sqlite/entries/entry-row.js +5 -1
  60. package/dist/store/sqlite/entries/entry-writes.js +3 -10
  61. package/dist/store/sqlite/entries/raw-archive.d.ts +2 -1
  62. package/dist/store/sqlite/entries/raw-archive.js +12 -3
  63. package/dist/store/sqlite/recall/candidates.js +2 -7
  64. package/dist/store/sqlite/recall/search-rows.d.ts +3 -0
  65. package/dist/store/sqlite/recall/search-rows.js +22 -6
  66. package/dist/store/sqlite/records/object-rows.d.ts +2 -0
  67. package/dist/store/sqlite/records/object-rows.js +5 -1
  68. package/dist/store/sqlite/records/object-writes.d.ts +3 -0
  69. package/dist/store/sqlite/records/object-writes.js +43 -1
  70. package/dist/store/sqlite/review/conflicts.js +3 -4
  71. package/dist/store/sqlite/runtime/rule-sql.d.ts +1 -0
  72. package/dist/store/sqlite/runtime/rule-sql.js +2 -0
  73. package/dist/surface/capture/session-worker.d.ts +3 -2
  74. package/dist/surface/capture/session-worker.js +36 -10
  75. package/dist/surface/cli/api-context.js +2 -1
  76. package/dist/surface/cli/client.d.ts +6 -5
  77. package/dist/surface/cli/client.js +50 -19
  78. package/dist/surface/cli/decisions.js +16 -17
  79. package/dist/surface/cli/hooks/session-end-worker.js +3 -2
  80. package/dist/surface/cli/install-steps.js +99 -13
  81. package/dist/surface/cli/memory-writes.js +3 -2
  82. package/dist/surface/cli/sleep-render.js +7 -0
  83. package/dist/surface/cli/sleep.d.ts +3 -2
  84. package/dist/surface/cli/sleep.js +10 -4
  85. package/dist/surface/cli/transfer.js +6 -3
  86. package/dist/surface/hooks-install/codex-wrapper.js +52 -11
  87. package/dist/surface/hooks-install/rules/hook-blocks.js +9 -2
  88. package/dist/surface/mcp/admin-tools.js +5 -2
  89. package/dist/surface/server/routes/decisions.js +2 -2
  90. package/dist/surface/server/sleep-child.js +5 -4
  91. package/dist/surface/server/sleep-offload.js +36 -25
  92. package/extensions/openclaw-plugin/openclaw.plugin.json +1 -1
  93. package/extensions/openclaw-plugin/package.json +1 -1
  94. package/openclaw.plugin.json +1 -1
  95. package/package.json +1 -1
@@ -1,5 +1,5 @@
1
1
  import type { Migration } from './types.js';
2
- export declare const CURRENT_SCHEMA_VERSION = 62;
2
+ export declare const CURRENT_SCHEMA_VERSION = 63;
3
3
  /** Every schema migration in version order; runMigrations applies each one above the stored
4
4
  * version. */
5
5
  export declare const MIGRATIONS: Migration[];
@@ -60,7 +60,8 @@ import { v59 } from './v59.js';
60
60
  import { v60 } from './v60.js';
61
61
  import { v61 } from './v61.js';
62
62
  import { v62 } from './v62.js';
63
- export const CURRENT_SCHEMA_VERSION = 62;
63
+ import { v63 } from './v63.js';
64
+ export const CURRENT_SCHEMA_VERSION = 63;
64
65
  /** Every schema migration in version order; runMigrations applies each one above the stored
65
66
  * version. */
66
67
  export const MIGRATIONS = [
@@ -126,5 +127,6 @@ export const MIGRATIONS = [
126
127
  v60,
127
128
  v61,
128
129
  v62,
130
+ v63,
129
131
  ];
130
132
  //# sourceMappingURL=index.js.map
@@ -0,0 +1,3 @@
1
+ import type { Migration } from './types.js';
2
+ export declare const v63: Migration;
3
+ //# sourceMappingURL=v63.d.ts.map
@@ -0,0 +1,9 @@
1
+ export const v63 = {
2
+ version: 63,
3
+ up: (db) => {
4
+ // Skip a NULL or unknown kind: trg_memories_kind_check_update is not column-scoped and would abort the open.
5
+ db.exec(`UPDATE memories SET superseded_by = NULL WHERE superseded_by = '' ` +
6
+ `AND kind IN ('raw','distilled','superseded','archived')`);
7
+ },
8
+ };
9
+ //# sourceMappingURL=v63.js.map
@@ -135,8 +135,8 @@ async function partitionMergeCandidates(run) {
135
135
  /** Returns how many clusters were skipped because their merged text matches a rejected value. */
136
136
  export async function mergePass(run) {
137
137
  const used = new Set();
138
- // The rejection guard reuses the run's tombstone checks; a dry-run never reaches
139
- // batchWriteAndDelete's guard bypass, so it has nothing to protect there.
138
+ // The rejection guard reuses the run's tombstone checks; a dry run reads them too, so it counts a
139
+ // refused cluster as refused though it never reaches batchWriteAndDelete's guard bypass.
140
140
  let mergesSkippedRejected = 0;
141
141
  for (const bucket of (await partitionMergeCandidates(run)).values()) {
142
142
  const { ids, lengths } = bucket;
@@ -179,9 +179,9 @@ async function mergeCluster({ run, partition, cluster, related, used, }) {
179
179
  const mergedContent = mergeContents(cluster);
180
180
  // Build the semantic entry FIRST (createMemory is cheap and pure) so the tombstone check below
181
181
  // runs under the partition's tenant, the one every cluster member shares and the row will land
182
- // in.
183
- const semantic = dryRun ? null : semanticSummary(mergedContent, cluster, partition, run);
184
- if (semantic && (await mergeRejected({ run, semantic, cluster, related, used })))
182
+ // in. A dry run builds it too, so it refuses the cluster a real run would.
183
+ const semantic = semanticSummary(mergedContent, cluster, partition, run);
184
+ if (await mergeRejected({ run, semantic, cluster, related, used }))
185
185
  return false;
186
186
  for (const e of cluster)
187
187
  used.add(e.id);
@@ -191,7 +191,7 @@ async function mergeCluster({ run, partition, cluster, related, used, }) {
191
191
  count: cluster.length,
192
192
  preview: mergedContent.slice(0, MERGE_DETAIL_PREVIEW_CHARS),
193
193
  });
194
- if (!dryRun && semantic) {
194
+ if (!dryRun) {
195
195
  run.pendingWrites.push(semantic);
196
196
  run.units.push([semantic.id, ...cluster.map((e) => e.id)]);
197
197
  result.semanticCreated++;
@@ -2,10 +2,9 @@ import type { StoreWith } from '../../base/ports/store.js';
2
2
  import type { RejectedValueRow } from '../../base/ports/store/rejections.js';
3
3
  import type { AppendAuditOptions } from '../../base/ports/store/types.js';
4
4
  export interface TombstoneChecks {
5
- /** The tenant's tombstone for `digest`; null when there is none, and always under dryRun. */
5
+ /** The tenant's tombstone for `digest`; null when there is none. */
6
6
  find(tenantId: string, digest: string): Promise<RejectedValueRow | null>;
7
- /** The digests among `digests` the tenant holds a tombstone for, in one store call; none under
8
- * dryRun, as `find`. */
7
+ /** The digests among `digests` the tenant holds a tombstone for, in one store call. */
9
8
  rejectedAmong(tenantId: string, digests: readonly string[]): Promise<Set<string>>;
10
9
  /** One audit row; nothing under dryRun. */
11
10
  audit(event: AppendAuditOptions): Promise<void>;
@@ -13,6 +12,6 @@ export interface TombstoneChecks {
13
12
  * stands without its row. */
14
13
  auditOrCount(event: AppendAuditOptions): Promise<void>;
15
14
  }
16
- /** The checks of one sleep on `store`; under dryRun no call reaches the store. */
15
+ /** The checks of one sleep on `store`; under dryRun the lookups read and no audit row is written. */
17
16
  export declare function tombstoneChecks(store: StoreWith<'consolidation'>, dryRun: boolean): TombstoneChecks;
18
17
  //# sourceMappingURL=tombstones.d.ts.map
@@ -1,14 +1,14 @@
1
1
  import { reportAuditWriteFailure } from '../../base/records/audit-report.js';
2
- /** The checks of one sleep on `store`; under dryRun no call reaches the store. */
2
+ /** The checks of one sleep on `store`; under dryRun the lookups read and no audit row is written. */
3
3
  export function tombstoneChecks(store, dryRun) {
4
4
  const audit = async (event) => {
5
5
  if (!dryRun)
6
6
  await store.appendAuditEvents([event]);
7
7
  };
8
8
  return {
9
- find: async (tenantId, digest) => dryRun ? null : ((await store.consolidation.rejected(tenantId, [digest]))[0] ?? null),
9
+ find: async (tenantId, digest) => (await store.consolidation.rejected(tenantId, [digest]))[0] ?? null,
10
10
  async rejectedAmong(tenantId, digests) {
11
- if (dryRun || digests.length === 0)
11
+ if (digests.length === 0)
12
12
  return new Set();
13
13
  return new Set((await store.consolidation.rejected(tenantId, digests)).map((row) => row.digest));
14
14
  },
@@ -3,9 +3,8 @@
3
3
  * `active` despite memory decay. The memory mirror (memory_id NULLABLE, ON DELETE SET NULL) is for
4
4
  * recall only; saveDecision commits both in one `objects` transaction.
5
5
  */
6
- import type { MemoryEntry } from '../../base/memory/entry.js';
7
6
  import type { KeysetPosition } from '../../base/util/keyset.js';
8
- import type { EntryWrites, Objects } from '../../base/ports/store.js';
7
+ import type { Objects } from '../../base/ports/store.js';
9
8
  import type { SavableDescriptor } from './descriptor.js';
10
9
  import type { Decision, DecisionStatus } from '../../base/records/object-types.js';
11
10
  export type { Decision, DecisionStatus } from '../../base/records/object-types.js';
@@ -16,6 +15,9 @@ export interface SaveDecisionOptions {
16
15
  /** Table id of an ACTIVE decision this one supersedes; the CLI resolves a `--supersedes <memory-id>` via
17
16
  * resolveActiveDecisionIdByMemory, HTTP/SDK pass the table id. */
18
17
  supersedesDecisionId?: number;
18
+ /** A memory of the tenant the save also weakens, for a `--supersedes <memory-id>` that names one
19
+ * no active decision backs; the save is refused when the tenant holds none. */
20
+ weakensMemoryId?: string;
19
21
  /** Extra memory tags merged after ['decision'] (the CLI passes path-context tags; HTTP/SDK
20
22
  * pass none). */
21
23
  extraTags?: string[];
@@ -27,11 +29,6 @@ export interface ListDecisionsOptions {
27
29
  after?: KeysetPosition;
28
30
  }
29
31
  export declare const DECISION: SavableDescriptor<'decision', SaveDecisionOptions>;
30
- /**
31
- * Weaken the memory a new decision replaces, once the save has committed: marked stale, tagged
32
- * `superseded`, and its half-life halved to a day at least the first time only.
33
- */
34
- export declare function weakenSupersededMemory(writes: EntryWrites, entry: MemoryEntry, actor?: string): Promise<void>;
35
32
  export declare function loadDecisions(objects: Objects, tenantId: string, opts?: ListDecisionsOptions): Promise<Decision[]>;
36
33
  /** Resolve a `--supersedes <memory-id>` to the table id of the ACTIVE decision backed by that memory, or null.
37
34
  * Exported so the CLI's backward-compat path is testable at the store layer. */
@@ -3,12 +3,10 @@
3
3
  * `active` despite memory decay. The memory mirror (memory_id NULLABLE, ON DELETE SET NULL) is for
4
4
  * recall only; saveDecision commits both in one `objects` transaction.
5
5
  */
6
- import { markStale, SUPERSEDED_TAG } from '../../base/memory/stale-mark.js';
7
6
  import { assertTenantId } from '../../base/scope/tenant-id.js';
8
7
  import { MAX_SHORT_FIELD_LEN } from '../../base/util/limits.js';
9
8
  import { requireText } from './fields.js';
10
9
  import { listObjects } from './lifecycle.js';
11
- import { CLI_ACTOR } from '../../base/scope/actor.js';
12
10
  export const VALID_DECISION_STATES = new Set([
13
11
  'active',
14
12
  'superseded',
@@ -27,17 +25,11 @@ export const DECISION = {
27
25
  content: opts.context ? `${decisionText}\n\nContext: ${opts.context}` : decisionText,
28
26
  tags: opts.extraTags ?? [],
29
27
  supersedesId: opts.supersedesDecisionId,
28
+ weakensMemoryId: opts.weakensMemoryId,
30
29
  at: now.toISOString(),
31
30
  };
32
31
  },
33
32
  };
34
- /**
35
- * Weaken the memory a new decision replaces, once the save has committed: marked stale, tagged
36
- * `superseded`, and its half-life halved to a day at least the first time only.
37
- */
38
- export function weakenSupersededMemory(writes, entry, actor = CLI_ACTOR) {
39
- return writes.writeEntry({ entry: markStale(entry, SUPERSEDED_TAG), actor });
40
- }
41
33
  export function loadDecisions(objects, tenantId, opts = {}) {
42
34
  return listObjects(objects, DECISION, tenantId, opts);
43
35
  }
@@ -22,6 +22,8 @@ export interface ObjectDraft<K extends SavableKind> {
22
22
  readonly supersedesId: number | undefined;
23
23
  /** What changed; stored only on a versioned successor. */
24
24
  readonly changeSummary?: string;
25
+ /** A decision only: a memory the save also weakens, beside the one the replaced row mirrors. */
26
+ readonly weakensMemoryId?: string;
25
27
  /** Read once the checks pass, so one instant stamps everything the save writes. */
26
28
  readonly at: string;
27
29
  }
@@ -3,7 +3,7 @@
3
3
  // whatever store the caller holds: the CLI's, a served one, or a test's. The tenant, the fields and
4
4
  // the list status are checked first, so a bad request fails before a store is asked.
5
5
  import { DEFAULT_LIST_LIMIT } from '../../base/util/limits.js';
6
- import { BadRequestError, ConflictError, NotFoundError } from '../../base/errors/api-errors.js';
6
+ import { BadRequestError, ConflictError, memoryNotFoundText, NotFoundError, } from '../../base/errors/api-errors.js';
7
7
  import { createMemory, Layer } from '../../base/memory/entry.js';
8
8
  import { isObjectRefusal, } from '../../base/records/object-types.js';
9
9
  import { assertTenantId } from '../../base/scope/tenant-id.js';
@@ -73,12 +73,16 @@ function objectSave(site, kind, draft) {
73
73
  fields: draft.fields,
74
74
  supersedesId: draft.supersedesId,
75
75
  changeSummary: draft.changeSummary,
76
+ weakensMemoryId: draft.weakensMemoryId,
76
77
  actor: site.actor,
77
78
  at: draft.at,
78
79
  };
79
80
  }
81
+ function isSaveRefusal(written) {
82
+ return 'refused' in written;
83
+ }
80
84
  function saved(d, tenantId, replaced, written) {
81
- if (!isObjectRefusal(written))
85
+ if (!isSaveRefusal(written))
82
86
  return written;
83
87
  switch (written.refused) {
84
88
  case 'missing':
@@ -89,6 +93,8 @@ function saved(d, tenantId, replaced, written) {
89
93
  throw new ConflictError(`${d.label} ${replaced} could not be superseded (no longer active or self-reference).`);
90
94
  case 'vanished':
91
95
  throw new Error(`failed to reload saved ${d.label} row`);
96
+ case 'memory_missing':
97
+ throw new NotFoundError(memoryNotFoundText(written.memoryId));
92
98
  }
93
99
  }
94
100
  /** Creates an object, or the version that replaces the one its options name, with its mirror
@@ -18,17 +18,29 @@ export declare const AUTO_SHARE_MIN_SCORE = 0.6;
18
18
  /** Estimate how well a memory would transfer to other projects.
19
19
  * Returns 0..1 where >0.5 = good candidate for sharing. */
20
20
  export declare function transferScore(entry: MemoryEntry): number;
21
- /** Share a memory to the global store with attribution (source enriched with project path and timestamp).
22
- * Returns the new entry, or null if the transfer score is too low. */
21
+ /** What a hand-run share did: wrote a copy, left a row below the transfer score alone, or found
22
+ * the global store already holding its text (`existingId` is that row). */
23
+ export type ShareOutcome = {
24
+ readonly kind: 'shared';
25
+ readonly entry: MemoryEntry;
26
+ } | {
27
+ readonly kind: 'low-score';
28
+ } | {
29
+ readonly kind: 'already-shared';
30
+ readonly existingId: string;
31
+ };
32
+ /** Share a memory to the global store with attribution (source enriched with project path and
33
+ * timestamp). Writes nothing when the global store holds the text, `force` or not; throws when the
34
+ * row may not be shared. */
23
35
  export declare function shareMemory(local: {
24
36
  readonly store: StoreWith<'folderFiles'>;
25
- }, global: ConfiguredFolder<SharingStore & StoreWith<'vectors' | 'vectorWrites'>>, id: string, options: {
37
+ }, global: ConfiguredFolder<SharingStore & StoreWith<'vectors' | 'vectorWrites' | 'captures'>>, id: string, options: {
26
38
  force?: boolean;
27
39
  tenantId: string;
28
40
  skipEmbed?: boolean;
29
41
  embed: EmbedRun;
30
42
  detached: DetachedWork;
31
- }): Promise<MemoryEntry | null>;
43
+ }): Promise<ShareOutcome>;
32
44
  /** List all projects that contributed memories to the global store, parsed from
33
45
  * 'shared:<project>:' or 'promoted:<path>' sources; ALL_TENANTS is the host-wide view. */
34
46
  export declare function listPeers(global: {
@@ -8,7 +8,7 @@ import { AGENT_MEMORY_SOURCE_PREFIX, AGENT_MEMORY_TAGS, } from '../../base/memor
8
8
  import { isPersonalScope, isQuarantineScope } from '../../base/scope/recall-scope.js';
9
9
  import { detectSecret } from '../../base/util/secret-detect.js';
10
10
  import { embedMemoryDetached, embedAll, folderEmbedTarget, } from '../search/embed-memories.js';
11
- import { duplicateKey, storedTextKeys } from '../../base/util/same-text.js';
11
+ import { duplicateKey, heldTextKeys } from '../../base/util/same-text.js';
12
12
  import { chunked } from '../../base/util/chunked.js';
13
13
  import { ALL_TENANTS } from '../../base/util/tenant.js';
14
14
  import { isReusable } from '../../base/memory/memory-quality.js';
@@ -111,16 +111,25 @@ export function transferScore(entry) {
111
111
  }
112
112
  return Math.min(1, Math.max(0, score));
113
113
  }
114
- /** Share a memory to the global store with attribution (source enriched with project path and timestamp).
115
- * Returns the new entry, or null if the transfer score is too low. */
114
+ /** Share a memory to the global store with attribution (source enriched with project path and
115
+ * timestamp). Writes nothing when the global store holds the text, `force` or not; throws when the
116
+ * row may not be shared. */
116
117
  export async function shareMemory(local, global, id, options) {
117
118
  // Tenant A cannot share tenant B's memory to global: the read finds no row of another tenant.
118
119
  const [entry] = await local.store.entriesByIds([id], options.tenantId);
119
120
  if (!entry)
120
121
  throw new NotFoundError(`Memory not found: ${id}`);
121
- const globalEntry = toGlobalEntry(await local.store.folderFiles.home(), entry, options.force === true, options.embed.clock());
122
- if (!globalEntry)
123
- return null;
122
+ // Built first because it throws for a row that may not be shared, ahead of the held-text answer.
123
+ const globalEntry = toGlobalEntry(await local.store.folderFiles.home(), entry, options.embed.clock());
124
+ // The caller's tenant and the default scope filter, not autoShare's whole-store view: a copy
125
+ // carries its row's tenant, so another tenant's twin is no copy of this row and must stay unnamed.
126
+ const held = await heldGlobalTexts(global.store.captures, [entry.content], options.tenantId);
127
+ const twin = held.get(duplicateKey(entry.content));
128
+ if (twin?.id !== undefined)
129
+ return { kind: 'already-shared', existingId: twin.id };
130
+ const lowScore = transferScore(entry) < SHARE_MIN_SCORE && options.force !== true;
131
+ if (lowScore)
132
+ return { kind: 'low-score' };
124
133
  await global.store.entryWrites.writeEntry({ entry: globalEntry, actor: CLI_ACTOR });
125
134
  // Embed here unless the caller opts out: autoShare sets skipEmbed to batch one embedAll(), since
126
135
  // embedMemory rewrites the whole index per call.
@@ -135,15 +144,11 @@ export async function shareMemory(local, global, id, options) {
135
144
  };
136
145
  embedMemoryDetached(target, globalEntry, options.detached);
137
146
  }
138
- return globalEntry;
147
+ return { kind: 'shared', entry: globalEntry };
139
148
  }
140
- /** The global copy of a local row, or null when its transfer score is too low and `force` is
141
- * off; throws when the row may not be shared. */
142
- function toGlobalEntry(local, entry, force, now) {
149
+ /** The global copy of a local row; throws when the row may not be shared. */
150
+ function toGlobalEntry(local, entry, now) {
143
151
  assertShareable(entry, entry.id);
144
- const score = transferScore(entry);
145
- if (score < SHARE_MIN_SCORE && !force)
146
- return null;
147
152
  // The label keeps the folder name for a user-global row; a NULL row gets `shared::`, which
148
153
  // originFromSource reads as no project.
149
154
  const fallbackName = local.folderName;
@@ -256,20 +261,31 @@ async function* autoSharePages(store, minScore, tenantId) {
256
261
  after = next;
257
262
  } while (after !== null);
258
263
  }
264
+ /** Each text key `texts` have that a row in the global store holds, with the first such row;
265
+ * `tenantId` and `opts` pick which rows count. */
266
+ async function heldGlobalTexts(captures, texts, tenantId, opts) {
267
+ const rows = await captures.textsHolding(tenantId, texts.filter((text) => duplicateKey(text) !== ''), opts);
268
+ const held = new Map();
269
+ for (const row of rows) {
270
+ for (const key of heldTextKeys(row))
271
+ if (!held.has(key))
272
+ held.set(key, row);
273
+ }
274
+ return held;
275
+ }
259
276
  /** The page's rows that share. The global store, the union of every tenant, is asked only for
260
277
  * the rows that may hold a page row's text. */
261
278
  async function pageCandidates(to, page, minScore, stats) {
262
279
  const scored = page.filter((entry) => clearsShareRules(entry, minScore, stats));
263
280
  if (scored.length === 0)
264
281
  return [];
265
- const texts = scored.map((entry) => entry.content).filter((text) => duplicateKey(text) !== '');
266
- const globalKeys = storedTextKeys(await to.textsHolding(ALL_TENANTS, texts, { everyScope: true }));
267
- return scored.filter((entry) => isNewAndClean(entry, globalKeys, stats));
282
+ const held = await heldGlobalTexts(to, scored.map((entry) => entry.content), ALL_TENANTS, { everyScope: true });
283
+ return scored.filter((entry) => isNewAndClean(entry, held, stats));
268
284
  }
269
285
  /** Writes one page of candidates in one transaction; returns the copies written and how many a
270
286
  * tombstone refused. */
271
287
  async function sharePage(local, to, page, now) {
272
- const copies = page.flatMap((entry) => toGlobalEntry(local, entry, true, now) ?? []);
288
+ const copies = page.map((entry) => toGlobalEntry(local, entry, now));
273
289
  const written = new Set(await to.lessonWrites.writeSkippingRejected(copies, CLI_ACTOR));
274
290
  const shared = copies.filter((copy) => written.has(copy.id));
275
291
  return { shared, refused: copies.length - shared.length };
@@ -35,7 +35,8 @@ export { bufferToFloat32, float32ToBuffer } from '../base/util/vector-codec.js';
35
35
  export { replacesIndex } from '../base/embeddings/index-identity.js';
36
36
  // An add-on's ContextReads applies hippo.db's scope, secret, tally and rarest-term rules with the
37
37
  // same code. An add-on's ambientCandidates and summaryWithDescendants admit rows by hippo.db's
38
- // rule.
38
+ // rule. A store that ignores `admit.excludeTags` or `recall.excludeTags` gets only core's after-load
39
+ // filter, so its recent-N or recall pool can come short.
39
40
  export { ambientRefusal, descendantAdmits, } from '../base/scope/read-admission.js';
40
41
  export { SECRET_TAGS } from '../base/util/secret-detect.js';
41
42
  /** An add-on's ambient tallies, scored as hippo.db's are under the environment's eval switches. */
@@ -25,13 +25,25 @@ const INSTALLED_TRANSFORMERS = {
25
25
  installed: () => resolveTransformersPackage() !== null,
26
26
  load: () => importTransformers(),
27
27
  };
28
+ // Sharing the model-load backoff is deliberate: one window, one attempt.
29
+ const INSTALL_RECHECK_MS = MODEL_LOAD_POLICY.backoffMs;
28
30
  /** One pipeline per model for the embedder's life, since a pipeline is expensive to load. */
29
31
  export function createLocalEmbedder(transformers = INSTALLED_TRANSFORMERS) {
30
- let available = null;
32
+ let state = { kind: 'no', retryAt: 0 };
31
33
  const gates = new Map();
32
34
  const pipelines = createModelLoads(MODEL_LOAD_POLICY, warnLoadFailure);
33
35
  const load = (model) => pipelines.load(model, () => createPipeline(transformers, model, gates));
34
- const isAvailable = () => (available ??= transformers.installed());
36
+ const isAvailable = () => {
37
+ if (state.kind === 'yes')
38
+ return true;
39
+ const now = Date.now();
40
+ if (now < state.retryAt)
41
+ return false;
42
+ state = transformers.installed()
43
+ ? { kind: 'yes' }
44
+ : { kind: 'no', retryAt: now + INSTALL_RECHECK_MS };
45
+ return state.kind === 'yes';
46
+ };
35
47
  return {
36
48
  isAvailable,
37
49
  requirePipeline: (model, signal) => waitForPipeline(load(model), signal && gateOf(gates, model).opened, signal),
@@ -35,8 +35,8 @@ interface MoveBadOptions {
35
35
  * busy write puts the claim back.
36
36
  */
37
37
  export declare function moveBad(fsx: SpoolFs, dir: string, claim: string, options: MoveBadOptions): boolean;
38
- /** Removes a claim once the store holds its summary; a claim left behind is imported again, so
39
- * the log says so. */
38
+ /** Removes a claim once the store holds its summary; a claim left behind comes back for another
39
+ * import, so the log names it. */
40
40
  export declare function removeClaim(fsx: SpoolFs, claim: string, name: string, log: Log): void;
41
41
  export {};
42
42
  //# sourceMappingURL=spool-claims.d.ts.map
@@ -54,12 +54,13 @@ export function moveBad(fsx, dir, claim, options) {
54
54
  settle(() => fsx.unlinkSync(claim), log, what);
55
55
  return true;
56
56
  }
57
- /** Removes a claim once the store holds its summary; a claim left behind is imported again, so
58
- * the log says so. */
57
+ /** Removes a claim once the store holds its summary; a claim left behind comes back for another
58
+ * import, so the log names it. */
59
59
  export function removeClaim(fsx, claim, name, log) {
60
60
  const removed = settleCode(() => fsx.unlinkSync(claim), log, `spool file ${name} claim not removed`);
61
61
  if (removed.settled === 'busy') {
62
- log(`spool file ${name} saved; its claim could not be removed (${removed.code}); it will be imported again`);
62
+ log(`spool file ${name} saved; its claim could not be removed (${removed.code}); ` +
63
+ 'a later import reuses the saved record');
63
64
  }
64
65
  }
65
66
  //# sourceMappingURL=spool-claims.js.map
@@ -61,7 +61,7 @@ export async function importFile(options) {
61
61
  };
62
62
  let failure;
63
63
  try {
64
- failure = await importOne(spooled, markRecorded);
64
+ failure = await importOne({ ...spooled, importKey: entry.stem }, markRecorded);
65
65
  }
66
66
  catch (err) {
67
67
  failure = { busy: isStoreBusy(err), message: errorMessage(err), fields: errorFields(err) };
@@ -5,6 +5,8 @@ export interface SpooledCompaction {
5
5
  payload: PostCompactPayload;
6
6
  text: CompactionText;
7
7
  at: Date;
8
+ /** The spool file's stem, which a put-back keeps, so the store can tell two imports of one file. */
9
+ importKey: string;
8
10
  }
9
11
  /**
10
12
  * Records one spooled compaction; it calls `recorded` once the store holds the summary, so the file
@@ -15,5 +17,5 @@ export type SpoolImporter = (spooled: SpooledCompaction, recorded: () => void) =
15
17
  /** The JSON text of one spooled compaction, which parseSpooled reads back. */
16
18
  export declare function spoolBody(tenantId: string, payload: PostCompactPayload, text: CompactionText, at: Date): string;
17
19
  /** null when the text is not a spooled compaction. */
18
- export declare function parseSpooled(text: string, fallbackTenantId: string): SpooledCompaction | null;
20
+ export declare function parseSpooled(text: string, fallbackTenantId: string): Omit<SpooledCompaction, 'importKey'> | null;
19
21
  //# sourceMappingURL=spool-record.d.ts.map
@@ -4,7 +4,8 @@ import { COMPACTION_DB_WAIT_MS, REPLAY_AFTER_MS, TRANSCRIPT_FILL_WINDOW_MS, } fr
4
4
  import { errorFields, errorMessage, log as hippoLog, reportCompactionFailure, } from '../../../base/util/log.js';
5
5
  import { isSqliteBusy } from '../../../db/index.js';
6
6
  import { closeStartedWithoutSummary, nextCompactionStart, openTranscriptRows, stalledSummarizedRows, } from './compaction-rows.js';
7
- import { compactionOrigin, markSnapshotSaved, markSummarized, recordSummary, saveItems, startCompaction, toRecord, } from './compactions-record.js';
7
+ import { compactionByRequest, compactionOrigin, markSnapshotSaved, markSummarized, recordSummary, saveItems, startCompaction, toRecord, } from './compactions-record.js';
8
+ import { spoolRequestId } from './spool-request-id.js';
8
9
  import { answered, bound } from '../runtime/bound.js';
9
10
  import { waitingOpener } from '../runtime/open.js';
10
11
  import { handleNow } from '../runtime/handle-clock.js';
@@ -126,11 +127,18 @@ function saveStalled(db, files, tenantId, opts) {
126
127
  return { saved, notes };
127
128
  }
128
129
  function recordSpooled(db, files, spooled) {
129
- const { id, sessionId, originProject, cwd, items } = recordSummary(db, files, spooled.tenantId, {
130
- meta: spooled.payload,
131
- text: spooled.text,
132
- at: spooled.at,
133
- });
130
+ const { tenantId, payload, importKey } = spooled;
131
+ const requestId = importKey === undefined ? undefined : spoolRequestId(importKey);
132
+ const earlier = requestId === undefined
133
+ ? null
134
+ : compactionByRequest(db, { tenantId, requestId, sessionId: payload.sessionId });
135
+ const { id, sessionId, originProject, cwd, items } = earlier ??
136
+ recordSummary(db, files, tenantId, {
137
+ meta: payload,
138
+ text: spooled.text,
139
+ at: spooled.at,
140
+ caller: { requestId },
141
+ });
134
142
  return { id, sessionId, originProject, cwd, items };
135
143
  }
136
144
  function saveRecordItems(db, files, tenantId, record, opts) {
@@ -0,0 +1,3 @@
1
+ /** `spool:` plus the key; a key too long for an id is hashed, so one key always gives one id. */
2
+ export declare function spoolRequestId(importKey: string): string;
3
+ //# sourceMappingURL=spool-request-id.d.ts.map
@@ -0,0 +1,12 @@
1
+ // The request id a spool file's compaction record carries, so a second import of the file finds it.
2
+ import { createHash } from 'node:crypto';
3
+ import { MAX_ID_LEN } from '../../../base/util/limits.js';
4
+ const PREFIX = 'spool:';
5
+ /** `spool:` plus the key; a key too long for an id is hashed, so one key always gives one id. */
6
+ export function spoolRequestId(importKey) {
7
+ const id = `${PREFIX}${importKey}`;
8
+ if (id.length <= MAX_ID_LEN)
9
+ return id;
10
+ return `${PREFIX}${createHash('sha256').update(importKey).digest('hex')}`;
11
+ }
12
+ //# sourceMappingURL=spool-request-id.js.map
@@ -24,6 +24,7 @@ import { auditRows, dirtySummaries, listL2SummariesPage, settleSummary, } from '
24
24
  import { META_KEY } from '../../../db/meta.js';
25
25
  import { noteRebuildFailures } from './rebuild-holds.js';
26
26
  import { emptyExtractions, noteEmptyExtractions } from './empty-extractions.js';
27
+ import { sleepClaim } from './sleep-lock.js';
27
28
  // A half-life move reads, writes, audits and records its base on one handle, so it commits whole or
28
29
  // not at all.
29
30
  function listHalfLifeRows(db, from, typedPending) {
@@ -140,6 +141,7 @@ export function sqliteConsolidation(handles) {
140
141
  ...bound(on, recordSleepBody(files), openStore),
141
142
  ...bound(on, bareBodies),
142
143
  commit: chunkedCommit(handles),
144
+ ...sleepClaim(files.hippoRoot),
143
145
  };
144
146
  }
145
147
  //# sourceMappingURL=consolidation.js.map
@@ -0,0 +1,4 @@
1
+ import type { Consolidation } from '../../../base/ports/store/consolidation.js';
2
+ /** The claim members of the folder's Consolidation group; the closure keeps the lock its sleep holds. */
3
+ export declare function sleepClaim(hippoRoot: string): Required<Pick<Consolidation, 'claimSleep' | 'releaseSleep'>>;
4
+ //# sourceMappingURL=sleep-lock.d.ts.map
@@ -0,0 +1,69 @@
1
+ // A sleep's claim on the store: a file lock beside hippo.db that every process on the folder honours,
2
+ // freed by the operating system when its holder dies, so no age or pid check can break a live sleep.
3
+ import * as fs from 'node:fs';
4
+ import * as path from 'node:path';
5
+ import { takeFileLock } from '../../../host/file-lock.js';
6
+ import { errorFields, errorMessage, log } from '../../../base/util/log.js';
7
+ import { answered } from '../runtime/bound.js';
8
+ const SLEEP_LOCK_FILE = 'sleep.lock.db';
9
+ // A folder that cannot keep a lock warns once for the process, not once per sleep.
10
+ const warnedRoots = new Set();
11
+ /** When the holder took the claim: the mtime it stamped on the lock file. */
12
+ function claimedSince(file) {
13
+ // A file gone under a live holder, or one that cannot be read, has no stamp left, so the time is now.
14
+ try {
15
+ return (fs.statSync(file, { throwIfNoEntry: false })?.mtime ?? new Date()).toISOString();
16
+ }
17
+ catch (err) {
18
+ log.warn(`the sleep claim on ${file} could not be read: ${errorMessage(err)}`, errorFields(err));
19
+ return new Date().toISOString();
20
+ }
21
+ }
22
+ // By path, never by descriptor: a descriptor closed here would drop this process's other locks.
23
+ function stamp(file) {
24
+ try {
25
+ const now = new Date();
26
+ fs.utimesSync(file, now, now);
27
+ }
28
+ catch (err) {
29
+ log.warn(`the sleep claim on ${file} was not stamped, so a refused sleep may name an older time: ` +
30
+ errorMessage(err), errorFields(err));
31
+ }
32
+ }
33
+ function warnUnusable(hippoRoot, cause) {
34
+ if (warnedRoots.has(hippoRoot))
35
+ return;
36
+ warnedRoots.add(hippoRoot);
37
+ log.warn(`the sleep claim could not be taken on ${hippoRoot}, so sleeps there run unguarded: ` +
38
+ errorMessage(cause), errorFields(cause));
39
+ }
40
+ /** The claim members of the folder's Consolidation group; the closure keeps the lock its sleep holds. */
41
+ export function sleepClaim(hippoRoot) {
42
+ // Joined at the claim, so a store built on a root that is no path still opens.
43
+ const lockFile = () => path.join(hippoRoot, SLEEP_LOCK_FILE);
44
+ let held = null;
45
+ return {
46
+ claimSleep: () => answered(() => {
47
+ const file = lockFile();
48
+ const take = takeFileLock(file);
49
+ if (take.kind === 'held')
50
+ return { kind: 'held', since: claimedSince(file) };
51
+ if (take.kind === 'unusable') {
52
+ warnUnusable(hippoRoot, take.cause);
53
+ return { kind: 'taken' };
54
+ }
55
+ held = take.lock;
56
+ stamp(file);
57
+ return { kind: 'taken' };
58
+ }),
59
+ releaseSleep: () => answered(() => {
60
+ try {
61
+ held?.release();
62
+ }
63
+ finally {
64
+ held = null;
65
+ }
66
+ }),
67
+ };
68
+ }
69
+ //# sourceMappingURL=sleep-lock.js.map
@@ -7,6 +7,7 @@ import { notSupersededAt } from '../../../db/sql-predicates.js';
7
7
  import { cachedStatement } from '../../../db/statement-cache.js';
8
8
  import { entriesPage, entryPageOrder, entryRange, } from '../runtime/keyset.js';
9
9
  import { MEMORY_SELECT_COLUMNS, rowToEntry } from '../runtime/rows.js';
10
+ import { tagsOf } from '../runtime/rule-sql.js';
10
11
  import { tenantAnd, TENANT_IS } from '../runtime/tenant.js';
11
12
  /** The least string above every string that starts with `prefix` in byte order, or null when
12
13
  * none is. */
@@ -36,8 +37,6 @@ function startsWith(column, prefix) {
36
37
  ? { sql: `${column} >= ?`, params: [prefix] }
37
38
  : { sql: `${column} >= ? AND ${column} < ?`, params: [prefix, upper] };
38
39
  }
39
- // A tags column that is not a JSON array reads as no tags, as parseJsonArray reads it.
40
- const tagsOf = (column) => `CASE WHEN NOT json_valid(${column}) THEN '[]' WHEN json_type(${column}) = 'array' THEN ${column} ELSE '[]' END`;
41
40
  const TERMS = {
42
41
  ids: (ids, column) => inList(column('id'), ids),
43
42
  origins: (origins, column) => inList(column('origin_project'), origins),