hippo-memory 3.8.0 → 3.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/README.md +9 -8
  2. package/dist/api/agent-memories.d.ts +3 -2
  3. package/dist/api/agent-memories.js +21 -5
  4. package/dist/base/memory/agent-memory-report.js +1 -0
  5. package/dist/base/util/secret-detect.d.ts +8 -0
  6. package/dist/base/util/secret-detect.js +31 -11
  7. package/dist/base/util/version.d.ts +1 -1
  8. package/dist/base/util/version.js +1 -1
  9. package/dist/domain/agent-memories/apply.js +2 -1
  10. package/dist/domain/agent-memories/claude-code.d.ts +4 -0
  11. package/dist/domain/agent-memories/claude-code.js +24 -1
  12. package/dist/domain/agent-memories/container-steps.js +19 -3
  13. package/dist/domain/agent-memories/folder-store.d.ts +1 -0
  14. package/dist/domain/agent-memories/handover.js +2 -2
  15. package/dist/domain/agent-memories/keys.d.ts +4 -2
  16. package/dist/domain/agent-memories/keys.js +6 -3
  17. package/dist/domain/agent-memories/legacy.js +15 -8
  18. package/dist/domain/agent-memories/markdown.d.ts +5 -0
  19. package/dist/domain/agent-memories/markdown.js +7 -2
  20. package/dist/domain/agent-memories/note-parts.d.ts +4 -0
  21. package/dist/domain/agent-memories/note-parts.js +232 -0
  22. package/dist/domain/agent-memories/plan.d.ts +9 -4
  23. package/dist/domain/agent-memories/plan.js +35 -15
  24. package/dist/domain/agent-memories/source.d.ts +5 -0
  25. package/dist/domain/agent-memories/source.js +12 -0
  26. package/dist/domain/agent-memories/sync.js +5 -1
  27. package/dist/domain/agent-memories/types.d.ts +5 -1
  28. package/dist/store/sqlite/entries/set-aside.d.ts +2 -2
  29. package/dist/store/sqlite/entries/set-aside.js +5 -3
  30. package/dist/surface/capture/compact.d.ts +1 -1
  31. package/dist/surface/capture/compact.js +1 -1
  32. package/dist/surface/cli/doctor.js +1 -0
  33. package/dist/surface/cli/hook-runtime.d.ts +3 -0
  34. package/dist/surface/cli/hook-runtime.js +13 -0
  35. package/dist/surface/cli/hook.js +3 -0
  36. package/dist/surface/cli/hooks/note-import-worker.d.ts +15 -0
  37. package/dist/surface/cli/hooks/note-import-worker.js +44 -0
  38. package/dist/surface/cli/hooks/note-written.d.ts +4 -0
  39. package/dist/surface/cli/hooks/note-written.js +41 -0
  40. package/dist/surface/cli/hooks/post-compact.js +9 -18
  41. package/dist/surface/cli/hooks/session-end.js +2 -14
  42. package/dist/surface/cli/init.js +3 -0
  43. package/dist/surface/cli/setup.js +2 -0
  44. package/dist/surface/cli/verbs/sessions.d.ts +2 -0
  45. package/dist/surface/cli/verbs/sessions.js +16 -2
  46. package/dist/surface/cli/verbs.d.ts +2 -0
  47. package/dist/surface/hooks-install/json-hooks.js +2 -2
  48. package/dist/surface/hooks-install/rules/claude-hooks.d.ts +3 -2
  49. package/dist/surface/hooks-install/rules/claude-hooks.js +25 -2
  50. package/dist/surface/hooks-install/rules/install-plan.js +1 -0
  51. package/dist/surface/hooks-install/rules/json-hooks.d.ts +4 -2
  52. package/dist/surface/hooks-install/rules/json-hooks.js +3 -2
  53. package/dist/surface/hooks-install/rules/shared.d.ts +3 -0
  54. package/dist/surface/hooks-install/rules/shared.js +5 -0
  55. package/extensions/openclaw-plugin/openclaw.plugin.json +1 -1
  56. package/extensions/openclaw-plugin/package.json +1 -1
  57. package/openclaw.plugin.json +1 -1
  58. package/package.json +1 -1
@@ -0,0 +1,232 @@
1
+ // A note over the content cap as parts of one row each: each heading section packed up to the cap,
2
+ // so no part is ever cut short, and a run the secret check flags is never split across two parts.
3
+ import path from 'node:path';
4
+ import { truncateCodePointSafe } from '../../base/util/code-point-cut.js';
5
+ import { maskEmails, redactSecretsStrict, secretSpans, } from '../../base/util/secret-detect.js';
6
+ import { headingOfKey, sha256Hex, textItemKeys } from './keys.js';
7
+ import { closesFence, fenceOf, markdownHeading, slugHeading } from './markdown.js';
8
+ import { CONTENT_CAP, PART_MARK } from './source.js';
9
+ /** The longest title-and-heading line a part opens with, so a long heading leaves room for text. */
10
+ const HEAD_CAP = 200;
11
+ /** The size as stored: emails are masked before the cap. */
12
+ const size = (text) => maskEmails(text).length;
13
+ const overCap = (item) => size(item.text) > CONTENT_CAP;
14
+ /** Each item over the cap replaced by its parts, in note order; other items stay as they are. */
15
+ export function splitContainer(container) {
16
+ if (!container.items.some(overCap))
17
+ return container;
18
+ const fileTitle = (item) => container.textKeyed ? path.basename(container.path) : path.posix.basename(item.key);
19
+ // A text-keyed item's key ends in a hash of its whole text, which any edit changes, so its parts
20
+ // hang on the heading before the hash; `seen` keeps the keys of two items under one heading apart.
21
+ const noteOf = (item) => container.textKeyed ? headingOfKey(item.key) : item.key;
22
+ const seen = new Map();
23
+ return {
24
+ ...container,
25
+ items: container.items.flatMap((item) => overCap(item) ? noteParts(item, item.title ?? fileTitle(item), noteOf(item), seen) : [item]),
26
+ };
27
+ }
28
+ function noteParts(item, title, noteKey, seen) {
29
+ const note = item.text;
30
+ const spans = flaggedSpans(note);
31
+ const parts = sectionsOf(noteLines(note, 0, note.length)).flatMap((section) => sectionParts({ note, budget: CONTENT_CAP, spans }, section, title));
32
+ const keys = textItemKeys(parts.map((p) => ({ headingSlug: `${noteKey}${PART_MARK}${p.slug}`, text: p.text })), seen);
33
+ return parts.map((part, i) => ({
34
+ key: keys[i],
35
+ text: part.text,
36
+ updatedAt: item.updatedAt,
37
+ title,
38
+ flagged: spans.some((s) => s.start < part.end && s.end > part.start),
39
+ }));
40
+ }
41
+ /** The runs the strict check flags in the whole note; when they miss one it still finds, the
42
+ * whole note is one run, as before the split. */
43
+ function flaggedSpans(note) {
44
+ if (redactSecretsStrict(note) === note)
45
+ return [];
46
+ const spans = secretSpans(note);
47
+ let rest = note;
48
+ for (const s of spans) {
49
+ rest = rest.slice(0, s.start) + ' '.repeat(s.end - s.start) + rest.slice(s.end);
50
+ }
51
+ return redactSecretsStrict(rest) === rest ? spans : [{ start: 0, end: note.length }];
52
+ }
53
+ /** Each part opens with the title and heading path; a path over the head cap stays in the text
54
+ * instead, so no heading is cut short. */
55
+ function sectionParts(whole, section, title) {
56
+ const { heading } = section;
57
+ const line = heading === '' || heading === title ? title : `${title} > ${heading}`;
58
+ const fits = size(line) <= HEAD_CAP;
59
+ const head = `${fits ? line : truncateCodePointSafe(title, HEAD_CAP)}\n\n`;
60
+ const lines = fits ? section.lines : [...section.headingLines, ...section.lines];
61
+ const cut = { ...whole, budget: whole.budget - size(head) };
62
+ return packPieces(cut, blocksOf(cut.note, lines), (piece) => splitBlock(cut, piece)).map((piece) => ({ ...piece, slug: section.slug, text: head + piece.text }));
63
+ }
64
+ /** The lines of `note` between two offsets, a CR before each line end left out. */
65
+ function noteLines(note, from, to) {
66
+ const lines = [];
67
+ for (let start = from; start <= to;) {
68
+ const nl = note.indexOf('\n', start);
69
+ const stop = nl < 0 || nl > to ? to : nl;
70
+ const end = stop > start && note[stop - 1] === '\r' ? stop - 1 : stop;
71
+ lines.push({ start, end, text: note.slice(start, end) });
72
+ start = stop + 1;
73
+ }
74
+ return lines;
75
+ }
76
+ // The line after `line` is inside a fence when this returns a run.
77
+ function fenceAfter(open, line) {
78
+ if (open === null)
79
+ return fenceOf(line);
80
+ return closesFence(line, open) ? null : open;
81
+ }
82
+ /** Text before the first heading is the 'top' section; a heading inside a fence is code. */
83
+ function sectionsOf(lines) {
84
+ const sections = [{ heading: '', slug: slugHeading(''), headingLines: [], lines: [] }];
85
+ let fence = null;
86
+ for (const line of lines) {
87
+ const heading = fence === null ? markdownHeading(line.text) : null;
88
+ const last = sections[sections.length - 1];
89
+ if (heading === null)
90
+ last.lines.push(line);
91
+ else if (last.heading !== '' && !last.lines.some((l) => l.text.trim() !== '')) {
92
+ sections[sections.length - 1] = {
93
+ heading: `${last.heading} > ${heading}`,
94
+ slug: partSlug(heading),
95
+ headingLines: [...last.headingLines, line],
96
+ lines: [],
97
+ };
98
+ }
99
+ else
100
+ sections.push({ heading, slug: partSlug(heading), headingLines: [line], lines: [] });
101
+ fence = fenceAfter(fence, line.text);
102
+ }
103
+ return sections.filter((s) => s.lines.some((l) => l.text.trim() !== ''));
104
+ }
105
+ /** A heading with no Latin letter or digit slugs to 'top', so it takes a hash and pairs only with
106
+ * itself. */
107
+ function partSlug(heading) {
108
+ const slug = slugHeading(heading);
109
+ return slug === 'top' ? `h-${sha256Hex(heading).slice(0, 8)}` : slug;
110
+ }
111
+ /** Paragraphs, lists and fences, a fence always a block of its own, blank lines inside it kept. */
112
+ function blocksOf(note, lines) {
113
+ const blocks = [];
114
+ let current = [];
115
+ let fence = null;
116
+ const flush = () => {
117
+ if (current.length > 0)
118
+ blocks.push(current);
119
+ current = [];
120
+ };
121
+ for (const line of lines) {
122
+ if (fence === null && line.text.trim() === '')
123
+ flush();
124
+ else {
125
+ if (fence === null && fenceOf(line.text) !== null)
126
+ flush();
127
+ current.push(line);
128
+ fence = fenceAfter(fence, line.text);
129
+ if (fence === null && fenceOf(current[0].text) !== null)
130
+ flush();
131
+ }
132
+ }
133
+ flush();
134
+ return blocks.map((b) => slice(note, b[0].start, b[b.length - 1].end));
135
+ }
136
+ function slice(note, start, end) {
137
+ return { start, end, text: note.slice(start, end) };
138
+ }
139
+ /** Neighbours a flagged run spans are one piece, so no cut falls inside the run. */
140
+ function keepSpansWhole(cut, pieces) {
141
+ const out = [];
142
+ for (const piece of pieces) {
143
+ const last = out[out.length - 1];
144
+ const spanned = last && cut.spans.some((s) => s.start < piece.start && s.end > last.end);
145
+ if (spanned)
146
+ out[out.length - 1] = slice(cut.note, last.start, piece.end);
147
+ else
148
+ out.push(slice(cut.note, piece.start, piece.end));
149
+ }
150
+ return out;
151
+ }
152
+ /** Whole pieces joined up to the budget; a piece over it goes to `finer` and stands alone. */
153
+ function packPieces(cut, pieces, finer) {
154
+ const out = [];
155
+ let open = null;
156
+ for (const piece of keepSpansWhole(cut, pieces)) {
157
+ if (size(piece.text) > cut.budget) {
158
+ if (open !== null)
159
+ out.push(open);
160
+ open = null;
161
+ out.push(...finer(piece));
162
+ continue;
163
+ }
164
+ const joined = open === null ? piece : slice(cut.note, open.start, piece.end);
165
+ if (size(joined.text) <= cut.budget)
166
+ open = joined;
167
+ else {
168
+ if (open !== null)
169
+ out.push(open);
170
+ open = piece;
171
+ }
172
+ }
173
+ if (open !== null)
174
+ out.push(open);
175
+ return out;
176
+ }
177
+ /** A block over the budget: a fence at its lines, each part closing and reopening it; any other
178
+ * block at its lines, then its words, then a code point. */
179
+ function splitBlock(cut, block) {
180
+ const lines = noteLines(cut.note, block.start, block.end);
181
+ const fence = fenceOf(lines[0].text);
182
+ if (fence !== null && lines.length > 1)
183
+ return fenceParts(cut, lines, fence);
184
+ return packLines(cut, lines);
185
+ }
186
+ function packLines(cut, lines) {
187
+ const words = (line) => packPieces(cut, wordsOf(cut.note, line), (word) => hardCut(cut, word));
188
+ return packPieces(cut, lines, words);
189
+ }
190
+ function fenceParts(cut, lines, fence) {
191
+ const open = lines[0].text;
192
+ const last = lines[lines.length - 1].text;
193
+ const closed = lines.length > 1 && closesFence(last, fence);
194
+ const close = closed ? last : fence;
195
+ const inner = lines.slice(1, closed ? -1 : undefined);
196
+ if (inner.length === 0)
197
+ return packLines(cut, lines);
198
+ const room = { ...cut, budget: cut.budget - size(open) - size(close) - 2 };
199
+ // Under half a part left for code, and the cuts would be scraps inside a fence: plain lines.
200
+ if (room.budget < cut.budget / 2)
201
+ return packLines(cut, lines);
202
+ return packLines(room, inner).map((p) => ({ ...p, text: `${open}\n${p.text}\n${close}` }));
203
+ }
204
+ function wordsOf(note, line) {
205
+ const words = [];
206
+ for (const m of line.text.matchAll(/\S+/g)) {
207
+ const start = line.start + m.index;
208
+ words.push(slice(note, start, start + m[0].length));
209
+ }
210
+ return words;
211
+ }
212
+ /** The last resort: cuts at the budget on a code point, a flagged run kept whole even over it. */
213
+ function hardCut(cut, piece) {
214
+ const out = [];
215
+ for (let at = piece.start; at < piece.end;) {
216
+ const inside = cut.spans.find((s) => s.start <= at && s.end > at);
217
+ let to = inside ? Math.min(piece.end, inside.end) : cutPoint(cut, at, piece.end);
218
+ const next = cut.spans.find((s) => s.start > at && s.start < to && s.end > to);
219
+ if (!inside && next)
220
+ to = next.start;
221
+ out.push(slice(cut.note, at, to));
222
+ at = to;
223
+ }
224
+ return out;
225
+ }
226
+ function cutPoint(cut, from, to) {
227
+ let end = from + truncateCodePointSafe(cut.note.slice(from, to), cut.budget).length;
228
+ while (end > from + 1 && size(cut.note.slice(from, end)) > cut.budget)
229
+ end--;
230
+ return Math.max(end, from + 1);
231
+ }
232
+ //# sourceMappingURL=note-parts.js.map
@@ -34,6 +34,8 @@ export interface PlannedWrite {
34
34
  readonly key: string;
35
35
  readonly hash: string;
36
36
  readonly supersedes: readonly string[];
37
+ /** Rows whose recall and outcome counts the new row takes: a note that crossed the cap. */
38
+ readonly carry?: readonly string[];
37
39
  }
38
40
  export interface ContainerPlan {
39
41
  readonly unchanged: number;
@@ -65,16 +67,19 @@ export interface LegacyTarget {
65
67
  /** Opaque to this function: the sync's handle on one container's item. */
66
68
  readonly ref: string;
67
69
  readonly file: string;
70
+ /** The note it is, or a part of: the parts of one long note share it. */
71
+ readonly note: string;
68
72
  readonly textKey: string;
69
73
  }
70
74
  export interface LegacyMatch {
71
75
  /** Legacy row id to the target whose key it takes, keeping its id and history (same text: a
72
76
  * renamed note too). */
73
77
  readonly adopt: ReadonlyMap<string, string>;
74
- /** Target ref to the legacy row a new row of that target replaces (different text, one legacy
75
- * row of that file). */
76
- readonly replace: ReadonlyMap<string, string>;
78
+ /** Target ref to the legacy rows a new row of that target replaces (different text, a file name
79
+ * only one note has). */
80
+ readonly replace: ReadonlyMap<string, readonly string[]>;
77
81
  }
78
- /** Same text first, then one legacy row per file name; anything else is left to decay. */
82
+ /** Same text first, then every row of a file name only one note has, given to its first target;
83
+ * anything else is left to decay. */
79
84
  export declare function matchLegacy(rows: readonly LegacyRow[], targets: readonly LegacyTarget[]): LegacyMatch;
80
85
  //# sourceMappingURL=plan.d.ts.map
@@ -1,4 +1,6 @@
1
1
  // What one sync does to one container's rows: a pure function of the items read and the rows found.
2
+ import { headingOfKey } from './keys.js';
3
+ import { fileOfKey, isPartKey } from './source.js';
2
4
  export function planContainer(input) {
3
5
  const live = groupByKey(input.live);
4
6
  const dormant = groupByKey(input.dormant);
@@ -22,15 +24,17 @@ export function planContainer(input) {
22
24
  draft,
23
25
  });
24
26
  }
25
- const read = new Set([...input.items.map((i) => i.key), ...input.skipped]);
27
+ const read = new Set(input.items.map((i) => i.key));
28
+ // Skipped holds file keys, so the parts of a note that was not read stay too.
29
+ const unread = new Set(input.skipped);
26
30
  const gone = new Map();
27
31
  for (const [key, rows] of live) {
28
32
  const tagged = rows.filter((r) => r.tagged).map((r) => r.id);
29
- if (!read.has(key) && tagged.length > 0)
33
+ if (!read.has(key) && !unread.has(fileOfKey(key)) && tagged.length > 0)
30
34
  gone.set(key, tagged);
31
35
  }
32
- if (input.textKeyed)
33
- pairEdits(gone, draft.fresh);
36
+ pairCapCrossings(gone, draft.fresh);
37
+ pairEdits(gone, draft.fresh, input.textKeyed ? () => true : isPartKey);
34
38
  for (const ids of gone.values())
35
39
  draft.setAside.push(...ids);
36
40
  const { fresh, ...plan } = draft;
@@ -52,6 +56,9 @@ function planItem({ input, item, rows, snaps, draft }) {
52
56
  draft.retag.push(kept.id);
53
57
  const others = tagged.filter((r) => r.id !== kept.id);
54
58
  draft.collapse.push(...others.map((r) => ({ id: r.id, by: kept.id })));
59
+ // An unchanged note retires its old Claude import's copy too.
60
+ const stale = input.legacy?.get(item.key) ?? [];
61
+ draft.collapse.push(...stale.map((id) => ({ id, by: kept.id })));
55
62
  if (kept.tagged && others.length === 0)
56
63
  draft.unchanged++;
57
64
  return;
@@ -79,11 +86,24 @@ function planItem({ input, item, rows, snaps, draft }) {
79
86
  else
80
87
  draft.fresh.push({ key: item.key, hash: item.hash, supersedes: legacy });
81
88
  }
82
- /** A single-file store keys items by text, so an edit reads as one key gone and one new under
83
- * the same heading. */
84
- function pairEdits(gone, fresh) {
85
- const goneBy = groupBy([...gone.keys()], headingOf);
86
- const freshBy = groupBy(fresh.map((w, i) => ({ w, i })), (f) => headingOf(f.w.key));
89
+ /** A note that crossed the cap either way: its first new row, whole or part, supersedes every
90
+ * row of the other shape and takes their history, so nothing goes dormant. */
91
+ function pairCapCrossings(gone, fresh) {
92
+ for (const [file, keys] of groupBy([...gone.keys()], fileOfKey)) {
93
+ const i = fresh.findIndex((w) => fileOfKey(w.key) === file);
94
+ if (i < 0 || (!keys.includes(file) && fresh[i].key !== file))
95
+ continue;
96
+ const ids = keys.flatMap((key) => gone.get(key) ?? []);
97
+ fresh[i] = { ...fresh[i], supersedes: [...fresh[i].supersedes, ...ids], carry: ids };
98
+ for (const key of keys)
99
+ gone.delete(key);
100
+ }
101
+ }
102
+ /** Text keys, a single-file store's or a long note's parts, read an edit as one key gone and one
103
+ * new under the same heading. */
104
+ function pairEdits(gone, fresh, textKey) {
105
+ const goneBy = groupBy([...gone.keys()].filter(textKey), headingOfKey);
106
+ const freshBy = groupBy(fresh.map((w, i) => ({ w, i })).filter((f) => textKey(f.w.key)), (f) => headingOfKey(f.w.key));
87
107
  for (const [heading, keys] of goneBy) {
88
108
  const news = freshBy.get(heading) ?? [];
89
109
  if (keys.length !== 1 || news.length !== 1)
@@ -93,9 +113,6 @@ function pairEdits(gone, fresh) {
93
113
  gone.delete(keys[0]);
94
114
  }
95
115
  }
96
- function headingOf(key) {
97
- return key.slice(0, Math.max(0, key.lastIndexOf('/')));
98
- }
99
116
  // Byte order, as memory.ts's timestamp note asks: localeCompare may skip the ISO punctuation.
100
117
  const byteOrder = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
101
118
  function newestRow(rows) {
@@ -119,7 +136,8 @@ function groupBy(values, keyOf) {
119
136
  }
120
137
  return out;
121
138
  }
122
- /** Same text first, then one legacy row per file name; anything else is left to decay. */
139
+ /** Same text first, then every row of a file name only one note has, given to its first target;
140
+ * anything else is left to decay. */
123
141
  export function matchLegacy(rows, targets) {
124
142
  const byText = new Map();
125
143
  for (const t of targets)
@@ -137,8 +155,10 @@ export function matchLegacy(rows, targets) {
137
155
  const replace = new Map();
138
156
  for (const [file, left] of leftByFile) {
139
157
  const matches = targetsByFile.get(file) ?? [];
140
- if (left.length === 1 && matches.length === 1)
141
- replace.set(matches[0].ref, left[0].id);
158
+ // Two notes of one name match none: the old row could be either.
159
+ if (new Set(matches.map((t) => t.note)).size !== 1)
160
+ continue;
161
+ replace.set(matches[0].ref, left.map((r) => r.id));
142
162
  }
143
163
  return { adopt, replace };
144
164
  }
@@ -14,6 +14,11 @@ export declare function itemSource(prefix: string, { key, text }: {
14
14
  readonly key: string;
15
15
  readonly text: string;
16
16
  }): string;
17
+ /** Joins a long note's key to a part's `<heading slug>/<12 hex>`. */
18
+ export declare const PART_MARK = "::";
19
+ /** The note a key belongs to: the key before its part tail, else the whole key. */
20
+ export declare function fileOfKey(key: string): string;
21
+ export declare function isPartKey(key: string): boolean;
17
22
  /** The key and hash of a source under `prefix`; the hash follows the last `#`, since a file name
18
23
  * may hold one too. */
19
24
  export declare function splitSource(source: string, prefix: string): {
@@ -22,6 +22,18 @@ export function containerPrefix(tool, container) {
22
22
  export function itemSource(prefix, { key, text }) {
23
23
  return `${prefix}${key}#${itemHash(text)}`;
24
24
  }
25
+ /** Joins a long note's key to a part's `<heading slug>/<12 hex>`. */
26
+ export const PART_MARK = '::';
27
+ // A file name may hold "::", so only the exact tail the splitter writes, at the key's end, is a part.
28
+ const PART_TAIL = new RegExp(`${PART_MARK}[a-z0-9-]+/[0-9a-f]{${ID_SUFFIX_CHARS}}(?:~\\d+)?$`);
29
+ /** The note a key belongs to: the key before its part tail, else the whole key. */
30
+ export function fileOfKey(key) {
31
+ const tail = PART_TAIL.exec(key);
32
+ return tail === null ? key : key.slice(0, tail.index);
33
+ }
34
+ export function isPartKey(key) {
35
+ return PART_TAIL.test(key);
36
+ }
25
37
  /** The key and hash of a source under `prefix`; the hash follows the last `#`, since a file name
26
38
  * may hold one too. */
27
39
  export function splitSource(source, prefix) {
@@ -13,6 +13,7 @@ import { codexAdapter } from './codex.js';
13
13
  import { copilotAdapter } from './copilot.js';
14
14
  import { geminiAdapter } from './gemini.js';
15
15
  import { legacyWork } from './legacy.js';
16
+ import { splitContainer } from './note-parts.js';
16
17
  import { openclawAdapter } from './openclaw.js';
17
18
  import { qwenCodeAdapter } from './qwen-code.js';
18
19
  import { addTally, emptyReport, toolReport, } from '../../base/memory/agent-memory-report.js';
@@ -78,7 +79,10 @@ function knownTools(ids, onUnknown) {
78
79
  export async function runPass(pass, opts) {
79
80
  const report = emptyReport();
80
81
  const allowed = allowedTools(opts, pass.invoking, pass.target, report.warnings);
81
- const listings = ADAPTERS.filter((a) => allowed.has(a.tool)).flatMap((a) => listSafely(a, pass, report));
82
+ // Long notes split before the legacy match, so an old row is matched to a part.
83
+ const listings = ADAPTERS.filter((a) => allowed.has(a.tool))
84
+ .flatMap((a) => listSafely(a, pass, report))
85
+ .map((l) => ({ ...l, containers: l.containers.map(splitContainer) }));
82
86
  const hasItems = listings.some((l) => l.containers.some((c) => c.items.length > 0));
83
87
  let store = null;
84
88
  let synced = [];
@@ -8,10 +8,14 @@ export interface AdapterContext extends Machine {
8
8
  }
9
9
  export interface MemoryItem {
10
10
  /** A path inside the container with '/' separators, or `<heading slug>/<text hash>` in a
11
- * single-file store. */
11
+ * single-file store; a part is `<path or heading slug>::<heading slug>/<text hash>`. */
12
12
  readonly key: string;
13
13
  readonly text: string;
14
14
  readonly updatedAt: number;
15
+ /** The note's frontmatter name, else its file name; the head of each part of a long note. */
16
+ readonly title?: string;
17
+ /** A part of a long note that overlaps text the strict secret check flags in the whole note. */
18
+ readonly flagged?: boolean;
15
19
  }
16
20
  /** A folder, or one file's memory section, that exists on disk. */
17
21
  export interface Container {
@@ -8,7 +8,7 @@ export interface SetAsideRowOptions {
8
8
  readonly why: SetAsideWhy;
9
9
  readonly rules: StoreModel;
10
10
  }
11
- /** Design 6's set-aside on the caller's transaction: a pinned row only loses the tag, any other
12
- * goes dormant, restorable. */
11
+ /** Design 6's set-aside on the caller's transaction: a pinned row, or one an object links to, only
12
+ * loses the tag; any other goes dormant, restorable. */
13
13
  export declare function setAsideRow(db: DatabaseSyncLike, { tag, row, why, rules }: SetAsideRowOptions): SetAsideResult;
14
14
  //# sourceMappingURL=set-aside.d.ts.map
@@ -5,9 +5,10 @@ import { SYNC_ACTOR } from '../../../base/memory/agent-memory-tools.js';
5
5
  import { insertDormantRow } from '../dormant/dormant-rows.js';
6
6
  import { calculateStrength } from '../../../base/memory/strength.js';
7
7
  import { deleteEntryRowInTx, setEntryTagsInTx } from './entry-writes.js';
8
+ import { memoriesBackingAmong } from './delete-and-batch.js';
8
9
  import { handleNow } from '../runtime/handle-clock.js';
9
- /** Design 6's set-aside on the caller's transaction: a pinned row only loses the tag, any other
10
- * goes dormant, restorable. */
10
+ /** Design 6's set-aside on the caller's transaction: a pinned row, or one an object links to, only
11
+ * loses the tag; any other goes dormant, restorable. */
11
12
  export function setAsideRow(db, { tag, row, why, rules }) {
12
13
  const untagged = { ...row, tags: row.tags.filter((t) => t !== tag) };
13
14
  const audit = (metadata) => appendAuditEvents(db, [
@@ -19,7 +20,8 @@ export function setAsideRow(db, { tag, row, why, rules }) {
19
20
  metadata,
20
21
  },
21
22
  ]);
22
- if (row.pinned) {
23
+ // Deleting a row an object links to nulls the link, which no restore repairs.
24
+ if (row.pinned || memoriesBackingAmong(db, [row.id]).has(row.id)) {
23
25
  setEntryTagsInTx(db, untagged);
24
26
  audit({ why, untagged: true });
25
27
  return { kind: 'untagged', entry: untagged };
@@ -27,7 +27,7 @@ export interface PostCompactOptions {
27
27
  stdinText?: string;
28
28
  stdinTimedOut?: boolean;
29
29
  logFile?: string;
30
- afterSave?: (transcriptPath: string, cwd: string | null, log: (message: string) => void) => Promise<void>;
30
+ afterSave?: (transcriptPath: string, cwd: string | null) => void | Promise<void>;
31
31
  }
32
32
  /** PostCompact entry point: saves the summary and its items, replays earlier leftovers, returns
33
33
  * the one line to show. Never throws, so the hook exits 0. */
@@ -296,7 +296,7 @@ export async function postCompactHook(hippoRoot, store, options) {
296
296
  storeBusy = saved.deferred;
297
297
  if (!storeBusy && receipt.input.transcriptPath !== null && options.afterSave) {
298
298
  try {
299
- await options.afterSave(receipt.input.transcriptPath, receipt.input.cwd, log);
299
+ await options.afterSave(receipt.input.transcriptPath, receipt.input.cwd);
300
300
  }
301
301
  catch (err) {
302
302
  log(`agent memory import failed: ${errorMessage(err)}`, errorFields(err));
@@ -131,6 +131,7 @@ const CLAUDE_CODE_HOOKS = [
131
131
  ['hippo compact-resume', 'resume after compaction'],
132
132
  ['hippo post-compact', 'saving the memories a compaction lists'],
133
133
  ['hippo capture-error', 'failed-tool capture'],
134
+ ['hippo note-written', 'importing memory notes when Claude Code writes them'],
134
135
  ];
135
136
  function claudeCodeCheck(home) {
136
137
  const claudeDir = claudeConfigDir(home, processEnv());
@@ -21,6 +21,9 @@ export declare function appendSessionEndCloseLog(logFile: string | null, message
21
21
  startFresh?: boolean;
22
22
  fields?: LogFields;
23
23
  }): void;
24
+ /** Starts `workerArgs` as a detached child that outlives the host's teardown; `name` labels a
25
+ * failed start. */
26
+ export declare function spawnDetachedWorker(name: string, workerArgs: readonly string[]): void;
24
27
  /** Runs `run` with the held lines written on exit too, as sleep may end the process before the
25
28
  * run writes them. */
26
29
  export declare function flushingOnExit(held: HeldLog, run: () => Promise<void>): Promise<void>;
@@ -3,6 +3,7 @@
3
3
  import { envClaudeCodeSessionId, envHippoSessionId } from '../../base/util/env.js';
4
4
  import * as path from 'node:path';
5
5
  import * as fs from 'node:fs';
6
+ import { spawn } from 'node:child_process';
6
7
  import { bookTokenUse } from '../../api/ledger-db.js';
7
8
  import { sessionPilotArm } from '../../api/pilot-arm.js';
8
9
  import { cliDetached, cliFolder, cliInfra, cliLedgerReach, cliSyncOptions } from './api-context.js';
@@ -63,6 +64,18 @@ export function appendSessionEndCloseLog(logFile, message, opts = {}) {
63
64
  log.warn(`session-end log not written: ${errorMessage(err)}`, errorFields(err));
64
65
  }
65
66
  }
67
+ /** Starts `workerArgs` as a detached child that outlives the host's teardown; `name` labels a
68
+ * failed start. */
69
+ export function spawnDetachedWorker(name, workerArgs) {
70
+ const child = spawn(process.execPath, workerArgs, {
71
+ detached: true,
72
+ stdio: 'ignore',
73
+ windowsHide: true,
74
+ });
75
+ // With no 'error' listener an async spawn failure is an uncaught exception.
76
+ child.on('error', (err) => log.warn(`hippo ${name}: the worker did not start: ${errorMessage(err)}`, errorFields(err)));
77
+ child.unref();
78
+ }
66
79
  /** Runs `run` with the held lines written on exit too, as sleep may end the process before the
67
80
  * run writes them. */
68
81
  export async function flushingOnExit(held, run) {
@@ -122,6 +122,9 @@ function printClaudeHookInstall(result) {
122
122
  if (result.installedCaptureError) {
123
123
  console.log(`Installed hippo capture-error PostToolUseFailure hook in ${result.target} settings`);
124
124
  }
125
+ if (result.installedNoteWritten) {
126
+ console.log(`Installed hippo note-written PostToolUse hook in ${result.target} settings`);
127
+ }
125
128
  if (result.migratedFromStop) {
126
129
  console.log(`Migrated legacy Stop hook → SessionEnd (was running every turn; now fires once on session exit)`);
127
130
  }
@@ -0,0 +1,15 @@
1
+ import { type CommandContext } from '../flag-values.js';
2
+ /** What a hook hands the worker: the session's transcript, which names its notes folder. */
3
+ export interface NoteImportJob {
4
+ /** The hook that asked, which prefixes each log line. */
5
+ readonly from: 'note-written' | 'post-compact';
6
+ readonly transcriptPath: string;
7
+ readonly cwd: string | null;
8
+ readonly logFile: string | null;
9
+ }
10
+ /** Starts the import in a detached worker and returns at once; the worker finds its store from
11
+ * the folder it inherits. */
12
+ export declare function startNoteImport({ from, transcriptPath, cwd, logFile }: NoteImportJob): void;
13
+ /** Never throws: a failed import is a log line, since nothing waits on this process. */
14
+ export declare function handleNoteImportWorker({ hippoRoot, tenantId, flags, }: CommandContext): Promise<void>;
15
+ //# sourceMappingURL=note-import-worker.d.ts.map
@@ -0,0 +1,44 @@
1
+ // The detached agent-note import (`__note-import-worker`): one session folder's notes, with no
2
+ // hook time limit, and a log line for what it did.
3
+ import { importSessionFolder } from '../../../api/agent-memories.js';
4
+ import { summaryLine } from '../../../base/memory/agent-memory-report.js';
5
+ import { isInitialized } from '../../../host/project-identity.js';
6
+ import { currentMachine } from '../../../infra/machine.js';
7
+ import { cliSyncOptions } from '../api-context.js';
8
+ import { stringFlag } from '../flag-values.js';
9
+ import { appendSessionEndCloseLog, hookStoreRoot, reportSessionEndFailure, spawnDetachedWorker, } from '../hook-runtime.js';
10
+ /** Starts the import in a detached worker and returns at once; the worker finds its store from
11
+ * the folder it inherits. */
12
+ export function startNoteImport({ from, transcriptPath, cwd, logFile }) {
13
+ const args = [process.argv[1], '__note-import-worker', '--transcript', transcriptPath];
14
+ args.push('--from', from);
15
+ if (cwd !== null)
16
+ args.push('--cwd', cwd);
17
+ if (logFile !== null)
18
+ args.push('--log-file', logFile);
19
+ spawnDetachedWorker(from, args);
20
+ }
21
+ /** Never throws: a failed import is a log line, since nothing waits on this process. */
22
+ export async function handleNoteImportWorker({ hippoRoot, tenantId, flags, }) {
23
+ const transcript = stringFlag(flags, 'transcript');
24
+ const logFile = stringFlag(flags, 'log-file') ?? null;
25
+ const from = stringFlag(flags, 'from') ?? 'note-written';
26
+ const say = (line) => appendSessionEndCloseLog(logFile, `${from}: ${line}`);
27
+ const store = hookStoreRoot(hippoRoot);
28
+ // A hook fires in every folder, and none may create a store.
29
+ if (transcript === undefined || !isInitialized(store))
30
+ return;
31
+ try {
32
+ const sync = cliSyncOptions(tenantId, currentMachine());
33
+ const report = await importSessionFolder(store, transcript, stringFlag(flags, 'cwd') ?? null, sync);
34
+ const summary = summaryLine(report);
35
+ if (summary !== null)
36
+ say(summary);
37
+ for (const warning of report.warnings)
38
+ say(`agent memories: ${warning}`);
39
+ }
40
+ catch (err) {
41
+ reportSessionEndFailure(logFile, `${from}: agent memory import`, err);
42
+ }
43
+ }
44
+ //# sourceMappingURL=note-import-worker.js.map
@@ -0,0 +1,4 @@
1
+ import { type CommandContext } from '../flag-values.js';
2
+ /** Every path exits 0, so a failure never blocks the session. */
3
+ export declare function handleNoteWritten({ flags }: CommandContext): Promise<void>;
4
+ //# sourceMappingURL=note-written.d.ts.map