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
package/lib/time.js ADDED
@@ -0,0 +1,303 @@
1
+ /**
2
+ * Resolving the stretch of time a turn is talking about.
3
+ *
4
+ * The store has always *carried* time — `createdAt` says when a fact was
5
+ * learned, `asOf` says when a `snapshot` reading was measured — but nothing ever
6
+ * *asked* about it. A turn like 「上个月那个发票接口的问题是怎么解决的」 shares
7
+ * 发票/接口 with every invoice memory ever written, so the ranking falls back to
8
+ * importance and recency and hands back the same three entries it hands back for
9
+ * every other invoice question. The date the user actually said, which is the
10
+ * one thing that would cut the list down to the right week, was ignored.
11
+ *
12
+ * This module is the missing half: turn free text into a half-open epoch range,
13
+ * deterministically and without a model call. It is deliberately narrow. It
14
+ * recognises the shapes people really type — 今天/昨天/前天, 上周/上个月/去年,
15
+ * 去年春天, 最近三天, 3 天前, 2026-09-20, 9 月 20 日 — and returns `undefined`
16
+ * for everything else. A false positive is worse than a miss: it silently
17
+ * reorders results for a turn that was not about time at all, and the reader has
18
+ * no way to see why.
19
+ *
20
+ * Two design choices worth keeping:
21
+ *
22
+ * - **Local time.** Windows are computed with the host's local calendar, the
23
+ * same way `peakHours` is, because the user's "昨天" means their wall clock,
24
+ * not UTC. A memory system that answered 今天 with yesterday's date between
25
+ * 00:00 and 08:00 in Shanghai would be worse than one that ignored dates.
26
+ * - **Half-open ranges.** `[start, end)` so an entry measured exactly at
27
+ * midnight belongs to one day, not two.
28
+ *
29
+ * @module dsh-cross-memory/time
30
+ */
31
+ /** Chinese digit characters that appear in dates. */
32
+ const DIGITS = {
33
+ 一: 1, 二: 2, 两: 2, 三: 3, 四: 4, 五: 5, 六: 6, 七: 7, 八: 8, 九: 9, 十: 10,
34
+ };
35
+ /**
36
+ * Read a number written as Arabic digits or Chinese numerals.
37
+ *
38
+ * Only the shapes dates use: 3, 三, 十, 十一, 二十, 三十一.
39
+ *
40
+ * @param text - the matched text.
41
+ * @returns the number, or `undefined` when it is neither form.
42
+ */
43
+ export function cnNumber(text) {
44
+ if (/^\d+$/.test(text)) {
45
+ const value = Number(text);
46
+ return Number.isFinite(value) ? value : undefined;
47
+ }
48
+ if (!/^[一二两三四五六七八九十]+$/u.test(text))
49
+ return undefined;
50
+ const tens = /^([一二两三四五六七八九])?十([一二三四五六七八九])?$/u.exec(text);
51
+ if (tens !== null) {
52
+ const high = tens[1] === undefined ? 1 : DIGITS[tens[1]] ?? 0;
53
+ const low = tens[2] === undefined ? 0 : DIGITS[tens[2]] ?? 0;
54
+ return high * 10 + low;
55
+ }
56
+ return DIGITS[text];
57
+ }
58
+ /** Midnight local time of the day `date` falls in, shifted by whole days. */
59
+ function startOfDay(now, dayOffset = 0) {
60
+ const date = new Date(now);
61
+ return new Date(date.getFullYear(), date.getMonth(), date.getDate() + dayOffset).getTime();
62
+ }
63
+ /** Midnight local time of the Monday of `now`'s week, shifted by whole weeks. */
64
+ function startOfWeek(now, weekOffset = 0) {
65
+ const date = new Date(now);
66
+ const monday = (date.getDay() + 6) % 7;
67
+ return new Date(date.getFullYear(), date.getMonth(), date.getDate() - monday + weekOffset * 7).getTime();
68
+ }
69
+ /** First instant of the month `months` away from the one `now` falls in. */
70
+ function startOfMonth(now, months = 0) {
71
+ const date = new Date(now);
72
+ return new Date(date.getFullYear(), date.getMonth() + months, 1).getTime();
73
+ }
74
+ /** First instant of the year `years` away from the one `now` falls in. */
75
+ function startOfYear(now, years = 0) {
76
+ return new Date(new Date(now).getFullYear() + years, 0, 1).getTime();
77
+ }
78
+ /** Month index (0-based) a season starts in. Winter is handled separately. */
79
+ const SEASON_START = { 春: 2, 夏: 5, 秋: 8, 冬: 11 };
80
+ /**
81
+ * The window a season covers in a given year.
82
+ *
83
+ * Winter is the awkward one: 冬天 spans December into the next March, so its
84
+ * end is computed from the following year. That is what 「去年冬天」 means to a
85
+ * reader — the December-to-February stretch, not "December only".
86
+ *
87
+ * @param now - the clock.
88
+ * @param season - one of 春/夏/秋/冬.
89
+ * @param yearOffset - years relative to `now`'s year.
90
+ * @returns the half-open window.
91
+ */
92
+ function seasonRange(now, season, yearOffset) {
93
+ const year = new Date(now).getFullYear() + yearOffset;
94
+ const start = SEASON_START[season];
95
+ if (start === undefined)
96
+ return { start: now, end: now, label: season };
97
+ const from = new Date(year, start, 1).getTime();
98
+ const to = season === '冬' ? new Date(year + 1, 2, 1).getTime() : new Date(year, start + 3, 1).getTime();
99
+ return { start: from, end: to, label: `${yearOffset === 0 ? '今年' : yearOffset === -1 ? '去年' : `${year}年`}${season}天` };
100
+ }
101
+ /** Year words, mapped to their offset from the current year. */
102
+ const YEAR_WORDS = {
103
+ 今年: 0, 本年: 0, 这一年: 0,
104
+ 去年: -1, 上年: -1, 上一年: -1, 前年: -2,
105
+ 明年: 1, 下一年: 1,
106
+ };
107
+ /** Day words, mapped to their offset from today. */
108
+ const DAY_WORDS = {
109
+ 今天: 0, 今日: 0, 本日: 0,
110
+ 昨天: -1, 昨日: -1, 前天: -2, 前日: -2,
111
+ 明天: 1, 明日: 1, 后天: 2,
112
+ };
113
+ /** Week words, mapped to their offset from this week. */
114
+ const WEEK_WORDS = {
115
+ 本周: 0, 这周: 0, 这一周: 0, 本星期: 0, 这星期: 0, 这个星期: 0,
116
+ 上周: -1, 上星期: -1, 上个星期: -1, 上一周: -1, 上个周: -1,
117
+ 下周: 1, 下星期: 1, 下个星期: 1, 下一周: 1,
118
+ };
119
+ /** Month words, mapped to their offset from this month. */
120
+ const MONTH_WORDS = {
121
+ 本月: 0, 这个月: 0, 这一个月: 0,
122
+ 上个月: -1, 上月: -1, 上一个月: -1,
123
+ 下个月: 1, 下月: 1, 下一个月: 1,
124
+ };
125
+ /** Unit words for "N units ago" / "the last N units", in days. */
126
+ const UNIT_DAYS = {
127
+ 天: 1, 日: 1, 周: 7, 星期: 7, 个星期: 7, 个月: 30, 月: 30, 年: 365,
128
+ };
129
+ /**
130
+ * The window a turn refers to, or `undefined` when it names no time.
131
+ *
132
+ * Rules are tried most-specific first, so "2026 年 3 月" resolves as a month
133
+ * rather than falling through to the bare "3 月" rule, and "去年春天" resolves
134
+ * as last year's spring rather than this year's.
135
+ *
136
+ * @param text - the raw turn or query.
137
+ * @param now - clock the relative expressions are resolved against.
138
+ * @returns the half-open window, or `undefined` when the text names no time.
139
+ */
140
+ export function parseTimeRange(text, now = Date.now()) {
141
+ const query = text.trim();
142
+ if (query.length === 0)
143
+ return undefined;
144
+ // ── Absolute dates ──────────────────────────────────────────────────────
145
+ // 2026-09-20, 2026/9/20, 2026年9月20日, 2026年9月, 2026-09
146
+ const absolute = /(\d{4})\s*[-/年]\s*(\d{1,2})\s*(?:[-/月]\s*(\d{1,2})\s*日?)?/.exec(query);
147
+ if (absolute !== null) {
148
+ const year = Number(absolute[1]);
149
+ const month = Number(absolute[2]);
150
+ if (month >= 1 && month <= 12) {
151
+ if (absolute[3] === undefined) {
152
+ return { start: new Date(year, month - 1, 1).getTime(), end: new Date(year, month, 1).getTime(), label: `${year}-${month}` };
153
+ }
154
+ const day = Number(absolute[3]);
155
+ if (day >= 1 && day <= 31) {
156
+ return {
157
+ start: new Date(year, month - 1, day).getTime(),
158
+ end: new Date(year, month - 1, day + 1).getTime(),
159
+ label: `${year}-${month}-${day}`,
160
+ };
161
+ }
162
+ }
163
+ }
164
+ // A bare year: 2026年 / 2026 年
165
+ const bareYear = /(\d{4})\s*年/u.exec(query);
166
+ if (bareYear !== null) {
167
+ const year = Number(bareYear[1]);
168
+ return { start: new Date(year, 0, 1).getTime(), end: new Date(year + 1, 0, 1).getTime(), label: `${year}年` };
169
+ }
170
+ // ── Year-qualified seasons and months ───────────────────────────────────
171
+ // 去年春天, 今年冬天, 去年 9 月, 前年3月. The unit is required: 去年3个问题 must
172
+ // not resolve to last March.
173
+ const YEARS = '今年|本年|去年|上年|上一年|前年|明年';
174
+ const qualifiedSeason = new RegExp(`(${YEARS})\\s*(春天|春季|夏天|夏季|秋天|秋季|冬天|冬季)`, 'u').exec(query);
175
+ if (qualifiedSeason !== null) {
176
+ const offset = YEAR_WORDS[qualifiedSeason[1]];
177
+ if (offset !== undefined)
178
+ return seasonRange(now, qualifiedSeason[2][0], offset);
179
+ }
180
+ const qualifiedMonth = new RegExp(`(${YEARS})\\s*([一二两三四五六七八九十\\d]{1,3})\\s*月`, 'u').exec(query);
181
+ if (qualifiedMonth !== null) {
182
+ const offset = YEAR_WORDS[qualifiedMonth[1]];
183
+ const month = cnNumber(qualifiedMonth[2]);
184
+ if (offset !== undefined && month !== undefined && month >= 1 && month <= 12) {
185
+ const year = new Date(now).getFullYear() + offset;
186
+ return { start: new Date(year, month - 1, 1).getTime(), end: new Date(year, month, 1).getTime(), label: `${qualifiedMonth[1]}${month}月` };
187
+ }
188
+ }
189
+ // ── Bare month-day and bare month ───────────────────────────────────────
190
+ // 9 月 20 日 / 九月二十日, then 3 月 / 三月
191
+ const monthDay = /([一二两三四五六七八九十\d]{1,3})\s*月\s*([一二两三四五六七八九十\d]{1,3})\s*[日号]/u.exec(query);
192
+ if (monthDay !== null) {
193
+ const month = cnNumber(monthDay[1]);
194
+ const day = cnNumber(monthDay[2]);
195
+ if (month !== undefined && day !== undefined && month >= 1 && month <= 12 && day >= 1 && day <= 31) {
196
+ const year = new Date(now).getFullYear();
197
+ return {
198
+ start: new Date(year, month - 1, day).getTime(),
199
+ end: new Date(year, month - 1, day + 1).getTime(),
200
+ label: `${month}月${day}日`,
201
+ };
202
+ }
203
+ }
204
+ const bareMonth = /(?:^|[^\d])([一二两三四五六七八九十\d]{1,3})\s*月(?!\s*[\d一二两三四五六七八九十])/u.exec(query);
205
+ if (bareMonth !== null) {
206
+ const month = cnNumber(bareMonth[1]);
207
+ if (month !== undefined && month >= 1 && month <= 12) {
208
+ const year = new Date(now).getFullYear();
209
+ return { start: new Date(year, month - 1, 1).getTime(), end: new Date(year, month, 1).getTime(), label: `${month}月` };
210
+ }
211
+ }
212
+ // ── Bare seasons ────────────────────────────────────────────────────────
213
+ // 春天/春季/夏天 … (a lone 春 only counts when it is written as 春天/春季)
214
+ const season = /(春天|春季|夏天|夏季|秋天|秋季|冬天|冬季)/u.exec(query);
215
+ if (season !== null) {
216
+ const range = seasonRange(now, season[1][0], 0);
217
+ return { ...range, label: season[1] };
218
+ }
219
+ // ── Counted intervals ───────────────────────────────────────────────────
220
+ // Two shapes, and they mean different things. 最近三天 / 近 3 天 / 过去两个月 is
221
+ // a window that *ends now* and *includes* the current day/month — three days
222
+ // means today and the two before it, so the start is `-(count - 1)`; 3 天前 /
223
+ // 两周前 / 5 个月前 is the single period that far back. Merging them would turn
224
+ // "三个月前那次事故" into "the last three months", which is exactly the kind of
225
+ // wrong-every-time answer the whole module exists to avoid.
226
+ const WINDOW = /(?:最近|近|过去)\s*([一二两三四五六七八九十\d]{1,3})\s*(个?[天日周月]|个?星期|年)/u.exec(query);
227
+ if (WINDOW !== null) {
228
+ const count = cnNumber(WINDOW[1]);
229
+ const unit = WINDOW[2];
230
+ const days = UNIT_DAYS[unit];
231
+ if (count !== undefined && days !== undefined && count > 0) {
232
+ const label = WINDOW[0];
233
+ if (unit === '年')
234
+ return { start: startOfYear(now, -(count - 1)), end: now, label };
235
+ if (unit === '月' || unit === '个月')
236
+ return { start: startOfMonth(now, -(count - 1)), end: now, label };
237
+ if (unit === '周' || unit === '星期' || unit === '个星期')
238
+ return { start: startOfWeek(now, -(count - 1)), end: now, label };
239
+ return { start: startOfDay(now, -(count * days) + 1), end: now, label };
240
+ }
241
+ }
242
+ const AGO = /([一二两三四五六七八九十\d]{1,3})\s*(个?[天日周月]|个?星期|年)\s*前/u.exec(query);
243
+ if (AGO !== null) {
244
+ const count = cnNumber(AGO[1]);
245
+ const unit = AGO[2];
246
+ const days = UNIT_DAYS[unit];
247
+ if (count !== undefined && days !== undefined && count > 0) {
248
+ const label = AGO[0];
249
+ if (unit === '年')
250
+ return { start: startOfYear(now, -count), end: startOfYear(now, -count + 1), label };
251
+ if (unit === '月' || unit === '个月')
252
+ return { start: startOfMonth(now, -count), end: startOfMonth(now, -count + 1), label };
253
+ if (unit === '周' || unit === '星期' || unit === '个星期')
254
+ return { start: startOfWeek(now, -count), end: startOfWeek(now, -count + 1), label };
255
+ return { start: startOfDay(now, -(count * days)), end: startOfDay(now, -(count * days) + 1), label };
256
+ }
257
+ }
258
+ // ── Single words ────────────────────────────────────────────────────────
259
+ for (const [word, offset] of Object.entries(DAY_WORDS)) {
260
+ if (query.includes(word)) {
261
+ return { start: startOfDay(now, offset), end: startOfDay(now, offset + 1), label: word };
262
+ }
263
+ }
264
+ for (const [word, offset] of Object.entries(WEEK_WORDS)) {
265
+ if (query.includes(word)) {
266
+ return { start: startOfWeek(now, offset), end: startOfWeek(now, offset + 1), label: word };
267
+ }
268
+ }
269
+ for (const [word, offset] of Object.entries(MONTH_WORDS)) {
270
+ if (query.includes(word)) {
271
+ return { start: startOfMonth(now, offset), end: startOfMonth(now, offset + 1), label: word };
272
+ }
273
+ }
274
+ for (const [word, offset] of Object.entries(YEAR_WORDS)) {
275
+ if (query.includes(word)) {
276
+ return { start: startOfYear(now, offset), end: startOfYear(now, offset + 1), label: word };
277
+ }
278
+ }
279
+ // ── English, just the shapes a mixed-language turn actually uses ────────
280
+ const lower = query.toLowerCase();
281
+ const english = [
282
+ [/\byesterday\b/, { start: startOfDay(now, -1), end: startOfDay(now, 0), label: 'yesterday' }],
283
+ [/\btoday\b/, { start: startOfDay(now, 0), end: startOfDay(now, 1), label: 'today' }],
284
+ [/\blast week\b/, { start: startOfWeek(now, -1), end: startOfWeek(now, 0), label: 'last week' }],
285
+ [/\blast month\b/, { start: startOfMonth(now, -1), end: startOfMonth(now, 0), label: 'last month' }],
286
+ [/\blast year\b/, { start: startOfYear(now, -1), end: startOfYear(now, 0), label: 'last year' }],
287
+ ];
288
+ for (const [pattern, range] of english)
289
+ if (pattern.test(lower))
290
+ return range;
291
+ return undefined;
292
+ }
293
+ /**
294
+ * Whether one instant falls inside a window.
295
+ * @param at - epoch milliseconds, or `undefined` when the entry carries no time.
296
+ * @param range - the window, or `undefined` when the turn named no time.
297
+ * @returns true when `at` is inside `[start, end)`.
298
+ */
299
+ export function within(at, range) {
300
+ if (at === undefined || range === undefined || at <= 0)
301
+ return false;
302
+ return at >= range.start && at < range.end;
303
+ }
package/lib/tool.js ADDED
@@ -0,0 +1,330 @@
1
+ /**
2
+ * The model-facing `memory` tool.
3
+ *
4
+ * One tool with an `action` switch keeps the tool catalog small while giving the
5
+ * model explicit control over scope: it must name `global` or `project` on every
6
+ * write, which is the decision the two-mode design is about.
7
+ *
8
+ * @module dsh-cross-memory/tool
9
+ */
10
+ import { defineTool } from '@deepseek-ai/dsh-tools';
11
+ import { renderEntry, renderEvidence, renderHit } from './render.js';
12
+ /** The scopes the model may name. */
13
+ const SCOPES = ['global', 'project'];
14
+ /** The kinds the model may name. */
15
+ const KINDS = ['fact', 'preference', 'knowledge', 'failure', 'procedure'];
16
+ /** The actions the model may take. */
17
+ const ACTIONS = ['write', 'search', 'read', 'forget', 'evidence'];
18
+ /** Description head: what the tool is for. */
19
+ const DESCRIPTION = [
20
+ 'Your durable cross-session memory. Use it to remember facts that should survive into future sessions, and to recall what earlier sessions learned.',
21
+ '',
22
+ 'When to write (action=write): the user states a preference or working style, a project decision is made with its reason, a command or workflow is discovered, an environment quirk or gotcha is found, or the user asks you to remember something. Do NOT write transient task state, secrets, credentials, or anything already captured in the repository.',
23
+ 'When to search (action=search): before starting work that may have been done before, when the user references earlier sessions, or when you need a detail the injected summary only previews.',
24
+ 'When a memory\'s wording, age, or context could change your answer, action=evidence returns the conversation it came from: what that session was about, and which memories it produced. Do not open evidence speculatively; open it when the memory alone is not enough.',
25
+ '',
26
+ 'Choose the scope deliberately on every write:',
27
+ '- "global" — true across every project: how the user likes to work, durable preferences, general tooling facts. A memory that would help on an unrelated repository belongs here.',
28
+ '- "project" — true only for the current workspace: its architecture, conventions, build/test commands, and gotchas.',
29
+ 'If a project memory turns out to be broadly useful, write it to "global" as well rather than moving it.',
30
+ '',
31
+ 'Titles are the identity: writing the same title again updates that memory instead of duplicating it.',
32
+ ].join('\n');
33
+ /** Output schema shared by every action. */
34
+ const OUTPUT_SCHEMA = {
35
+ type: 'object',
36
+ additionalProperties: false,
37
+ properties: {
38
+ ok: { type: 'boolean', required: true },
39
+ action: { type: 'string', required: true, enum: [...ACTIONS] },
40
+ message: { type: 'string', required: true },
41
+ results: {
42
+ type: 'array',
43
+ required: true,
44
+ items: {
45
+ type: 'object',
46
+ additionalProperties: false,
47
+ properties: {
48
+ id: { type: 'string', required: true },
49
+ scope: { type: 'string', required: true, enum: [...SCOPES] },
50
+ title: { type: 'string', required: true },
51
+ body: { type: 'string', required: true },
52
+ tags: { type: 'array', required: true, items: { type: 'string' } },
53
+ },
54
+ },
55
+ },
56
+ },
57
+ };
58
+ /**
59
+ * Register the `memory` tool.
60
+ * @param ctx - context carrying the tool registry.
61
+ * @param runtime - the memory runtime the tool operates on.
62
+ * @returns the exact disposer that unregisters the tool.
63
+ */
64
+ export function registerMemoryTool(ctx, runtime) {
65
+ return ctx.tools.register(defineTool({
66
+ name: 'memory',
67
+ description: DESCRIPTION,
68
+ parameters: {
69
+ action: {
70
+ type: 'string',
71
+ required: true,
72
+ enum: [...ACTIONS],
73
+ description: 'write (store a memory), search (find memories), read (show one by id), forget (delete one), evidence (show the session a memory came from).',
74
+ },
75
+ scope: {
76
+ type: 'string',
77
+ enum: [...SCOPES],
78
+ description: 'global for cross-project facts, project for this workspace. Required for write and forget; use it to filter search and read.',
79
+ },
80
+ title: {
81
+ type: 'string',
82
+ description: 'write: short imperative heading (max 80 chars). Also the identity used for deduplication.',
83
+ },
84
+ body: {
85
+ type: 'string',
86
+ description: 'write: the fact to remember, 1-4 sentences, self-contained.',
87
+ },
88
+ tags: {
89
+ type: 'array',
90
+ items: { type: 'string' },
91
+ description: 'write/search: lowercase keyword tags.',
92
+ },
93
+ keys: {
94
+ type: 'array',
95
+ items: { type: 'string' },
96
+ description: 'write: the words a future search must find this memory by — the other name for the same thing, the command, the file, the error text, the product\'s own term, and the English technical term when the memory is Chinese (and the reverse). Retrieval matches characters, not meaning, so a turn saying "system prompt" cannot reach a memory that only says "前缀缓存". Preferred over restating the body.',
97
+ },
98
+ kind: {
99
+ type: 'string',
100
+ enum: [...KINDS],
101
+ description: 'write: what kind of memory this is — preference (how the user wants work done), failure (what went wrong), procedure (an ordered recipe), knowledge (a non-obvious technique), fact (background). Defaults to fact. search: keep only this kind.',
102
+ },
103
+ appliesTo: {
104
+ type: 'string',
105
+ description: 'write: a short phrase saying when this memory matters, when the title does not make it obvious.',
106
+ },
107
+ durability: {
108
+ type: 'string',
109
+ enum: ['durable', 'snapshot'],
110
+ description: 'write: how long this memory stays true. durable (default) is a fact that does not move — a convention, a command, a constraint. snapshot is a reading taken at one moment — a count, a pass rate, the state of a system — and is listed with the date it was taken and archived once it is old. Use snapshot instead of writing a number as if it were a rule.',
111
+ },
112
+ asOf: {
113
+ type: 'string',
114
+ description: 'write: for durability=snapshot, when the reading was taken (ISO date or epoch ms). Defaults to now.',
115
+ },
116
+ pinned: {
117
+ type: 'boolean',
118
+ description: 'write: keep this memory in the injected summary whenever it fits, ahead of what the ranking would choose. For the few rules that must be visible in every session; pinned memories are also never archived for being unused.',
119
+ },
120
+ permanent: {
121
+ type: 'boolean',
122
+ description: 'write: never retire this memory on its own — retention, the per-scope cap, and unattended consolidation all leave it alone, and only /memories forget removes it. Costs no summary slot; use it for a rule that should survive until you change your mind (rewriting the same title is how you change your mind).',
123
+ },
124
+ query: {
125
+ type: 'string',
126
+ description: 'search: what to look for. Empty lists the most recent memories.',
127
+ },
128
+ id: {
129
+ type: 'string',
130
+ description: 'read/forget: the memory id from a search result.',
131
+ },
132
+ evidenceSession: {
133
+ type: 'string',
134
+ description: 'evidence: the session id whose evidence note to read. Use this when you already know the session; otherwise pass the memory id instead.',
135
+ },
136
+ limit: {
137
+ type: 'integer',
138
+ description: 'search: maximum hits (default 8, max 25).',
139
+ },
140
+ },
141
+ output: {
142
+ schema: OUTPUT_SCHEMA,
143
+ render: (_args, value) => [{ type: 'text', text: value.message }],
144
+ presentationMeta: (_args, value) => ({ action: value.action, count: value.results.length }),
145
+ },
146
+ // Reading evidence costs nothing, so it runs alongside other read-only calls.
147
+ isConcurrencySafe: (args) => args.action === 'search' || args.action === 'read' || args.action === 'evidence',
148
+ async execute(args, exec) {
149
+ const agent = exec.agent;
150
+ if (agent === undefined)
151
+ throw new Error('dsh-cross-memory: the memory tool requires an owning agent session');
152
+ const session = agent.session;
153
+ switch (args.action) {
154
+ case 'write': {
155
+ if (args.scope === undefined)
156
+ throw new Error('dsh-cross-memory: write requires an explicit scope (global or project)');
157
+ const title = args.title?.trim();
158
+ const body = args.body?.trim();
159
+ if (title === undefined || title.length === 0)
160
+ throw new Error('dsh-cross-memory: write requires a non-empty title');
161
+ if (body === undefined || body.length === 0)
162
+ throw new Error('dsh-cross-memory: write requires a non-empty body');
163
+ const asOf = args.asOf === undefined ? undefined : Date.parse(args.asOf);
164
+ if (args.asOf !== undefined && !Number.isFinite(asOf)) {
165
+ throw new Error('dsh-cross-memory: asOf must be an ISO date or epoch milliseconds');
166
+ }
167
+ const result = await runtime.write(session, {
168
+ scope: args.scope,
169
+ title: title.slice(0, 120),
170
+ body,
171
+ tags: args.tags ?? [],
172
+ ...args.kind === undefined ? {} : { kind: args.kind },
173
+ ...args.keys === undefined ? {} : { keys: args.keys },
174
+ ...args.appliesTo === undefined ? {} : { appliesTo: args.appliesTo },
175
+ ...args.durability === undefined ? {} : { durability: args.durability },
176
+ ...asOf === undefined ? {} : { asOf },
177
+ ...args.pinned === undefined ? {} : { pinned: args.pinned },
178
+ ...args.permanent === undefined ? {} : { permanent: args.permanent },
179
+ }, 'tool');
180
+ // The runtime may have stored a project draft globally: a session with
181
+ // no workspace of its own has no project scope, and reporting the scope
182
+ // the caller asked for would describe a memory that does not exist.
183
+ const scope = result.entry.scope;
184
+ const moved = scope === args.scope
185
+ ? ''
186
+ : ` This session has no workspace of its own, so it was stored as ${scope}.`;
187
+ const hint = scope === 'project'
188
+ ? ' If this fact also applies to unrelated projects, write a global copy of it too.'
189
+ : '';
190
+ return {
191
+ ok: true,
192
+ action: args.action,
193
+ message: `${result.action === 'created' ? 'Remembered' : 'Updated'} ${scope} memory "${result.entry.title}" (id=${result.entry.id}).${hint}${moved}`,
194
+ results: [toResult(result.entry)],
195
+ };
196
+ }
197
+ case 'search': {
198
+ const limit = Math.min(Math.max(args.limit ?? 8, 1), 25);
199
+ const scopes = args.scope === undefined ? undefined : [args.scope];
200
+ const tags = args.tags ?? [];
201
+ const query = args.query?.trim() ?? '';
202
+ const filters = {
203
+ ...scopes === undefined ? {} : { scopes },
204
+ tags,
205
+ ...args.kind === undefined ? {} : { kinds: [args.kind] },
206
+ limit,
207
+ };
208
+ const hits = query.length === 0
209
+ ? await runtime.browse(session, filters)
210
+ : await runtime.search(session, query, filters);
211
+ if (hits.length === 0) {
212
+ return {
213
+ ok: true,
214
+ action: args.action,
215
+ message: query.length === 0 ? 'No memories stored yet.' : `No memories match ${JSON.stringify(query)}.`,
216
+ results: [],
217
+ };
218
+ }
219
+ await runtime.recordUsage(session, hits.map((hit) => hit.entry));
220
+ return {
221
+ ok: true,
222
+ action: args.action,
223
+ message: [`${hits.length} ${hits.length === 1 ? 'memory' : 'memories'}:`, ...hits.map((hit, index) => renderHit(hit, index))].join('\n'),
224
+ results: hits.map((hit) => toResult(hit.entry)),
225
+ };
226
+ }
227
+ case 'read': {
228
+ const id = args.id?.trim();
229
+ if (id === undefined || id.length === 0)
230
+ throw new Error('dsh-cross-memory: read requires an id');
231
+ const order = args.scope === undefined ? ['project', 'global'] : [args.scope];
232
+ for (const scope of order) {
233
+ const entry = await runtime.read(session, scope, id);
234
+ if (entry !== undefined) {
235
+ return { ok: true, action: args.action, message: renderEntry(entry), results: [toResult(entry)] };
236
+ }
237
+ }
238
+ return { ok: false, action: args.action, message: `No memory with id ${JSON.stringify(id)}.`, results: [] };
239
+ }
240
+ case 'forget': {
241
+ const id = args.id?.trim();
242
+ if (id === undefined || id.length === 0)
243
+ throw new Error('dsh-cross-memory: forget requires an id');
244
+ const order = args.scope === undefined ? ['project', 'global'] : [args.scope];
245
+ for (const scope of order) {
246
+ if (await runtime.forget(session, scope, id)) {
247
+ return { ok: true, action: args.action, message: `Forgot ${scope} memory ${JSON.stringify(id)}.`, results: [] };
248
+ }
249
+ }
250
+ return { ok: false, action: args.action, message: `No memory with id ${JSON.stringify(id)}.`, results: [] };
251
+ }
252
+ case 'evidence': {
253
+ // The model can name the memory (the usual case: it just read one) or the
254
+ // session id directly when the note mentioned it.
255
+ let target = args.evidenceSession?.trim();
256
+ let context = '';
257
+ let trail = '';
258
+ const id = args.id?.trim();
259
+ if ((target === undefined || target.length === 0) && id !== undefined && id.length > 0) {
260
+ const order = args.scope === undefined ? ['project', 'global'] : [args.scope];
261
+ let found;
262
+ for (const scope of order) {
263
+ found = await runtime.read(session, scope, id, false);
264
+ if (found !== undefined)
265
+ break;
266
+ }
267
+ if (found === undefined) {
268
+ return { ok: false, action: args.action, message: `No memory with id ${JSON.stringify(id)}.`, results: [] };
269
+ }
270
+ context = `Memory ${JSON.stringify(found.title)}: `;
271
+ // The verbatim excerpt checked before the entry was written. Without
272
+ // it the reader can only open the session note, which is the model's
273
+ // own summary — the very thing the quote exists to be checked against.
274
+ if (found.quote !== undefined && found.quote.length > 0) {
275
+ const at = found.evidenceSeq === undefined ? '' : ` @seq ${found.evidenceSeq}`;
276
+ context += `\nevidence${at}: "${found.quote}"\n`;
277
+ }
278
+ // The merge trail. A consolidation folds several memories into one
279
+ // and archives the sources, so without this the only record of what
280
+ // the surviving claim was built from is a list of ids nobody can
281
+ // open. Resolved here, and a source that is really gone says so
282
+ // instead of being dropped silently.
283
+ const sources = found.derivedFrom ?? [];
284
+ if (sources.length > 0) {
285
+ const lines = [];
286
+ for (const source of sources) {
287
+ let origin;
288
+ for (const scope of order) {
289
+ origin = await runtime.read(session, scope, source, false);
290
+ if (origin !== undefined)
291
+ break;
292
+ }
293
+ lines.push(origin === undefined
294
+ ? ` - ${source} (no longer in the store)`
295
+ : ` - ${source}: ${origin.title}`);
296
+ }
297
+ trail = `merged from ${sources.length} ${sources.length === 1 ? 'memory' : 'memories'}:\n${lines.join('\n')}\n\n`;
298
+ }
299
+ target = found.sourceSession;
300
+ if (target === undefined || target.length === 0) {
301
+ const note = trail.length === 0 ? '' : `\n\n${trail.trimEnd()}`;
302
+ return { ok: true, action: args.action, message: `${context}this memory records no source session.${note}`, results: [toResult(found)] };
303
+ }
304
+ }
305
+ if (target === undefined || target.length === 0) {
306
+ throw new Error('dsh-cross-memory: evidence requires an id or evidenceSession');
307
+ }
308
+ const note = await runtime.store.readSessionNote(target);
309
+ if (note === undefined) {
310
+ return { ok: true, action: args.action, message: `${trail}No evidence note for session ${JSON.stringify(target)} (only mined sessions have one).`, results: [] };
311
+ }
312
+ return { ok: true, action: args.action, message: `${context}${trail}${renderEvidence(note)}`, results: [] };
313
+ }
314
+ /* c8 ignore next 2 -- the registry validates the action enum before dispatch */
315
+ default:
316
+ throw new Error(`dsh-cross-memory: unsupported action ${String(args.action)}`);
317
+ }
318
+ },
319
+ presentCall: (args) => ({
320
+ card: 'generic',
321
+ title: args.action === 'write' ? `Remember (${args.scope ?? 'auto'}): ${args.title ?? ''}` : `Memory ${args.action}`,
322
+ kind: 'other',
323
+ rawInput: args,
324
+ }),
325
+ }));
326
+ }
327
+ /** Project one entry onto the tool's result payload. */
328
+ function toResult(entry) {
329
+ return { id: entry.id, scope: entry.scope, title: entry.title, body: entry.body, tags: [...entry.tags] };
330
+ }