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,144 @@
1
+ import type { Exporter, LoggerType, Message } from '@deepseek-ai/cordis';
2
+ /** Verbosity, least to most talkative. `off` records nothing. */
3
+ export declare const LOG_LEVELS: readonly ['off', 'error', 'warn', 'info', 'debug'];
4
+ /** How much this plugin records in its log file. */
5
+ export type LogLevel = (typeof LOG_LEVELS)[number];
6
+ /** How large the log may grow before it is rotated once. */
7
+ export declare const LOG_MAX_BYTES: number;
8
+ /** Narrow an unknown value to a log level, defaulting to `info`. */
9
+ export declare function toLogLevel(value: unknown, fallback?: LogLevel): LogLevel;
10
+ /**
11
+ * Whether one message is recorded at one verbosity.
12
+ * @param level - the configured verbosity.
13
+ * @param type - the message's severity.
14
+ * @returns true when the message belongs in the log.
15
+ */
16
+ export declare function allows(level: LogLevel, type: LoggerType): boolean;
17
+ /** Where the plugin writes its log inside one harness home. */
18
+ export declare function logPath(dshHome: string): string;
19
+ /** An append-only text sink. */
20
+ export interface LogSink {
21
+ /** Append one already-formatted line. */
22
+ write(line: string): void;
23
+ }
24
+ /**
25
+ * Create the file sink, with one rotated generation beside it.
26
+ *
27
+ * Rotation is deliberately crude — check the size before writing, move the file
28
+ * to `<path>.1` when it is too big, keeping exactly one generation — because the
29
+ * alternative (a log library, or an unbounded file) is worse for a plugin that
30
+ * writes at most a few lines per pass.
31
+ *
32
+ * A write failure is reported through `onWriteError` rather than thrown: the log
33
+ * must never fail a pass, but the caller still has to be able to tell a user that
34
+ * the file stopped growing. The callback fires once per failure, not per retry.
35
+ *
36
+ * @param path - absolute log path; an empty string disables the sink.
37
+ * @param maxBytes - size at which the file is rotated.
38
+ * @param onWriteError - called with the reason a write failed.
39
+ * @returns the sink, or `undefined` when the directory cannot be created.
40
+ */
41
+ export declare function createFileSink(path: string, maxBytes?: number, onWriteError?: (reason: string) => void): LogSink | undefined;
42
+ /**
43
+ * Format one host message as a single timestamped line.
44
+ *
45
+ * The argument rendering is the host's own (`Logger.format`), so `%s`/`%d`/`%o`
46
+ * and `Error` arguments read exactly as they would in any other DSH log; the
47
+ * prefix and the collapsed newlines are what make it greppable in a file.
48
+ *
49
+ * @param exporter - the sink the message is being written to, for its formatters.
50
+ * @param message - the structured record.
51
+ * @returns one line, without a trailing newline.
52
+ */
53
+ export declare function formatLogMessage(exporter: Exporter, message: Message): string;
54
+ /** The logger name every line from this plugin carries, and the sink filters on. */
55
+ export declare const LOG_NAME = "dsh-cross-memory";
56
+ /**
57
+ * Whether one host message belongs in this plugin's file.
58
+ *
59
+ * The name is the real filter, but the prefix is accepted as a fallback: a line
60
+ * that goes out through `ctx.logger` instead of the named logger carries the
61
+ * fiber's name (`memories`), not this one, and dropping the plugin's own message
62
+ * silently is exactly the failure mode this module exists to prevent. The host
63
+ * still applies its own threshold to such a line, so the fallback only rescues
64
+ * what was delivered — which is why every call site uses the named logger.
65
+ *
66
+ * @param message - the structured record.
67
+ * @param name - the logger name this file owns.
68
+ * @returns true when the message is ours.
69
+ */
70
+ export declare function ownsMessage(message: Message, name?: string): boolean;
71
+ /**
72
+ * Build the exporter that writes to a sink.
73
+ *
74
+ * `levels` is the whole reason this object exists. cordis filters each message
75
+ * per exporter against `exporter.levels?.[name] ?? exporter.levels?.default ??
76
+ * logger.level ?? 1`, and the composition's only default exporter declares no
77
+ * levels, so the threshold falls back to `1` and every `warn` and `debug` line is
78
+ * discarded before a sink sees it. The map therefore carries both directions:
79
+ *
80
+ * - `[name]: 3` raises THIS logger's threshold, so the plugin's own `warn` and
81
+ * `debug` reach the file.
82
+ * - `default: 0` lowers every OTHER logger's threshold to `error`, so a foreign
83
+ * plugin's `warn` cannot land in this plugin's file. Without it the fallback
84
+ * threshold of `1` lets `web-server` connection noise in — measured on a real
85
+ * profile, not assumed.
86
+ *
87
+ * `export` still checks the name, because messages that pass the threshold arrive
88
+ * from every exporter and the file should be this plugin's record alone.
89
+ *
90
+ * The verbosity thunk returns a plain string because that is what the settings
91
+ * schema declares; an unrecognized value normalizes to `info` here exactly as it
92
+ * does in the runtime, so the two can never disagree about what "warn" means.
93
+ *
94
+ * @param sink - where formatted lines go.
95
+ * @param level - the verbosity in force right now.
96
+ * @param name - the logger name this file owns.
97
+ * @returns the exporter to hand `ctx.logger.exporter`.
98
+ */
99
+ export declare function createLogExporter(sink: LogSink, level: () => string, name?: string): Exporter;
100
+ /**
101
+ * Resolve the plugin's named logger.
102
+ *
103
+ * A name is what keeps this plugin's file to this plugin's lines. Deployments and
104
+ * test doubles that expose only the service's methods (no call signature) fall
105
+ * back to the service itself, which still logs — just under the fiber's name.
106
+ *
107
+ * @param logger - `ctx.logger` as the plugin sees it.
108
+ * @returns the object whose methods the runtime logs through.
109
+ */
110
+ export declare function pluginLogger(logger: unknown): LoggerLike;
111
+ /** The subset of `ctx.logger` this plugin calls. */
112
+ export interface LoggerLike {
113
+ error(...args: unknown[]): void;
114
+ warn(...args: unknown[]): void;
115
+ info(...args: unknown[]): void;
116
+ debug(...args: unknown[]): void;
117
+ }
118
+ /**
119
+ * A thin facade over `ctx.logger`.
120
+ *
121
+ * It adds exactly one thing the raw logger cannot express: a *decision* line,
122
+ * which is `info` while `traceMaintenance` is on and `debug` otherwise. The
123
+ * message always goes to the host logger, so every other sink still sees it —
124
+ * only this plugin's file applies `logLevel`.
125
+ */
126
+ export declare class MemoryLog {
127
+ private readonly logger;
128
+ private readonly trace;
129
+ constructor(logger: LoggerLike, trace: () => boolean);
130
+ error(...args: unknown[]): void;
131
+ warn(...args: unknown[]): void;
132
+ info(...args: unknown[]): void;
133
+ debug(...args: unknown[]): void;
134
+ /**
135
+ * Record a maintenance decision.
136
+ *
137
+ * Quiet by default: retention, recall and selection emit several lines per
138
+ * pass, and a readable `logLevel: info` is worth more than a complete one.
139
+ * `traceMaintenance` raises them to `info`, which a stock `logLevel` keeps.
140
+ *
141
+ * @param args - the format string and its arguments.
142
+ */
143
+ decision(...args: unknown[]): void;
144
+ }
@@ -0,0 +1,82 @@
1
+ /** Where one loop is in its life. */
2
+ export type LoopState = 'open' | 'done' | 'dropped' | 'expired';
3
+ /** One thing said but not done. */
4
+ export interface LoopItem {
5
+ /** Stable id derived from the text. */
6
+ readonly id: string;
7
+ /** What was said they would do; short and in their words. */
8
+ readonly text: string;
9
+ /** When it was captured. */
10
+ readonly openedAt: number;
11
+ /** The moment it was promised for, when one was said. */
12
+ readonly dueAt?: number;
13
+ /** Current state. */
14
+ readonly state: LoopState;
15
+ /** Session it came from. */
16
+ readonly sourceSession?: string;
17
+ /** Last time it was raised as a notice. */
18
+ readonly remindedAt?: number;
19
+ /** How many times it has been raised. */
20
+ readonly remindCount?: number;
21
+ }
22
+ /** The on-disk ledger. */
23
+ export interface LoopStore {
24
+ readonly version: 1;
25
+ readonly loops: readonly LoopItem[];
26
+ }
27
+ /** File name inside the memory store. */
28
+ export declare const LOOPS_FILE = "loops.json";
29
+ /** How long an untouched loop may stay open before it expires. */
30
+ export declare const LOOP_TTL_MS: number;
31
+ /** How many open loops are kept; the oldest are dropped past this. */
32
+ export declare const LOOP_CAP = 50;
33
+ /** Reminders per loop, and the spacing between them. */
34
+ export declare const LOOP_MAX_REMINDERS = 3;
35
+ export declare const LOOP_REMIND_INTERVAL_MS: number;
36
+ /** Read the ledger, tolerating a missing or corrupt file. */
37
+ export declare function readLoops(memoriesDir: string): Promise<LoopStore>;
38
+ /** Write the ledger atomically. */
39
+ export declare function writeLoops(memoriesDir: string, store: LoopStore): Promise<string>;
40
+ /**
41
+ * Fold newly extracted promises into the ledger.
42
+ *
43
+ * Duplicates are the normal case, not the exception: a promise repeated across
44
+ * three sessions must be ONE loop, or the user gets reminded three times about
45
+ * the same thing. Matching is on normalized text and containment, which is crude
46
+ * but predictable — the failure mode of a cleverer match is silently merging two
47
+ * different promises.
48
+ *
49
+ * @param store - the current ledger.
50
+ * @param candidates - what an extraction just found.
51
+ * @param now - clock.
52
+ * @param sessionId - where they came from.
53
+ * @returns the new ledger.
54
+ */
55
+ export declare function mergeLoops(store: LoopStore, candidates: readonly {
56
+ text: string;
57
+ dueAt?: number;
58
+ }[], now: number, sessionId?: string): LoopStore;
59
+ /** Expire loops nobody closed and nobody mentioned in weeks. */
60
+ export declare function pruneLoops(store: LoopStore, now: number): LoopStore;
61
+ /**
62
+ * Loops that may be raised right now.
63
+ *
64
+ * Only loops with a stated deadline qualify. A loop without one is a note, not a
65
+ * promise, and nagging somebody about a note they never dated is how a helpful
66
+ * assistant turns into a supervisor.
67
+ *
68
+ * @param store - the ledger.
69
+ * @param now - clock.
70
+ * @returns loops to raise, oldest deadline first.
71
+ */
72
+ export declare function dueLoops(store: LoopStore, now: number): LoopItem[];
73
+ /** Record that one loop was raised, or close it. */
74
+ export declare function withLoop(store: LoopStore, id: string, update: Partial<LoopItem>): LoopStore;
75
+ /** Close one loop by the id the user typed, accepting a unique prefix. */
76
+ export declare function closeLoop(store: LoopStore, idOrPrefix: string): {
77
+ store: LoopStore;
78
+ closed?: LoopItem;
79
+ reason?: string;
80
+ };
81
+ /** The text a command shows: open loops, soonest deadline first. */
82
+ export declare function describeLoops(store: LoopStore, now: number): string;
@@ -0,0 +1,117 @@
1
+ /** What a notice is about. */
2
+ export type NoticeKind = 'digest' | 'backlog' | 'conflict' | 'loop' | 'reflection';
3
+ /** Lifecycle of one notice. */
4
+ export type NoticeState = 'open' | 'delivered' | 'acked' | 'expired';
5
+ /** How the user answered one notice. */
6
+ export type NoticeOutcome = 'acted' | 'dismissed' | 'snoozed';
7
+ /** One durable notice. */
8
+ export interface Notice {
9
+ /** Stable id, derived from the dedupe key and creation time. */
10
+ readonly id: string;
11
+ /** What it is about. */
12
+ readonly kind: NoticeKind;
13
+ /** Unix ms. */
14
+ readonly createdAt: number;
15
+ /** Earliest moment it may be shown. */
16
+ readonly dueAt: number;
17
+ /** One short line, what the bubble says. */
18
+ readonly title: string;
19
+ /** The detail a human can expand; never empty. */
20
+ readonly body: string;
21
+ /** Ids of the memories / loops this notice is based on. Never empty. */
22
+ readonly evidence: readonly string[];
23
+ /** Two notices with the same key are the same subject. */
24
+ readonly dedupeKey: string;
25
+ /** Where it is in its lifecycle. */
26
+ readonly state: NoticeState;
27
+ /** When a frontend took it. */
28
+ readonly deliveredAt?: number;
29
+ /** What the user did about it. */
30
+ readonly outcome?: NoticeOutcome;
31
+ /** When the user answered. */
32
+ readonly ackedAt?: number;
33
+ }
34
+ /** The on-disk queue. */
35
+ export interface NoticeQueue {
36
+ readonly version: 1;
37
+ /** Unix ms of the last daily digest, so the next one knows what it covers. */
38
+ readonly lastDigestAt?: number;
39
+ /** Most recent first is not required; the queue is small and sorted on read. */
40
+ readonly notices: readonly Notice[];
41
+ }
42
+ /** File name inside the memory store. */
43
+ export declare const NOTICES_FILE = "notices.json";
44
+ /** How long an unacknowledged notice may sit before it is expired. */
45
+ export declare const NOTICE_TTL_MS: number;
46
+ /** Policy knobs, all injected so the module stays pure. */
47
+ export interface NoticePolicy {
48
+ /** Unix ms. */
49
+ readonly now: number;
50
+ /** Hours during which nothing may be delivered; `''` disables. */
51
+ readonly quietHours: string;
52
+ /** Safety valve, not a target: the user asked for "when it matters", not a quota. */
53
+ readonly dailyCap: number;
54
+ /** Same-subject spacing; a dismissal stretches it. */
55
+ readonly minSpacingHours: number;
56
+ }
57
+ /** Read the queue, tolerating a missing or corrupt file. */
58
+ export declare function readNotices(memoriesDir: string): Promise<NoticeQueue>;
59
+ /** Write the queue atomically. */
60
+ export declare function writeNotices(memoriesDir: string, queue: NoticeQueue): Promise<string>;
61
+ /**
62
+ * Decide whether one candidate notice may enter the queue.
63
+ *
64
+ * Runs no model and looks at no clock beyond the injected one: every rule here is
65
+ * explainable, which is the only way "why did it stay quiet?" can be answered
66
+ * later.
67
+ *
68
+ * @param queue - the current queue.
69
+ * @param candidate - what the trigger wants to say.
70
+ * @param policy - caps, spacing and quiet hours.
71
+ * @returns whether it was enqueued, and why not when it was not.
72
+ */
73
+ export declare function admitNotice(queue: NoticeQueue, candidate: Omit<Notice, 'id' | 'state'>, policy: NoticePolicy): {
74
+ ok: true;
75
+ notice: Notice;
76
+ dueAt: number;
77
+ } | {
78
+ ok: false;
79
+ reason: string;
80
+ };
81
+ /**
82
+ * Move `dueAt` to the end of the quiet window, when it falls inside one.
83
+ *
84
+ * Windows are written like `peakHours` (`22:00-08:00`, `Mon-Fri 09:00-12:00`) and
85
+ * parsed by the same routine, so there is one syntax for "time of day" in this
86
+ * plugin rather than two.
87
+ *
88
+ * @param dueAt - the moment the trigger wanted to fire.
89
+ * @param quietHours - the window spec; empty disables.
90
+ * @returns the moment it may actually fire.
91
+ */
92
+ export declare function quietHoursEnd(dueAt: number, quietHours: string): number;
93
+ /** Notices that may be delivered now, oldest first. */
94
+ export declare function dueNotices(queue: NoticeQueue, now: number): Notice[];
95
+ /** Replace one notice, returning a new queue. */
96
+ export declare function withNotice(queue: NoticeQueue, updated: Notice): NoticeQueue;
97
+ /**
98
+ * Record that a person answered one notice.
99
+ *
100
+ * This is the only feedback the plugin gets, and it is the difference between a
101
+ * proactive assistant that learns and one that just talks: a dismissal stretches
102
+ * the same subject's silence (see {@link admitNotice}), and the probe reports the
103
+ * acted/dismissed ratio so a week of reminders can be judged instead of guessed.
104
+ *
105
+ * @param queue - the current queue.
106
+ * @param idOrPrefix - full id or an unambiguous prefix, as typed by a person.
107
+ * @param outcome - what they did about it.
108
+ * @param now - clock.
109
+ * @returns the new queue and the answered notice, or why nothing matched.
110
+ */
111
+ export declare function ackNotice(queue: NoticeQueue, idOrPrefix: string, outcome: NoticeOutcome, now: number): {
112
+ queue: NoticeQueue;
113
+ notice?: Notice;
114
+ reason?: string;
115
+ };
116
+ /** Expire notices nobody ever took, so the queue cannot grow forever. */
117
+ export declare function pruneNotices(queue: NoticeQueue, now: number): NoticeQueue;
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Post a macOS notification.
3
+ *
4
+ * Deliberately the quiet kind: no sound, no focus steal. The point is that a
5
+ * notice is not lost, not that it interrupts. Never throws — a notification
6
+ * channel that can break a background pass is worse than a missed notice.
7
+ *
8
+ * @param title - notification title.
9
+ * @param message - notification body.
10
+ * @returns whether `osascript` accepted it.
11
+ */
12
+ export declare function systemNotification(title: string, message: string): boolean;
@@ -0,0 +1,43 @@
1
+ /** Directory holding the profile, inside the memory store. */
2
+ export declare const PERSONA_DIR = "persona";
3
+ /** Legacy single-file profile, migrated on first read. */
4
+ export declare const LEGACY_PERSONA_FILE = "persona.md";
5
+ /** How large a profile the injector will render, in characters of source text. */
6
+ export declare const PERSONA_MAX_SOURCE_CHARS = 6000;
7
+ /** Path of the profile. */
8
+ export declare function personaPath(memoriesDir: string): string;
9
+ /**
10
+ * Read the profile.
11
+ *
12
+ * Falls back to the legacy single file, so an upgrade does not lose the profile
13
+ * that was already there.
14
+ *
15
+ * @param memoriesDir - the memory store root.
16
+ * @returns the markdown body, or `undefined` when it does not exist yet.
17
+ */
18
+ export declare function readPersona(memoriesDir: string): Promise<string | undefined>;
19
+ /**
20
+ * Replace the profile atomically.
21
+ *
22
+ * A half-written profile is worse than a stale one — it would be injected into
23
+ * every conversation — so the write goes through a temp file and a rename.
24
+ *
25
+ * @param memoriesDir - the memory store root.
26
+ * @param body - the new markdown profile.
27
+ * @returns the absolute path written.
28
+ */
29
+ export declare function writePersona(memoriesDir: string, body: string): Promise<string>;
30
+ /**
31
+ * Render the profile as the fenced text the model receives.
32
+ *
33
+ * The frame says what the content is and what it is NOT: a profile is a set of
34
+ * claims about a person, and a model that reads them as instructions will invent
35
+ * work ("the user prefers X, so I will do X") instead of answering the question.
36
+ * It also carries the date, because a profile is a snapshot of a person.
37
+ *
38
+ * @param body - the stored markdown.
39
+ * @param maxBytes - hard UTF-8 budget; longer profiles are cut at a line boundary.
40
+ * @param now - clock, for the header date.
41
+ * @returns the framed block, or `undefined` when there is nothing to show.
42
+ */
43
+ export declare function renderPersonaBlock(body: string | undefined, maxBytes: number, now?: number): string | undefined;
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Turning one user turn into the strings a memory is actually compared against.
3
+ *
4
+ * A turn is a wall of text: instructions, pasted logs, code, a question at the
5
+ * end. Scoring an entire 2 000-character message as one query buries a precise
6
+ * hit inside all of that, and — worse — makes the result depend on the message's
7
+ * length rather than on what it is about. Splitting the turn into sentences and
8
+ * scoring each one independently is what lets "这段 PowerShell 该怎么写" reach a
9
+ * memory about `git commit -F` while the surrounding paragraphs match nothing.
10
+ *
11
+ * The splitter is CJK-aware on purpose: Chinese sentences end with `。!?` and
12
+ * often use a full-width comma as a clause boundary, so a whitespace-only split
13
+ * would hand the scorer one enormous "sentence" per paragraph. Character-level
14
+ * expansion (CJK bigrams) belongs to the scorer, not here — this module only
15
+ * decides *what text* is compared, and `search.ts` decides *how*.
16
+ *
17
+ * @module dsh-cross-memory/query
18
+ */
19
+ /** Longest single query string handed to the scorer, in characters. */
20
+ export declare const MAX_MESSAGE_CHARS = 240;
21
+ /** Most sentences and clauses one turn contributes. */
22
+ export declare const MAX_MESSAGES = 12;
23
+ /**
24
+ * The strings one user turn is scored as.
25
+ *
26
+ * The whole turn comes first, so a memory whose title spans a clause boundary
27
+ * is still reachable verbatim; then sentences and clauses, most specific
28
+ * (longest) first, because a long sentence shares more with an entry than a
29
+ * stray "好的" does. The scorer keeps the best hit, so this ordering only
30
+ * matters for the cap. The result is deduplicated, bounded, and deterministic.
31
+ *
32
+ * @param text - the raw user turn, or any search string.
33
+ * @returns candidate queries; empty when the input carries no usable text.
34
+ */
35
+ export declare function queryMessages(text: string): string[];
36
+ /**
37
+ * Whether a turn carries enough text to be worth a recall decision.
38
+ *
39
+ * A bare "好" or "ok" cannot express what a memory would have to be about, and
40
+ * letting it through only produces a full scan of the store on every step.
41
+ *
42
+ * @param text - the raw user turn.
43
+ * @returns true when the turn has at least one letter, digit, or ideograph.
44
+ */
45
+ export declare function isSubstantiveTurn(text: string): boolean;
@@ -0,0 +1,84 @@
1
+ import type { BackfillMessage } from './backfill.js';
2
+ /** One original turn worth showing next to a memory. */
3
+ export interface RawExcerpt {
4
+ /** Session the passage came from. */
5
+ readonly sessionId: string;
6
+ /** Surface seq of the message, for the evidence trail. */
7
+ readonly seq: number;
8
+ /** Speaker. */
9
+ readonly role: 'user' | 'assistant';
10
+ /** Credential-scrubbed text, truncated. */
11
+ readonly text: string;
12
+ }
13
+ /** Limits for one raw-recall selection. */
14
+ export interface RawRecallLimits {
15
+ /** Most excerpts to return. */
16
+ readonly maxExcerpts?: number;
17
+ /** Longest one excerpt may be, in characters. */
18
+ readonly maxChars?: number;
19
+ /** UTF-8 byte budget across all returned excerpts. */
20
+ readonly maxBytes?: number;
21
+ }
22
+ /**
23
+ * Score prose messages against the query and pick the best few.
24
+ *
25
+ * The gate is the same shape as memory recall's: a single shared bigram is not
26
+ * evidence (Chinese turns share 的/是 constantly), so a passage needs at least
27
+ * two shared tokens, or one long Latin identifier such as a file name. Each
28
+ * message contributes its best matching window, ranked by shared tokens, then by
29
+ * recency, then by brevity.
30
+ *
31
+ * @param messages - prose messages of one session.
32
+ * @param query - the current user turn.
33
+ * @param limits - count/character/byte caps.
34
+ * @returns excerpts in rank order, already scrubbed and truncated.
35
+ */
36
+ export declare function selectExcerpts(messages: readonly BackfillMessage[], query: string, limits?: RawRecallLimits): RawExcerpt[];
37
+ /**
38
+ * Show the window of one message that contains a memory's verbatim quote.
39
+ *
40
+ * Every automatic memory already stores the exact source text it came from
41
+ * (`quote`, checked as a substring when the entry was written). That makes the
42
+ * evidence lookup a string search, not a retrieval problem: find the message
43
+ * holding the quote, and cut a window around it. Locating a stored quote finds
44
+ * the passage a memory already points at, which lexical window selection can
45
+ * miss when the words in the query and the passage diverge.
46
+ *
47
+ * @param messages - the source session's prose.
48
+ * @param quote - the entry's stored quote.
49
+ * @param maxChars - window size.
50
+ * @returns the scrubbed window, or `undefined` when the quote is no longer there.
51
+ */
52
+ export declare function windowAroundQuote(messages: readonly BackfillMessage[], quote: string, maxChars?: number): RawExcerpt | undefined;
53
+ /**
54
+ * Read one session's prose transcript from the persisted logs.
55
+ *
56
+ * Failures (missing log, unreadable zstd, unknown session) return `undefined`:
57
+ * raw recall is an optional supplement and must never break a recall.
58
+ *
59
+ * @param sessionsDir - `<dshHome>/sessions`.
60
+ * @param sessionId - the session to read.
61
+ * @param now - clock, for the cache.
62
+ * @returns the prose messages, or `undefined`.
63
+ */
64
+ export declare function readTranscript(sessionsDir: string, sessionId: string, now?: number): Promise<readonly BackfillMessage[] | undefined>;
65
+ /**
66
+ * Collect raw excerpts for a recall: the source sessions of the memory hits.
67
+ *
68
+ * Quote grounding is tried first for every source that carries one, because it
69
+ * reproduces the exact sentence the memory was written from. A source whose
70
+ * quote is gone falls back to the lexical window selector, so an old or edited
71
+ * entry still contributes something.
72
+ *
73
+ * @param sessionsDir - `<dshHome>/sessions`.
74
+ * @param sources - memory sources in recall order, each with its optional quote.
75
+ * @param query - the current user turn.
76
+ * @param limits - count/character/byte caps (byte cap applies across sessions).
77
+ * @returns excerpts with their session id filled in.
78
+ */
79
+ export declare function collectExcerpts(sessionsDir: string, sources: readonly {
80
+ readonly sessionId: string;
81
+ readonly quote?: string;
82
+ }[], query: string, limits?: RawRecallLimits & {
83
+ readonly maxSessions?: number;
84
+ }): Promise<RawExcerpt[]>;
@@ -0,0 +1,122 @@
1
+ import type { LlmRuntime } from '@deepseek-ai/dsh-llm';
2
+ import type { Session } from '@deepseek-ai/dsh-session';
3
+ import type { MemoryEntry } from './types.js';
4
+ /** Directory inside the memory store. */
5
+ export declare const REFLECTION_DIR = "reflections";
6
+ /** How often the pass may run. */
7
+ export declare const REFLECTION_INTERVAL_MS: number;
8
+ /** Recent entries required before a reflection is worth attempting. */
9
+ export declare const REFLECTION_MIN_ENTRIES = 20;
10
+ /** How many entries one pass reads. */
11
+ export declare const REFLECTION_MAX_ENTRIES = 80;
12
+ /** One synthesized observation, with the memories behind it. */
13
+ export interface ReflectionInsight {
14
+ /** One or two sentences, in the user's language. */
15
+ readonly text: string;
16
+ /** Ids the insight is derived from; never empty. */
17
+ readonly evidence: readonly string[];
18
+ }
19
+ /** The instruction. Its job is to refuse restatement. */
20
+ export declare const REFLECTION_SYSTEM: string;
21
+ /** Output contract. */
22
+ export declare const REFLECTION_JSON_SCHEMA: {
23
+ readonly type: 'object';
24
+ readonly additionalProperties: false;
25
+ readonly required: readonly ['insights'];
26
+ readonly properties: {
27
+ readonly insights: {
28
+ readonly type: 'array';
29
+ readonly items: {
30
+ readonly type: 'object';
31
+ readonly additionalProperties: false;
32
+ readonly required: readonly ['text', 'evidence'];
33
+ readonly properties: {
34
+ readonly text: {
35
+ readonly type: 'string';
36
+ };
37
+ readonly evidence: {
38
+ readonly type: 'array';
39
+ readonly items: {
40
+ readonly type: 'string';
41
+ };
42
+ };
43
+ };
44
+ };
45
+ };
46
+ };
47
+ };
48
+ /**
49
+ * Whether a pass is due.
50
+ *
51
+ * @param lastAt - when the last reflection was written (0 when never).
52
+ * @param now - clock.
53
+ * @param entries - how many recent memories exist.
54
+ * @returns whether to run.
55
+ */
56
+ export declare function reflectionDue(lastAt: number, now: number, entries: number): boolean;
57
+ /** Render the input document, listing only what the model may cite. */
58
+ export declare function renderReflectionInput(entries: readonly MemoryEntry[], persona?: string, previous?: readonly string[]): string;
59
+ /**
60
+ * Parse a reflection reply, dropping any insight whose evidence the store cannot show.
61
+ *
62
+ * @param text - the raw reply.
63
+ * @param knownIds - ids present in the material the model was shown.
64
+ * @returns the validated insights, possibly none.
65
+ */
66
+ export declare function parseReflection(text: string, knownIds: ReadonlySet<string>): ReflectionInsight[];
67
+ /**
68
+ * Count what a reply contained, before validation dropped it.
69
+ *
70
+ * @param text - the raw reply.
71
+ * @param knownIds - ids the model was shown.
72
+ * @returns raw and evidence-bearing counts, or `undefined` when the reply is not JSON.
73
+ */
74
+ export declare function replyStats(text: string, knownIds: ReadonlySet<string>): {
75
+ raw: number;
76
+ cited: number;
77
+ } | undefined;
78
+ /** Everything one reflection call needs. */
79
+ export interface ReflectionRequest {
80
+ readonly llm: LlmRuntime | undefined;
81
+ readonly session: Session | undefined;
82
+ readonly entries: readonly MemoryEntry[];
83
+ readonly persona?: string;
84
+ readonly previous?: readonly string[];
85
+ readonly provider?: string;
86
+ readonly model?: string;
87
+ readonly timeoutMs: number;
88
+ readonly signal: AbortSignal;
89
+ }
90
+ /** What one pass produced. */
91
+ export interface ReflectionOutcome {
92
+ readonly insights: readonly ReflectionInsight[];
93
+ readonly reason: string;
94
+ readonly skipped?: 'no-llm' | 'no-route' | 'empty' | 'failed';
95
+ }
96
+ /**
97
+ * Run one reflection call.
98
+ *
99
+ * @param request - material, route, budget.
100
+ * @returns the validated insights, or why there are none.
101
+ */
102
+ export declare function runReflection(request: ReflectionRequest): Promise<ReflectionOutcome>;
103
+ /** Render one reflection as the markdown written to disk. */
104
+ export declare function renderReflectionFile(insights: readonly ReflectionInsight[], now: number): string;
105
+ /**
106
+ * Write one reflection file, one per day at most.
107
+ *
108
+ * @param memoriesDir - the store root.
109
+ * @param insights - validated observations.
110
+ * @param now - clock.
111
+ * @returns the absolute path written.
112
+ */
113
+ export declare function writeReflection(memoriesDir: string, insights: readonly ReflectionInsight[], now: number): Promise<string>;
114
+ /** List the reflection files, newest first. */
115
+ export declare function listReflections(memoriesDir: string): Promise<{
116
+ name: string;
117
+ body: string;
118
+ }[]>;
119
+ /** The one-line observations already written, for the "do not repeat" list. */
120
+ export declare function previousInsights(files: readonly {
121
+ body: string;
122
+ }[]): string[];