dsh-cross-memory 0.0.0-stage → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (152) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +253 -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 +1660 -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 +4482 -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 +163 -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 +490 -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 +341 -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 +142 -0
  57. package/lib/test/persona.test.js +86 -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 +238 -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 +76 -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 +246 -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,64 @@
1
+ /** Key one entry or usage row the same way, so the two lists can be joined. */
2
+ export function retentionKey(scope, id) {
3
+ return `${scope}\u0000${id}`;
4
+ }
5
+ /**
6
+ * The moment an entry last earned attention.
7
+ *
8
+ * Deliberately not `updatedAt` alone: consolidation rewrites entries without
9
+ * anyone using them, and counting that as attention would let a memory be
10
+ * rewritten every sweep and never expire. Reading and being surfaced are the
11
+ * signals that count, and the state database is the authority for both, because
12
+ * a concurrent session may hold a newer counter than the entry file does.
13
+ *
14
+ * @param entry - the entry file's view.
15
+ * @param row - the state database's view, when one exists.
16
+ * @returns Unix epoch milliseconds.
17
+ */
18
+ export function lastAttention(entry, row) {
19
+ return Math.max(entry.createdAt, entry.lastUsedAt, entry.lastSurfacedAt, row?.lastUsedAt ?? 0, row?.surfacedAt ?? 0);
20
+ }
21
+ /**
22
+ * Choose the entries to archive.
23
+ *
24
+ * A `user`-sourced entry is never chosen: somebody typed it, and a schedule is
25
+ * not entitled to overrule a person. Everything else is judged purely by age,
26
+ * so the outcome is explainable — "unused for N days" — rather than a score
27
+ * nobody can reconstruct.
28
+ *
29
+ * @param entries - every entry in one scope.
30
+ * @param rows - usage rows from the state database.
31
+ * @param options - the age limit and the clock.
32
+ * @returns the entries to archive, longest-unused first.
33
+ */
34
+ export function planRetention(entries, rows, options) {
35
+ const snapshotMaxAgeDays = options.snapshotMaxAgeDays ?? 0;
36
+ if (options.maxUnusedDays <= 0 && snapshotMaxAgeDays <= 0)
37
+ return [];
38
+ const usage = new Map(rows.map((row) => [retentionKey(row.scope, row.id), row]));
39
+ const limitMs = options.maxUnusedDays * 86_400_000;
40
+ const snapshotMs = snapshotMaxAgeDays * 86_400_000;
41
+ const decisions = [];
42
+ for (const entry of entries) {
43
+ // A pinned or permanent memory is a decision a person made; a schedule is not
44
+ // entitled to overrule it, exactly like a `user`-sourced one.
45
+ if (entry.source === 'user' || entry.pinned === true || entry.permanent === true)
46
+ continue;
47
+ const attention = lastAttention(entry, usage.get(retentionKey(entry.scope, entry.id)));
48
+ if (snapshotMaxAgeDays > 0 && entry.durability === 'snapshot') {
49
+ // Measured against when it was taken, not when it was last read.
50
+ const ageMs = options.now - (entry.asOf ?? entry.createdAt);
51
+ if (ageMs > snapshotMs) {
52
+ decisions.push({ scope: entry.scope, id: entry.id, ageDays: ageMs / 86_400_000 });
53
+ continue;
54
+ }
55
+ }
56
+ if (options.maxUnusedDays <= 0)
57
+ continue;
58
+ const ageMs = options.now - attention;
59
+ if (ageMs <= limitMs)
60
+ continue;
61
+ decisions.push({ scope: entry.scope, id: entry.id, ageDays: ageMs / 86_400_000 });
62
+ }
63
+ return decisions.sort((left, right) => right.ageDays - left.ageDays || left.id.localeCompare(right.id));
64
+ }
@@ -0,0 +1,245 @@
1
+ /**
2
+ * Timing for the background passes: how long to wait for a session to settle,
3
+ * and which hours the plugin is allowed to spend tokens in.
4
+ *
5
+ * Both exist for the same reason. Stage 1 (extraction) and stage 2
6
+ * (consolidation) are the only parts of this plugin that call a model, so they
7
+ * are the only parts that cost anything, and providers price by time of day:
8
+ * DeepSeek, for one, charges double on weekday mornings and afternoons (Beijing
9
+ * time) and half everywhere else. Deferring those two calls into the cheap
10
+ * window is a straight discount on everything this plugin spends.
11
+ *
12
+ * The window is expressed as the *peak* hours to avoid, not as the hours to run,
13
+ * because that is how providers publish it and how a person reasons about it:
14
+ * "don't spend between 9 and 12". Everything else is implicitly allowed, so
15
+ * weekends need no entry at all.
16
+ *
17
+ * @module dsh-cross-memory/schedule
18
+ */
19
+ /** Weekday numbers as `Date.getDay()` reports them, plus their spellings. */
20
+ const DAY_NAMES = {
21
+ sun: 0,
22
+ sunday: 0,
23
+ mon: 1,
24
+ monday: 1,
25
+ tue: 2,
26
+ tues: 2,
27
+ tuesday: 2,
28
+ wed: 3,
29
+ wednesday: 3,
30
+ thu: 4,
31
+ thur: 4,
32
+ thurs: 4,
33
+ thursday: 4,
34
+ fri: 5,
35
+ friday: 5,
36
+ sat: 6,
37
+ saturday: 6,
38
+ };
39
+ /** Parse `HH:MM` into minutes since midnight. */
40
+ function parseClock(text) {
41
+ const match = /^(\d{1,2}):(\d{2})$/u.exec(text.trim());
42
+ if (match === null)
43
+ return undefined;
44
+ const hours = Number(match[1]);
45
+ const minutes = Number(match[2]);
46
+ if (hours > 24 || minutes > 59)
47
+ return undefined;
48
+ if (hours === 24 && minutes !== 0)
49
+ return undefined;
50
+ return hours * 60 + minutes;
51
+ }
52
+ /** Resolve one day token (`mon`, `Mon-Fri`, `sat`) to weekday numbers. */
53
+ function parseDays(text) {
54
+ const trimmed = text.trim();
55
+ if (trimmed.length === 0 || trimmed === '*')
56
+ return new Set([0, 1, 2, 3, 4, 5, 6]);
57
+ const days = new Set();
58
+ for (const part of trimmed.split('+')) {
59
+ const range = part.split('-');
60
+ if (range.length === 2) {
61
+ const start = DAY_NAMES[range[0]?.trim().toLowerCase() ?? ''];
62
+ const end = DAY_NAMES[range[1]?.trim().toLowerCase() ?? ''];
63
+ if (start === undefined || end === undefined)
64
+ return undefined;
65
+ // A range wraps forward, so `Sat-Mon` is Sat, Sun, Mon.
66
+ for (let step = 0, day = start; step < 7; step += 1, day = (day + 1) % 7) {
67
+ days.add(day);
68
+ if (day === end)
69
+ break;
70
+ }
71
+ continue;
72
+ }
73
+ const day = DAY_NAMES[part.trim().toLowerCase()];
74
+ if (day === undefined)
75
+ return undefined;
76
+ days.add(day);
77
+ }
78
+ return days.size > 0 ? days : undefined;
79
+ }
80
+ /**
81
+ * Parse a `peakHours` spec.
82
+ *
83
+ * Grammar, all optional and local time:
84
+ *
85
+ * ```text
86
+ * <days> <HH:MM>-<HH:MM> Mon-Fri 09:00-12:00
87
+ * <HH:MM>-<HH:MM> every day
88
+ * <a>+<b> <HH:MM>-<HH:MM> Mon+Wed+Fri 14:00-18:00
89
+ * `*` for days * 09:00-12:00
90
+ * ```
91
+ *
92
+ * Entries are separated by `,` or `;`. A window whose end is not after its start
93
+ * crosses midnight (`Sat 22:00-02:00`). An empty spec means "never peak".
94
+ *
95
+ * @param spec - the configured spec.
96
+ * @returns the windows that parsed, plus any entries that did not.
97
+ */
98
+ export function parsePeakHours(spec) {
99
+ const windows = [];
100
+ const invalid = [];
101
+ for (const raw of spec.split(/[,;]/u)) {
102
+ const entry = raw.trim();
103
+ if (entry.length === 0)
104
+ continue;
105
+ // The day part is everything before the first token that contains a colon.
106
+ const match = /^(.*?)\s*(\d{1,2}:\d{2})\s*-\s*(\d{1,2}:\d{2})$/u.exec(entry);
107
+ if (match === null) {
108
+ invalid.push(entry);
109
+ continue;
110
+ }
111
+ const days = parseDays(match[1] ?? '');
112
+ const from = parseClock(match[2] ?? '');
113
+ const to = parseClock(match[3] ?? '');
114
+ if (days === undefined || from === undefined || to === undefined || from === to) {
115
+ invalid.push(entry);
116
+ continue;
117
+ }
118
+ windows.push({ days, from, to });
119
+ }
120
+ return { windows, invalid };
121
+ }
122
+ /** Minutes since local midnight. */
123
+ function minuteOf(now) {
124
+ return now.getHours() * 60 + now.getMinutes();
125
+ }
126
+ /**
127
+ * Whether a moment falls inside a window.
128
+ *
129
+ * A window that crosses midnight is matched on the day it *starts*: `Sat
130
+ * 22:00-02:00` covers Saturday night and Sunday's small hours, because that is
131
+ * what somebody writing it means.
132
+ *
133
+ * @param window - the parsed window.
134
+ * @param now - the moment to test.
135
+ * @returns true when the moment is inside.
136
+ */
137
+ export function withinWindow(window, now) {
138
+ const minutes = minuteOf(now);
139
+ const day = now.getDay();
140
+ if (window.to > window.from) {
141
+ return window.days.has(day) && minutes >= window.from && minutes < window.to;
142
+ }
143
+ // Crosses midnight: either late on a listed day, or early on the day after one.
144
+ if (window.days.has(day) && minutes >= window.from)
145
+ return true;
146
+ const yesterday = (day + 6) % 7;
147
+ return window.days.has(yesterday) && minutes < window.to;
148
+ }
149
+ /** Merge overlapping windows so the end of a moment is the end of its last window. */
150
+ function covering(windows, now) {
151
+ return windows.filter((window) => withinWindow(window, now));
152
+ }
153
+ /**
154
+ * Milliseconds until the current peak window ends, or `0` when not in one.
155
+ *
156
+ * The delay is floored one second past the boundary: firing exactly on it would
157
+ * re-enter the same check and defer again.
158
+ *
159
+ * @param spec - the configured `peakHours` spec.
160
+ * @param now - the moment to measure from.
161
+ * @returns milliseconds to wait, or 0 when spending is allowed right now.
162
+ */
163
+ export function peakDelayMs(spec, now = new Date()) {
164
+ if (spec.trim().length === 0)
165
+ return 0;
166
+ const { windows } = parsePeakHours(spec);
167
+ const current = covering(windows, now);
168
+ if (current.length === 0)
169
+ return 0;
170
+ const minutes = minuteOf(now);
171
+ let soonest = Number.POSITIVE_INFINITY;
172
+ for (const window of current) {
173
+ // Minutes from `now` to this window's end, crossing midnight when needed.
174
+ const remaining = window.to > minutes ? window.to - minutes : 1440 - minutes + window.to;
175
+ soonest = Math.min(soonest, remaining);
176
+ }
177
+ if (!Number.isFinite(soonest))
178
+ return 0;
179
+ return soonest * 60_000 + 1_000;
180
+ }
181
+ /**
182
+ * How long to wait after a session settles before mining it.
183
+ *
184
+ * The delay is the *larger* of the two configured waits, and that is the whole
185
+ * point: scheduling for the idle delay alone produced a pass that always failed
186
+ * the quiet-window gate. The timer fires once and is never re-armed, so a 5
187
+ * minute timer guarding a 6 hour window meant stage 1 never ran at all — the
188
+ * plugin's own store showed dozens of tracked sessions and not one watermark.
189
+ *
190
+ * @param settings - the tunables in force.
191
+ * @returns milliseconds to wait after the session settles.
192
+ */
193
+ export function extractionDelayMs(settings) {
194
+ return Math.max(settings.autoExtractIdleMs, settings.minIdleHours * 3_600_000);
195
+ }
196
+ /**
197
+ * How long to wait before the next pass, counting both gates.
198
+ *
199
+ * @param settings - the tunables in force.
200
+ * @param now - the moment to measure from.
201
+ * @returns milliseconds to wait.
202
+ */
203
+ export function backgroundDelayMs(settings, now = new Date()) {
204
+ return Math.max(extractionDelayMs(settings), peakDelayMs(settings.peakHours, now));
205
+ }
206
+ /** Render a delay as `45s`, `5m`, or `6h30m`, for one diagnostic line. */
207
+ export function formatDelay(ms) {
208
+ const seconds = Math.max(0, Math.round(ms / 1_000));
209
+ if (seconds < 60)
210
+ return `${seconds}s`;
211
+ const minutes = Math.floor(seconds / 60);
212
+ if (minutes < 60)
213
+ return `${minutes}m`;
214
+ const rest = minutes % 60;
215
+ return rest === 0 ? `${Math.floor(minutes / 60)}h` : `${Math.floor(minutes / 60)}h${rest}m`;
216
+ }
217
+ /**
218
+ * Waits between retries of a session whose extraction reply hit the output cap.
219
+ *
220
+ * A capped reply is not a completed extraction, so its window is left unmined
221
+ * and the next attempt reads it again — that is the whole point, and it is also
222
+ * the cost: the cause is usually deterministic (the transcript is bigger than
223
+ * `extractMaxOutputTokens` can describe, or the inherited reasoning level bills
224
+ * its thinking against the same ceiling), so a retry on the pass cadence would
225
+ * repeat a full-price call every `extractIntervalMinutes` and never succeed.
226
+ * Consecutive caps therefore back off geometrically to one attempt per six
227
+ * hours: a ceiling that is simply too small costs a handful of calls a day, and
228
+ * a transient cap is still retried within the hour.
229
+ */
230
+ const CAPPED_BACKOFF_LADDER = [30 * 60_000, 3_600_000, 2 * 3_600_000, 4 * 3_600_000, 6 * 3_600_000];
231
+ /**
232
+ * How long to wait before retrying a window whose reply hit the output cap.
233
+ *
234
+ * @param hits - consecutive capped replies for this session, counting this one.
235
+ * @param intervalMs - the configured pass interval. The wait is never shorter
236
+ * than it, so the ladder's first rung cannot undercut a slower cadence the
237
+ * user chose deliberately; `0` (periodic checks off) leaves the ladder alone.
238
+ * @returns milliseconds to wait before the next attempt.
239
+ */
240
+ export function cappedBackoffMs(hits, intervalMs) {
241
+ const last = CAPPED_BACKOFF_LADDER.length - 1;
242
+ const index = Math.min(Math.max(Math.trunc(hits), 1), last + 1) - 1;
243
+ const rung = CAPPED_BACKOFF_LADDER[index] ?? CAPPED_BACKOFF_LADDER[last] ?? 0;
244
+ return Math.max(intervalMs > 0 ? intervalMs : 0, rung);
245
+ }