dsh-cross-memory 0.0.0-stage → 0.2.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 (152) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +247 -2
  3. package/cordis.patch.yml +27 -0
  4. package/docs/DETAIL.md +13 -0
  5. package/docs/DETAIL.zh.md +17 -0
  6. package/icon.svg +1 -0
  7. package/lib/backfill.js +273 -0
  8. package/lib/citations.js +305 -0
  9. package/lib/client.js +1550 -0
  10. package/lib/config.js +736 -0
  11. package/lib/consolidate.js +1119 -0
  12. package/lib/extract.js +570 -0
  13. package/lib/gate.js +137 -0
  14. package/lib/git-origin.js +224 -0
  15. package/lib/index.js +4475 -0
  16. package/lib/log.js +260 -0
  17. package/lib/loops.js +186 -0
  18. package/lib/notices.js +195 -0
  19. package/lib/notify.js +33 -0
  20. package/lib/persona.js +112 -0
  21. package/lib/query.js +93 -0
  22. package/lib/raw-recall.js +286 -0
  23. package/lib/reflection.js +291 -0
  24. package/lib/remote.js +455 -0
  25. package/lib/render.js +678 -0
  26. package/lib/retention.js +64 -0
  27. package/lib/schedule.js +245 -0
  28. package/lib/search.js +1068 -0
  29. package/lib/skills.js +220 -0
  30. package/lib/state.js +701 -0
  31. package/lib/storage.js +1424 -0
  32. package/lib/sync-runtime.js +268 -0
  33. package/lib/sync.js +620 -0
  34. package/lib/test/activity.test.js +74 -0
  35. package/lib/test/archive.test.js +182 -0
  36. package/lib/test/backfill.test.js +144 -0
  37. package/lib/test/citations.test.js +91 -0
  38. package/lib/test/client-wiring.test.js +134 -0
  39. package/lib/test/consolidate-job.test.js +95 -0
  40. package/lib/test/consolidate.test.js +430 -0
  41. package/lib/test/consolidation-selection.test.js +152 -0
  42. package/lib/test/dedupe-keys.test.js +230 -0
  43. package/lib/test/delta.test.js +93 -0
  44. package/lib/test/derived.test.js +110 -0
  45. package/lib/test/disputes-panel.test.js +314 -0
  46. package/lib/test/eval.test.js +171 -0
  47. package/lib/test/expand.test.js +164 -0
  48. package/lib/test/extract.test.js +1020 -0
  49. package/lib/test/git-origin.test.js +189 -0
  50. package/lib/test/injection.test.js +440 -0
  51. package/lib/test/kind-filter.test.js +49 -0
  52. package/lib/test/legacy-state.test.js +69 -0
  53. package/lib/test/log.test.js +156 -0
  54. package/lib/test/loops.test.js +86 -0
  55. package/lib/test/memory.test.js +855 -0
  56. package/lib/test/notices.test.js +140 -0
  57. package/lib/test/persona.test.js +73 -0
  58. package/lib/test/prefilter.test.js +73 -0
  59. package/lib/test/preset.test.js +77 -0
  60. package/lib/test/raw-recall.test.js +186 -0
  61. package/lib/test/recall.test.js +433 -0
  62. package/lib/test/reflection.test.js +64 -0
  63. package/lib/test/remote.test.js +227 -0
  64. package/lib/test/retention.test.js +117 -0
  65. package/lib/test/retrieval.test.js +142 -0
  66. package/lib/test/rotation.test.js +228 -0
  67. package/lib/test/schedule.test.js +112 -0
  68. package/lib/test/settings-card.test.js +58 -0
  69. package/lib/test/skills.test.js +129 -0
  70. package/lib/test/state.test.js +212 -0
  71. package/lib/test/subagent-contract.test.js +139 -0
  72. package/lib/test/sweep.test.js +159 -0
  73. package/lib/test/sync.test.js +314 -0
  74. package/lib/test/time.test.js +171 -0
  75. package/lib/time.js +303 -0
  76. package/lib/tool.js +330 -0
  77. package/lib/types/backfill.d.ts +96 -0
  78. package/lib/types/citations.d.ts +105 -0
  79. package/lib/types/config.d.ts +811 -0
  80. package/lib/types/consolidate.d.ts +742 -0
  81. package/lib/types/extract.d.ts +352 -0
  82. package/lib/types/gate.d.ts +83 -0
  83. package/lib/types/git-origin.d.ts +23 -0
  84. package/lib/types/index.d.ts +1316 -0
  85. package/lib/types/log.d.ts +144 -0
  86. package/lib/types/loops.d.ts +82 -0
  87. package/lib/types/notices.d.ts +117 -0
  88. package/lib/types/notify.d.ts +12 -0
  89. package/lib/types/persona.d.ts +43 -0
  90. package/lib/types/query.d.ts +45 -0
  91. package/lib/types/raw-recall.d.ts +84 -0
  92. package/lib/types/reflection.d.ts +122 -0
  93. package/lib/types/remote.d.ts +233 -0
  94. package/lib/types/render.d.ts +286 -0
  95. package/lib/types/retention.d.ts +66 -0
  96. package/lib/types/schedule.d.ts +116 -0
  97. package/lib/types/search.d.ts +583 -0
  98. package/lib/types/skills.d.ts +71 -0
  99. package/lib/types/state.d.ts +294 -0
  100. package/lib/types/storage.d.ts +458 -0
  101. package/lib/types/sync-runtime.d.ts +103 -0
  102. package/lib/types/sync.d.ts +222 -0
  103. package/lib/types/test/activity.test.d.ts +1 -0
  104. package/lib/types/test/archive.test.d.ts +1 -0
  105. package/lib/types/test/backfill.test.d.ts +1 -0
  106. package/lib/types/test/citations.test.d.ts +1 -0
  107. package/lib/types/test/client-wiring.test.d.ts +1 -0
  108. package/lib/types/test/consolidate-job.test.d.ts +1 -0
  109. package/lib/types/test/consolidate.test.d.ts +1 -0
  110. package/lib/types/test/consolidation-selection.test.d.ts +1 -0
  111. package/lib/types/test/dedupe-keys.test.d.ts +1 -0
  112. package/lib/types/test/delta.test.d.ts +1 -0
  113. package/lib/types/test/derived.test.d.ts +1 -0
  114. package/lib/types/test/disputes-panel.test.d.ts +1 -0
  115. package/lib/types/test/eval.test.d.ts +1 -0
  116. package/lib/types/test/expand.test.d.ts +1 -0
  117. package/lib/types/test/extract.test.d.ts +1 -0
  118. package/lib/types/test/git-origin.test.d.ts +1 -0
  119. package/lib/types/test/injection.test.d.ts +1 -0
  120. package/lib/types/test/kind-filter.test.d.ts +1 -0
  121. package/lib/types/test/legacy-state.test.d.ts +1 -0
  122. package/lib/types/test/log.test.d.ts +1 -0
  123. package/lib/types/test/loops.test.d.ts +1 -0
  124. package/lib/types/test/memory.test.d.ts +1 -0
  125. package/lib/types/test/notices.test.d.ts +1 -0
  126. package/lib/types/test/persona.test.d.ts +1 -0
  127. package/lib/types/test/prefilter.test.d.ts +1 -0
  128. package/lib/types/test/preset.test.d.ts +1 -0
  129. package/lib/types/test/raw-recall.test.d.ts +1 -0
  130. package/lib/types/test/recall.test.d.ts +1 -0
  131. package/lib/types/test/reflection.test.d.ts +1 -0
  132. package/lib/types/test/remote.test.d.ts +1 -0
  133. package/lib/types/test/retention.test.d.ts +1 -0
  134. package/lib/types/test/retrieval.test.d.ts +1 -0
  135. package/lib/types/test/rotation.test.d.ts +1 -0
  136. package/lib/types/test/schedule.test.d.ts +1 -0
  137. package/lib/types/test/settings-card.test.d.ts +1 -0
  138. package/lib/types/test/skills.test.d.ts +1 -0
  139. package/lib/types/test/state.test.d.ts +1 -0
  140. package/lib/types/test/subagent-contract.test.d.ts +1 -0
  141. package/lib/types/test/sweep.test.d.ts +1 -0
  142. package/lib/types/test/sync.test.d.ts +1 -0
  143. package/lib/types/test/time.test.d.ts +1 -0
  144. package/lib/types/time.d.ts +67 -0
  145. package/lib/types/tool.d.ts +9 -0
  146. package/lib/types/types.d.ts +374 -0
  147. package/lib/types/workspace.d.ts +20 -0
  148. package/lib/types.js +47 -0
  149. package/lib/workspace.js +65 -0
  150. package/locale/en.json +7 -0
  151. package/locale/zh.json +7 -0
  152. package/package.json +126 -4
@@ -0,0 +1,583 @@
1
+ /**
2
+ * Lexical search over stored memories.
3
+ *
4
+ * Deliberately dependency-free and deterministic: one score ranks everything —
5
+ * lexical relevance, the entry's track record, and how recently it was
6
+ * touched — so tool search, the injected summary, and on-demand recall all
7
+ * agree on what is worth recalling.
8
+ *
9
+ * Chinese is a first-class case here, not a fallback. A query with no spaces
10
+ * ("该插件是否有日志") tokenizes to one indivisible run under any whitespace
11
+ * splitter, so a whole-run substring test is the only thing that could match —
12
+ * and a memory almost never contains a whole question verbatim. Every
13
+ * comparison therefore runs over CJK character bigrams as well, which is what
14
+ * makes "日志" find a memory titled "…的日志在哪里" without a model call.
15
+ *
16
+ * @module dsh-cross-memory/search
17
+ */
18
+ import type { MemoryEntry, MemoryHit, MemoryKind, MemoryScope } from './types.js';
19
+ import { type TimeRange } from './time.js';
20
+ /** Score added when the whole query appears verbatim in one field. */
21
+ export declare const FIELD_WEIGHTS: {
22
+ readonly title: 40;
23
+ readonly keys: 26;
24
+ readonly tags: 20;
25
+ readonly appliesTo: 18;
26
+ readonly body: 12;
27
+ };
28
+ /**
29
+ * Score added per query term that appears in one field.
30
+ *
31
+ * Much smaller than {@link FIELD_WEIGHTS} because a term is one signal among
32
+ * many; the whole-query match is the strong claim. `body` is capped per term so
33
+ * a long memory that happens to repeat a word cannot dominate.
34
+ */
35
+ export declare const TERM_WEIGHTS: {
36
+ readonly title: 8;
37
+ readonly keys: 7;
38
+ readonly tags: 6;
39
+ readonly appliesTo: 5;
40
+ readonly body: 2;
41
+ };
42
+ /**
43
+ * How much evidence one entry has for one query.
44
+ *
45
+ * `strongTerms` is not a sum over bigrams, because a Chinese query and a Chinese
46
+ * memory share a *run*, not a bag of pairs: "插件日志" enters the scorer as the
47
+ * overlapping pair 插件/件日/日志, so counting pairs would score one real phrase
48
+ * as three, while two independently common pairs would also score two. Counting
49
+ * substantive units instead — a shared CJK run of at least three characters, or
50
+ * a Latin word of at least three characters — is what makes "两个信号" mean two
51
+ * pieces of evidence rather than two accidental character overlaps.
52
+ */
53
+ export interface MatchEvidence {
54
+ /**
55
+ * Distinct query terms shared with the title, keys, tags, or `appliesTo` that
56
+ * count as real evidence:
57
+ *
58
+ * - a Latin word of three characters or more (`dsh`, `pnpm`, `3080`), or
59
+ * - a CJK bigram sitting inside a shared run of at least three characters.
60
+ *
61
+ * The run requirement is the whole design. A pair of CJK characters is the
62
+ * unit that makes Chinese retrievable at all — without it a space-free turn is
63
+ * one indivisible token — but it is also the unit that makes Chinese noisy:
64
+ * measured on a real 54-memory store, "该插件是否有日志" shares the isolated
65
+ * pair 插件 with a memory about an unrelated cost-meter bug and scores 12,
66
+ * above any floor low enough to admit a paraphrase. Requiring the pair to sit
67
+ * inside a shared run of three characters means the query and the memory must
68
+ * use the same *phrase* (插件日志), not merely the same characters.
69
+ */
70
+ readonly strongTerms: number;
71
+ /** True when the whole query appears in a strong field. */
72
+ readonly phrase: boolean;
73
+ }
74
+ /** Most body occurrences of one term that still earn score. */
75
+ export declare const BODY_TERM_CAP = 4;
76
+ /** Split text into searchable terms: ASCII words and CJK character bigrams.
77
+ *
78
+ * A CJK run also contributes bigrams of its neighbours, so "该插件是否有日志"
79
+ * yields "该插","插件","件是","是否","否有","有日","日志". A one-character run
80
+ * contributes itself, since a lone ideograph has no bigram.
81
+ *
82
+ * @param text - raw text.
83
+ * @returns lowercase terms; a run that yields nothing contributes nothing.
84
+ */
85
+ export declare function tokenize(text: string): string[];
86
+ /**
87
+ * A term's weight for scoring purposes.
88
+ *
89
+ * One CJK bigram is a much weaker claim than one Latin word — "日志" occurs in
90
+ * countless texts where "logging" does not — so a bigram earns less. Without
91
+ * this every Chinese question would clear the recall gate on noise alone.
92
+ *
93
+ * @param term - one term from {@link tokenize}.
94
+ * @returns a multiplier in `(0, 1]`.
95
+ */
96
+ export declare function termWeight(term: string): number;
97
+ /**
98
+ * Build (or reuse) the term index for one entry array.
99
+ *
100
+ * @param entries - entries from one scope, in list order.
101
+ * @returns term → ascending entry indexes.
102
+ */
103
+ export declare function termIndex(entries: readonly MemoryEntry[]): Map<string, number[]>;
104
+ /**
105
+ * The entries that share at least one token with the query.
106
+ *
107
+ * @param entries - the scope's entries.
108
+ * @param query - the turn's text.
109
+ * @returns candidates, or the whole array when the prefilter would be unreliable.
110
+ */
111
+ export declare function prefilterEntries(entries: readonly MemoryEntry[], query: string): readonly MemoryEntry[];
112
+ /**
113
+ * Score and evidence of one entry against one already-extracted query.
114
+ *
115
+ * Prefer this over {@link relevanceOfOne} when the caller has to *justify* a
116
+ * decision: a recall delta is bounded by evidence, not only by score.
117
+ *
118
+ * @param entry - candidate entry.
119
+ * @param query - one query string; empty scores zero.
120
+ * @returns the score and the evidence behind it.
121
+ */
122
+ export declare function matchOf(entry: MemoryEntry, query: string): {
123
+ score: number;
124
+ evidence: MatchEvidence;
125
+ };
126
+ /**
127
+ * Relevance of one entry to one already-extracted query string.
128
+ *
129
+ * @param entry - candidate entry.
130
+ * @param query - one query string; empty scores zero.
131
+ * @returns a non-negative score; `0` means no match.
132
+ */
133
+ export declare function relevanceOfOne(entry: MemoryEntry, query: string): number;
134
+ /**
135
+ * Relevance of one entry to a whole user turn.
136
+ *
137
+ * A turn is many sentences and only one of them is usually about any single
138
+ * memory, so scoring the turn as one string buries a precise hit inside a wall
139
+ * of unrelated words. Each sentence is scored on its own and the best one wins;
140
+ * an entry that several sentences mention earns a small bonus, because two
141
+ * independent mentions is stronger evidence than one.
142
+ *
143
+ * @param entry - candidate entry.
144
+ * @param query - the raw turn or search text.
145
+ * @returns a non-negative score; `0` means no match.
146
+ */
147
+ export declare function relevanceOf(entry: MemoryEntry, query: string): number;
148
+ /**
149
+ * Half-life of a memory's recency weight, in days.
150
+ *
151
+ * Deliberately short next to the store's own lifetime. It was 90 days, which on
152
+ * an eleven-day-old store distinguishes almost nothing: the recency term spanned
153
+ * 0.94–1.00 while the use-count term spanned 1.0–4.5, so the injected summary
154
+ * was decided by how often a memory had been read before. Measured on a real
155
+ * store that pinned the same six entries — a plugin's logger threshold, a
156
+ * sidebar adapter, a model catalog — into every unrelated session, because those
157
+ * are the memories the harness's own plugin work kept reading. Thirty days keeps
158
+ * recency meaningful against the use term without letting a quarter-old
159
+ * convention fall out of reach.
160
+ */
161
+ export declare const RECENCY_HALF_LIFE_DAYS = 30;
162
+ /**
163
+ * Floor on the recency weight.
164
+ *
165
+ * Without it a two-year-old memory scores essentially zero and can never
166
+ * outrank a fresh, weaker match, however exact its own — the opposite of what
167
+ * durable memory is for.
168
+ */
169
+ export declare const DECAY_FLOOR = 0.25;
170
+ /**
171
+ * The most recent moment an entry was written or actually read.
172
+ *
173
+ * Being *surfaced* is deliberately not part of this. The summary lists a bounded
174
+ * number of entries, and counting "listed in the summary" as fresh attention
175
+ * turns that bound into a lock: an entry that makes the cut refreshes its own
176
+ * recency on every injection and keeps every newcomer out. Measured on a real
177
+ * store, the injected set sat at exactly the 12-per-scope cap, every member at
178
+ * maximum recency, while two thirds of the store had never been read at all —
179
+ * including the entry that explicitly corrected one of the listed ones.
180
+ *
181
+ * Surfacing still counts where the question is "does this memory still earn its
182
+ * place on disk"; that rule is `lastAttention` in `retention.ts`, which is the
183
+ * only thing that ever archives a memory.
184
+ *
185
+ * @param entry - candidate entry.
186
+ * @returns Unix epoch milliseconds.
187
+ */
188
+ export declare function recencyOf(entry: MemoryEntry): number;
189
+ /**
190
+ * How fast an entry's recency weight decays.
191
+ *
192
+ * A memory not read or rewritten for a quarter is worth half as much as one
193
+ * touched today, and the weight never falls below {@link DECAY_FLOOR}: recency
194
+ * orders memories, it does not erase them.
195
+ * @param entry - candidate entry.
196
+ * @param now - injected clock.
197
+ * @returns a weight in `[DECAY_FLOOR, 1]`.
198
+ */
199
+ export declare function decayOf(entry: MemoryEntry, now?: number): number;
200
+ /**
201
+ * Multiplier for a memory a person or the model wrote deliberately.
202
+ *
203
+ * `auto` entries are a background extractor's guess about a transcript;
204
+ * `tool`/`user` entries are somebody's statement. When they disagree the
205
+ * explicit one is the newer truth, and without a thumb on the scale the guess
206
+ * wins purely because it has been around long enough to collect reads.
207
+ *
208
+ * Raised from 1.25 because that was not enough to matter: against a use term
209
+ * spanning 1.0–4.5 with a ten-use cap, a deliberately written entry lost to a
210
+ * heavily-read extracted one every time. Measured on a real store, all six
211
+ * hand-written global rules — including "never break the prompt cache" and
212
+ * "reconnaissance is read-only GET" — failed to reach any session's summary,
213
+ * while the twelve that did were all extracted notes.
214
+ *
215
+ * Two, because the bonus has to clear {@link AUTO_IMPORTANCE_CEILING} rather
216
+ * than merely approach it: at 1.6 a written rule still tied with a note that had
217
+ * been read five times, and the measured global half kept preferring the note.
218
+ */
219
+ export declare const EXPLICIT_SOURCE_BONUS = 2;
220
+ /**
221
+ * How much one recorded read is worth, and the cap on how far it can climb.
222
+ *
223
+ * Previously `1 + min(uses, 10) * 0.35`, which let a single read-count term
224
+ * outrank recency by four to one and flattened the top of the ranking into a
225
+ * four-way tie at the cap. The slope is smaller and the cap lower so that
226
+ * recency, explicitness and use count each still move the order.
227
+ */
228
+ export declare const USE_BONUS = 0.15;
229
+ /** @see USE_BONUS */
230
+ export declare const USE_CAP = 5;
231
+ /**
232
+ * Ceiling a purely read-accumulated entry can reach (see {@link importanceOf}).
233
+ *
234
+ * Exported because {@link EXPLICIT_SOURCE_BONUS} has to clear it for a hand
235
+ * written rule to outrank the busiest extracted note: with the bonus below
236
+ * `1 + USE_CAP * USE_BONUS` the injected global half stays a list of whatever
237
+ * the harness's own tooling happened to read most, which is exactly the state
238
+ * the slot audit measured.
239
+ */
240
+ export declare const AUTO_IMPORTANCE_CEILING: number;
241
+ /**
242
+ * How much an entry has earned its place: a small bonus per recorded use, and a
243
+ * larger one for having been written deliberately rather than inferred.
244
+ */
245
+ export declare function importanceOf(entry: MemoryEntry): number;
246
+ /**
247
+ * Lift for a memory whose claim came from the user.
248
+ *
249
+ * Deliberately smaller than {@link EXPLICIT_SOURCE_BONUS}: it breaks ties among
250
+ * memories that already matched the turn's words, it does not put somebody's
251
+ * preferences in front of the code they asked about — the lexical gate still
252
+ * decides reachability.
253
+ */
254
+ export declare const USER_VOICE_BONUS = 1.35;
255
+ /**
256
+ * How much a turn's time window lifts an entry whose *measurement* falls in it.
257
+ *
258
+ * A `snapshot` carries `asOf` — the day the number was read — and that is the
259
+ * one timestamp in the store that answers a date question exactly. The lift is
260
+ * roughly a body hit's worth: enough to reorder memories that all match the
261
+ * words of the turn, never enough to outrank a memory that matches them better.
262
+ * It multiplies relevance rather than joining it, so a time match alone can
263
+ * never recall an entry — the lexical gate still runs first.
264
+ */
265
+ export declare const TIME_MEASURED_BOOST = 1.5;
266
+ /**
267
+ * How much the window lifts an entry that was *learned* inside it.
268
+ *
269
+ * Weaker than {@link TIME_MEASURED_BOOST} on purpose: `createdAt` is when the
270
+ * memory was written, which for a conversation-derived memory is a good proxy
271
+ * for when the thing happened, but for a hand-written rule it is just when
272
+ * somebody typed it. Measured on the real store, 306 of 613 entries carry a
273
+ * session pointer, so the proxy holds for the extracted half and is a
274
+ * tie-breaker for the rest.
275
+ */
276
+ export declare const TIME_CREATED_BOOST = 1.15;
277
+ /**
278
+ * The multiplier a turn's time window applies to one entry.
279
+ *
280
+ * `undefined` (no time expression, or an entry with no timestamps) returns 1, so
281
+ * turns that name no date are scored exactly as before. An entry is never
282
+ * *penalised* for falling outside the window: a durable fact learned in March
283
+ * can still be the answer to a question about last week, and punishing it would
284
+ * hide the answer more often than it would sharpen the list.
285
+ *
286
+ * @param entry - candidate entry.
287
+ * @param range - the turn's window, when it named one.
288
+ * @returns a multiplier of at least 1.
289
+ */
290
+ export declare function timeBoost(entry: MemoryEntry, range: TimeRange | undefined): number;
291
+ /**
292
+ * Score one entry against a query: relevance × importance × recency decay × time.
293
+ *
294
+ * One formula for every ordering in the plugin — tool search, the injected
295
+ * summary, and the on-demand recall threshold — so "worth recalling" means the
296
+ * same thing everywhere and a knob tuned in one place holds in the others.
297
+ *
298
+ * @param entry - candidate entry.
299
+ * @param query - raw user/model query.
300
+ * @param now - clock used for the decay.
301
+ * @param range - the turn's time window, or `undefined` to resolve it from the
302
+ * query. Callers that score many entries for one turn should parse once with
303
+ * {@link parseTimeRange} and pass it in.
304
+ * @returns a non-negative score; `0` means the entry does not match.
305
+ */
306
+ export declare function scoreEntry(entry: MemoryEntry, query: string, now?: number, range?: TimeRange | null): number;
307
+ /**
308
+ * Both halves of one entry's number: what it matches, and what it deserves.
309
+ *
310
+ * They are multiplied together everywhere else, which makes a loss impossible to
311
+ * attribute by reading the output — and the two surfaces want opposite orders.
312
+ * Measured on the real store, ranking by `relevance` alone puts the expected
313
+ * entry in the top eight for **every** probe (7/7), while the multiplied score
314
+ * manages 5/7: 「怎么给 dsh 插件加日志才看得到」 loses to eight heavily-read
315
+ * explicit memories that share the word `dsh`, which 100 of the scope's 176
316
+ * entries carry. A caller that asked a *question* wants the first; a caller
317
+ * deciding what to volunteer unasked wants the second.
318
+ *
319
+ * @param entry - candidate entry.
320
+ * @param query - raw user/model query.
321
+ * @param now - clock used for the decay.
322
+ * @param range - the turn's time window, or `undefined` to resolve it.
323
+ * @returns relevance (`0` when the entry does not match) and the attention score.
324
+ */
325
+ export declare function rankEntry(entry: MemoryEntry, query: string, now?: number, range?: TimeRange | null): {
326
+ relevance: number;
327
+ score: number;
328
+ };
329
+ /**
330
+ * Rank one entry against a query, reporting the evidence behind the number.
331
+ *
332
+ * The recall gate compares relevance AND evidence, so a caller that has to
333
+ * explain a decision ("why was nothing recalled?") needs both parts plus the
334
+ * sentence that produced them.
335
+ *
336
+ * @param entry - candidate entry.
337
+ * @param query - raw turn or search text.
338
+ * @param now - clock used for the decay.
339
+ * @param range - the turn's time window, or `undefined` to resolve it.
340
+ * @returns relevance, the decayed score, the matching sentence, and evidence.
341
+ */
342
+ export declare function explainEntry(entry: MemoryEntry, query: string, now?: number, range?: TimeRange | null): {
343
+ relevance: number;
344
+ score: number;
345
+ best: string;
346
+ evidence: MatchEvidence;
347
+ };
348
+ /**
349
+ * How much clearer than the floor a single strong term has to be on its own.
350
+ *
351
+ * One substantive term is half the evidence two are, so it only counts when the
352
+ * score it produced is decisive rather than marginal. Without this the structural
353
+ * gate would admit a memory that shares one distinctive word with the turn.
354
+ */
355
+ export declare const QUALIFIED_SCORE_FACTOR = 2;
356
+ /** One entry's verdict on whether a turn is actually about it. */
357
+ export interface MatchCredit {
358
+ /** True when the entry is about the turn, not merely adjacent to it. */
359
+ readonly about: boolean;
360
+ /** True when the score is decisive enough to carry a single strong term. */
361
+ readonly distinctive: boolean;
362
+ /** True when the evidence gate is satisfied on its own terms. */
363
+ readonly credited: boolean;
364
+ /** Lexical relevance, before importance and decay. */
365
+ readonly relevance: number;
366
+ /** Relevance weighted by importance and recency, for ordering candidates. */
367
+ readonly score: number;
368
+ /** The sentence that produced the score. */
369
+ readonly best: string;
370
+ /** The structural evidence behind the score. */
371
+ readonly evidence: MatchEvidence;
372
+ }
373
+ /** How strictly {@link matchCredit} applies its structural gate. */
374
+ export interface CreditOptions {
375
+ /**
376
+ * Whether ONE strong term plus a decisive score is enough on its own.
377
+ *
378
+ * Right for a recall delta, wrong for the summary's topical tier. The recall
379
+ * path exists to answer "does this turn touch something already known", and a
380
+ * one-keyword turn ("端口 3080") is exactly what it must catch. The summary
381
+ * instead decides who outranks a well-read memory, so it demands the full
382
+ * term count: with the escape hatch on, measured on the real store, a query
383
+ * about how the summary is ranked put twelve memories in the topical tier on
384
+ * one shared term each, and the tier stopped discriminating — the ranking
385
+ * reverted to history with a gate in front of it.
386
+ */
387
+ readonly singleTerm?: boolean;
388
+ /** Clock used for the decayed score. */
389
+ readonly now?: number;
390
+ /**
391
+ * The turn's time window, or `null` for "none".
392
+ *
393
+ * Omitted, the window is resolved from the query — right for a one-off call,
394
+ * wrong for a loop over the whole store, where the same regex sweep would run
395
+ * once per entry on every step. The recall path parses once per turn and
396
+ * passes the result here.
397
+ */
398
+ readonly range?: TimeRange | null;
399
+ /**
400
+ * Whether one query term is too common in this scope to be evidence.
401
+ *
402
+ * `minTerms` asks for two pieces of *evidence*, but a word present in half the
403
+ * store is evidence of nothing: measured here, `dsh` appears in 100 of 176
404
+ * entries and any turn mentioning it primes dozens of memories to pass the
405
+ * two-term rule on `dsh` plus one more common word. Dropping hub terms from the
406
+ * count leaves the relevance floor, the phrase rule and the single-term escape
407
+ * hatch untouched — this only changes what "two terms" means.
408
+ */
409
+ readonly hub?: (term: string) => boolean;
410
+ }
411
+ /**
412
+ * Whether one entry is genuinely about one turn — the single decision behind
413
+ * both the injected summary's topical tier and the on-demand recall gate.
414
+ *
415
+ * Two gates that answer different questions, and neither replaces the other:
416
+ *
417
+ * - **FLOOR** (`minScore`) is the caller's strictness knob: the relevance an
418
+ * entry has to reach at all.
419
+ * - **CREDIT** is structural, and a score threshold cannot replace it for
420
+ * Chinese. Measured on a real 54-memory store, 「该插件是否有日志」 shares the
421
+ * isolated bigram 插件 with a memory about an unrelated cost-meter bug and
422
+ * scores 12 — above any floor low enough to admit a paraphrase. Credit asks
423
+ * instead for substantive terms: a Latin word of three characters or more, or
424
+ * a CJK pair inside a shared run of three or more, which is the only Chinese
425
+ * term a merely common pair cannot fake.
426
+ *
427
+ * A whole-query hit stands alone; otherwise `minTerms` are required, with one
428
+ * allowed when the score is {@link QUALIFIED_SCORE_FACTOR} times the floor and
429
+ * {@link CreditOptions.singleTerm} leaves that escape hatch open.
430
+ *
431
+ * This lives here, once, because the summary and the recall path used to spell
432
+ * the rule out separately and the two copies had already drifted apart.
433
+ *
434
+ * @param entry - candidate entry.
435
+ * @param query - the raw turn or search text.
436
+ * @param minScore - the relevance floor.
437
+ * @param minTerms - strong terms required when the score is not decisive.
438
+ * @param options - gate strictness and clock.
439
+ * @returns the verdict with the evidence behind it.
440
+ */
441
+ export declare function matchCredit(entry: MemoryEntry, query: string, minScore: number, minTerms: number, options?: CreditOptions): MatchCredit;
442
+ /**
443
+ * Query terms too common in one scope to count as evidence.
444
+ *
445
+ * Document frequency, computed over the same strong fields the evidence rule
446
+ * reads (title, keys, tags, `appliesTo`) so the two agree on what "this memory is
447
+ * about the term" means. A term present in more than `maxDf` of the scope is a
448
+ * hub: `dsh` in a DSH-plugin store, `插件` in any store written by an agent that
449
+ * keeps talking about its own plugins.
450
+ *
451
+ * This is deliberately NOT the ranking's document-frequency discount the README
452
+ * records as measured-and-rejected. That one tried to change which memory wins;
453
+ * this one only decides what counts as evidence, and the two failures are
454
+ * different: a hub term never made a bad memory rank first, it made two unrelated
455
+ * memories look like two independent signals.
456
+ *
457
+ * @param entries - every entry in the scope.
458
+ * @param maxDf - share of the scope above which a term is a hub; `0` disables.
459
+ * @returns a predicate over lowercase terms.
460
+ */
461
+ export declare function hubTerms(entries: readonly MemoryEntry[], maxDf: number): (term: string) => boolean;
462
+ /** Filter options accepted by {@link searchMemories}. */
463
+ export interface SearchOptions {
464
+ /** Only consider these scopes. */
465
+ readonly scopes?: readonly MemoryScope[];
466
+ /** Only consider entries carrying every one of these tags. */
467
+ readonly tags?: readonly string[];
468
+ /** Only consider entries of these kinds. */
469
+ readonly kinds?: readonly MemoryKind[];
470
+ /** Maximum hits returned. */
471
+ readonly limit?: number;
472
+ /** Clock used for the recency tie-break; injected for deterministic tests. */
473
+ readonly now?: number;
474
+ /**
475
+ * Follow the top hits one hop along shared keys and tags, and let what they
476
+ * link to fill the slots the direct matches left empty.
477
+ *
478
+ * Off by default because a caller that wants "what matches these words" — the
479
+ * settings page's search box is exactly that — should get what it asked for.
480
+ * The model-facing search turns it on: it is asking "what do we know about
481
+ * this", and the answer includes the entries filed under the same aliases.
482
+ */
483
+ readonly expand?: boolean;
484
+ }
485
+ /**
486
+ * Most direct hits used as seeds for the one-hop expansion.
487
+ *
488
+ * Three, because a hop from a weak match is a guess about a guess: the seeds are
489
+ * the entries the turn actually matched, and only their own links are followed.
490
+ */
491
+ export declare const EXPAND_SEEDS = 3;
492
+ /**
493
+ * Keys or tags two entries must share before either can pull the other in.
494
+ *
495
+ * Two, for the same reason the recall gate asks for two substantive terms: one
496
+ * shared tag is the memory equivalent of a common word. `sqlite` alone links
497
+ * every database note in the store; `sqlite` plus `state.db` is a claim that the
498
+ * two entries are about the same thing.
499
+ */
500
+ export declare const EXPAND_MIN_SHARED = 2;
501
+ /**
502
+ * A related entry's score, as a fraction of the seed it was reached from.
503
+ *
504
+ * Spreading activation, in one line: a neighbour inherits a fixed fraction of
505
+ * the activation of the node that lit it up. It was first written as a fraction
506
+ * of the WEAKEST direct hit, so that a hop could never displace a real match —
507
+ * which sounds safe and is useless. The real-store eval showed why: a query can
508
+ * match forty entries on one shared word each, and every one of them outranks a
509
+ * hop that is pegged to the weakest of the top three. 「注入相关性的排查一共分了
510
+ * 几轮」 left all four rounds out of the top five in every configuration.
511
+ *
512
+ * Tying the score to its own seed keeps the useful part of the old property —
513
+ * a hop never outranks the node it came from — while letting a neighbour of the
514
+ * *best* match beat entries that merely share a common word with the turn.
515
+ */
516
+ export declare const EXPAND_FACTOR = 0.4;
517
+ /**
518
+ * Share of a scope that may carry a link before it stops being an edge.
519
+ *
520
+ * A key or tag on more than half the entries is the scope's own name, not a
521
+ * relationship: in the plugin's own project scope `dsh-cross-memory` sits on 22 of
522
+ * 29 entries, and `--links` measured 18 of that scope's 48 hop-able pairs
523
+ * sharing nothing but such links (against 0 of 785 in the global scope). Those
524
+ * hops fired, scored like real ones, and carried no information. Ignoring the
525
+ * ubiquitous links removes them without a rarity threshold that would have
526
+ * silently disabled the mechanism in small scopes, where every link looks
527
+ * common because the scope has four entries.
528
+ */
529
+ export declare const EXPAND_GENERIC_SHARE = 0.5;
530
+ /**
531
+ * The link information that earns the full allowance.
532
+ *
533
+ * Two, because that is what two wholly specific links are worth (`1 - 1/N` each
534
+ * in a scope of any size). A hop backed by one rare alias and one common tag
535
+ * lands around half; a hop backed by two broad tags lands at a quarter and
536
+ * stays behind everything else.
537
+ */
538
+ export declare const EXPAND_WEIGHT_FULL = 2;
539
+ /** Most related entries one search may add. */
540
+ export declare const EXPAND_MAX = 3;
541
+ /**
542
+ * Entries reachable from the direct hits by following shared keys/tags.
543
+ *
544
+ * The deterministic stand-in for the graph channel in a memory architecture like
545
+ * Hindsight's: instead of embedding entities, it uses the aliases a memory is
546
+ * already filed under as edges. 「你了解我的账户吗」 matches one fragment about
547
+ * the account; the other three carry the same `keys`, and this is what surfaces
548
+ * them together — without a model call and without an index.
549
+ *
550
+ * @param groups - per-scope entry lists, broadest first.
551
+ * @param seeds - the direct hits whose links are followed.
552
+ * @param options - the same filters as {@link searchMemories}, plus the ids to
553
+ * exclude (the seeds themselves: an entry is not its own neighbour).
554
+ * @returns related hits, strongest first, with the seed each came from.
555
+ */
556
+ export declare function relatedHits(groups: readonly ScopeEntries[], seeds: readonly MemoryHit[], options?: SearchOptions & {
557
+ readonly exclude?: ReadonlySet<string>;
558
+ }): MemoryHit[];
559
+ /** One scope's entries plus the label to report them under. */
560
+ export interface ScopeEntries {
561
+ /** The scope these entries came from. */
562
+ readonly scope: MemoryScope;
563
+ /** Model-facing label, e.g. `global` or `project:dsh-cross-memory`. */
564
+ readonly label: string;
565
+ /** The entries. */
566
+ readonly entries: readonly MemoryEntry[];
567
+ }
568
+ /**
569
+ * Rank stored entries against a query across the supplied scopes.
570
+ * @param groups - per-scope entry lists, broadest first.
571
+ * @param query - raw query; empty returns nothing.
572
+ * @param options - scope, tag, and limit filters.
573
+ * @returns hits ordered by descending relevance, the attention score breaking ties.
574
+ */
575
+ export declare function searchMemories(groups: readonly ScopeEntries[], query: string, options?: SearchOptions): MemoryHit[];
576
+ /**
577
+ * Select entries without a text query — used by `memory_search`'s browse mode
578
+ * and by the injector.
579
+ * @param groups - per-scope entry lists, broadest first.
580
+ * @param options - scope, tag, and limit filters.
581
+ * @returns entries ordered by descending update time.
582
+ */
583
+ export declare function browseMemories(groups: readonly ScopeEntries[], options?: SearchOptions): MemoryHit[];
@@ -0,0 +1,71 @@
1
+ import type { SkillDraft } from './consolidate.js';
2
+ /** Normalize a proposed name into the harness grammar, or `undefined`. */
3
+ export declare function normalizeSkillName(value: string): string | undefined;
4
+ /**
5
+ * Render one draft as the markdown the harness loader reads.
6
+ * @param draft - the proposed skill.
7
+ * @returns a `SKILL.md` body with the required frontmatter.
8
+ */
9
+ export declare function renderSkillFile(draft: SkillDraft): string;
10
+ /** Where skill drafts live inside the memory store. */
11
+ export declare function draftRoot(memoriesDir: string): string;
12
+ /** Where the harness discovers promoted skills. */
13
+ export declare function promotionRoot(dshHome: string): string;
14
+ /**
15
+ * Write or replace one skill draft in the memory store.
16
+ *
17
+ * The write is atomic at the file level (a temp file renamed over the target),
18
+ * so a crash cannot leave a half-written `SKILL.md` that the loader would then
19
+ * try to parse.
20
+ *
21
+ * @param memoriesDir - the memory store root.
22
+ * @param draft - the skill to stage.
23
+ * @returns the absolute path of the staged file.
24
+ */
25
+ export declare function writeDraft(memoriesDir: string, draft: SkillDraft): Promise<string>;
26
+ /** One staged draft as reported to a human. */
27
+ export interface StagedSkill {
28
+ /** Skill name. */
29
+ readonly name: string;
30
+ /** Description from the draft's frontmatter, when present. */
31
+ readonly description: string;
32
+ /** Absolute path of the draft file. */
33
+ readonly path: string;
34
+ }
35
+ /**
36
+ * List the staged drafts that still need a human.
37
+ *
38
+ * `promote` copies rather than moves, so the draft outlives the promotion on
39
+ * purpose — it is the provenance. The cost was the notice: the banner kept
40
+ * counting promoted skills as pending, and on a real store it read "4 pending"
41
+ * when three of them had been live for a week. A draft whose promoted copy is
42
+ * byte-identical is not waiting for anybody, so it is not listed.
43
+ *
44
+ * @param memoriesDir - the memory store root.
45
+ * @param dshHome - the harness home; when given, already-promoted drafts are skipped.
46
+ * @returns the drafts still pending, name-sorted.
47
+ */
48
+ export declare function listDrafts(memoriesDir: string, dshHome?: string): Promise<StagedSkill[]>;
49
+ /**
50
+ * Copy one staged draft into the harness's skill root.
51
+ *
52
+ * Copies rather than moves, so the memory store keeps the provenance and the
53
+ * promoted file is an independent artifact a human can edit. Re-promoting an
54
+ * unchanged draft is a no-op, which is what makes it a safe retry.
55
+ *
56
+ * It REFUSES one case: overwriting a promoted copy that is newer than the draft.
57
+ * A draft is staged once and then forgotten while the promoted skill keeps being
58
+ * edited, so "re-promote" is the one action that can silently roll a live skill
59
+ * back — measured on a real store, one draft was four days older than its
60
+ * promoted copy and still said "must restart the host 2.0.17" where the live
61
+ * skill said "2.0.18-beta.1 can hot-mount".
62
+ *
63
+ * @param memoriesDir - the memory store root.
64
+ * @param dshHome - the harness home whose `skills/` the loader scans.
65
+ * @param name - the draft to promote.
66
+ * @returns the absolute path of the promoted skill, or `undefined` when no such draft exists.
67
+ * @throws when the promoted copy is newer than the draft it would replace.
68
+ */
69
+ export declare function promote(memoriesDir: string, dshHome: string, name: string): Promise<string | undefined>;
70
+ /** Remove one staged draft. */
71
+ export declare function discardDraft(memoriesDir: string, name: string): Promise<boolean>;