@dsh-cc/memory-consolidation 0.5.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.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,6 @@
1
+ # Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each
2
+ # side as of the last confirmed-consistent state. Both languages carry equal authority;
3
+ # after editing either side, bring the other along and re-record with:
4
+ # pnpm run verify-translation-pairing --write packages/memory/memory-consolidation/README.md
5
+ README.md: 896afedbd85a4ab522b4466675d5f67579ca0908
6
+ README.zh.md: 6dba1863f1923f21749191200f1eb865ad2720d1
package/README.md ADDED
@@ -0,0 +1,116 @@
1
+ # dsh-memory-consolidation
2
+
3
+ English | [中文](README.zh.md)
4
+
5
+ Background memory consolidation for the DeepSeek Harness: turn-end extraction
6
+ and the three-gate dream rewrite of the memory directory that `dsh-memory`
7
+ reads.
8
+
9
+ ## What this package provides
10
+
11
+ - **extractMemories** — an `agent/turn-stopping` listener starts a background
12
+ forked subagent (via `ctx.jobs` + `ctx.subagents`, read/search tools only)
13
+ that extracts durable facts from the turn and reports them as structured
14
+ output; the plugin validates the batch and writes the matching topic files
15
+ host-side.
16
+ - **Dream consolidation** — three configurable gates that must all pass before
17
+ a read-only forked subagent reviews past sessions and reports the rewritten
18
+ `MEMORY.md` + topic file set the same way:
19
+ 1. **Time** — at least `minHours` (default 24) since the last consolidation.
20
+ 2. **Session count** — at least `minSessions` (default 5) new transcripts.
21
+ 3. **Lock** — a `.consolidation-lock` file whose stored timestamp enforces
22
+ mutual exclusion; a stale holder (older than `lockStaleMs`, default 1 hour)
23
+ is reclaimed, so a crash mid-consolidation recovers automatically. A
24
+ failed or killed consolidation rolls the lock back so the time gate
25
+ re-opens.
26
+ - **Memory writes change model-visible context** — upstream, `dsh-memory`
27
+ re-assembles the `memory` system-prompt section via `system-prompt/change`
28
+ after the memory directory changes. This package introduces no new session
29
+ events for the memory files themselves.
30
+
31
+ ## Sandbox interaction: why the plugin writes, not the fork
32
+
33
+ Each memory directory lives in the harness home, OUTSIDE any session
34
+ workspace. A forked subagent inherits the parent session's sandbox policy, so
35
+ under `workspace-write` (or `read-only`) every model-side `write`/`edit`
36
+ aimed at a memory directory is fenced (`FS_SANDBOX_DENIED`), and a
37
+ background job cannot use the escalation retry — escalation prompts, and the
38
+ job's approval policy is `never`. Model-side memory writes are therefore
39
+ guaranteed to fail in any sandboxed session.
40
+
41
+ So the forks hold no write tools at all. They report their file set through
42
+ `outputSchema` (the driver-injected `structured_output` tool), and the plugin
43
+ — trusted host code — performs the writes itself. Writes land in the TURNING
44
+ agent's own workspace directory — `<memoryHome>/projects/<slug>/`, resolved
45
+ from the agent's canonical git root with `resolveWorkspaceMemoryDir` — never the
46
+ shared home root (that root is the explicitly-global layer owned by
47
+ `dsh-memory`'s `memory_save` with `scope: "global"`):
48
+
49
+ 1. `validateMemoryWrites` checks the untrusted payload: flat `.md` filenames
50
+ only (no separators, `..`, absolute paths, or dotfiles), no duplicates,
51
+ and hard caps (32 files / 64 KiB per file / 256 KiB per batch). Any
52
+ violation rejects the WHOLE batch.
53
+ 2. `writeMemoryFiles` writes the batch via the `ctx.fs` seam, stamping a
54
+ per-call policy of `{ mode: 'workspace-write', workspaceRoot: <memory dir> }`
55
+ — confinement is kept, but the writable root IS the memory directory. The
56
+ sandbox still fences each write behind the validation above; nothing
57
+ outside the memory directory becomes writable.
58
+
59
+ The job status reflects the real outcome: a non-completed `stopReason`, a
60
+ missing/invalid payload, or a write-back failure maps to `failed` with detail
61
+ instead of a silent fake-`completed`.
62
+
63
+ ## Usage
64
+
65
+ Load the plugin with `@dsh-cc/memory-consolidation`. Configuration:
66
+
67
+ | Key | Default | Meaning |
68
+ |---|---|---|
69
+ | `memoryHome` | harness home `memory/` | memory home root; extraction/dream write into the turning agent's repository `projects/<slug>/` under it |
70
+ | `extractEnabled` | `true` | run turn-end extraction |
71
+ | `dreamEnabled` | `true` | run the three-gate dream |
72
+ | `minHours` | `24` | minimum hours between consolidations |
73
+ | `minSessions` | `5` | minimum new transcripts to consolidate |
74
+ | `lockStaleMs` | `3_600_000` | lock holder stale window |
75
+ | `subagentProviderName` | `fork` | one-shot provider for the forks |
76
+
77
+ ```ts
78
+ import consolidation from '@dsh-cc/memory-consolidation'
79
+ await ctx.plugin(consolidation, { minHours: 24, minSessions: 5 })
80
+ ```
81
+
82
+ ## Model Experience
83
+
84
+ The turn-stopping listener is nearly free when the gates are closed (one lock
85
+ read). When the time and session gates open, one forked subagent runs per
86
+ consolidation, restricted to read/search tools plus the `structured_output`
87
+ report tool; its output is not appended to the main transcript. Per turn,
88
+ extraction may start a short background fork.
89
+
90
+ ## API
91
+
92
+ - `tryAcquireLock(fs, dir, pid, now, policy?)` / `rollbackLock(fs, dir, priorAt, policy?)` /
93
+ `readLastConsolidatedAt(fs, dir)` — the consolidation lock.
94
+ - `gatesPass(input)` / `timeGatePasses(...)` / `sessionGatePasses(...)` — the
95
+ gate predicates.
96
+ - `MEMORY_TOOL_FILTER` / `MEMORY_AGENT_TOOLS` — the memory-scoped tool set
97
+ (read/search + `structured_output`).
98
+ - `MEMORY_WRITES_SCHEMA` — the `outputSchema` contract every fork reports.
99
+ - `validateMemoryWrites(input)` / `writeMemoryFiles(fs, dir, writes)` /
100
+ `memoryWritePolicy(dir)` — the host-side write-back (owned by
101
+ `@dsh-cc/memory`, the memory directory owner, and re-exported here).
102
+ - `buildExtractionPrompt` / `buildConsolidationPrompt` — the fork prompts.
103
+
104
+ ## Known Limitations and Deferred Work
105
+
106
+ - The `ctx.fs` seam exposes no mtime, so the lock stores the holder PID and
107
+ last-consolidated epoch in the lock file's body rather than in the file
108
+ mtime; crash recovery rests on the stale window, not process-liveness.
109
+ - The session-count gate currently counts live sessions through `ctx.sessions`
110
+ and treats them as new; a clocked transcript query is deferred.
111
+ - There is no delete channel: the dream drops outdated memories from
112
+ `MEMORY.md`, but an orphaned topic file stays on disk until overwritten.
113
+ Topic-file deletion is deferred (the fork allow-list never had a remove
114
+ tool either).
115
+ - Concurrent extractions from parallel sessions write last-writer-wins; the
116
+ dream lock serializes only consolidations.
package/README.zh.md ADDED
@@ -0,0 +1,96 @@
1
+ # dsh-memory-consolidation
2
+
3
+ 中文 | [English](README.md)
4
+
5
+ 面向 DeepSeek Harness 的后台记忆整合:轮末抽取与对 `dsh-memory` 所读取的记忆
6
+ 目录进行三重门 dream 重写。
7
+
8
+ ## 本包提供的能力
9
+
10
+ - **extractMemories** —— `agent/turn-stopping` 监听器启动一个后台 fork 的
11
+ subagent(通过 `ctx.jobs` + `ctx.subagents`,仅持有读/搜索工具),从当前轮
12
+ 抽取持久事实并以结构化输出上报;插件校验该批次后在 host 侧写入匹配的主题
13
+ 文件。
14
+ - **Dream 整合** —— 三道可配置的门,全部通过后才会用只读的 fork subagent 回顾
15
+ 过往会话,并以同样方式上报重写后的 `MEMORY.md` 与主题文件集:
16
+ 1. **时间门** —— 自上次整合起至少 `minHours`(默认 24)小时。
17
+ 2. **会话门** —— 至少 `minSessions`(默认 5)条新 transcript。
18
+ 3. **文件锁** —— `.consolidation-lock` 文件以存储的时间戳保证互斥;过期的持有者
19
+ (超过 `lockStaleMs`,默认 1 小时)可被回收,因此整合中崩溃可自动恢复。失败
20
+ 或被 kill 的整合会回滚锁,使时间门重新打开。
21
+ - **记忆写入改变模型可见上下文** —— 在上游,`dsh-memory` 会在记忆目录变更后通过
22
+ `system-prompt/change` 重组装 `memory` 系统提示词 section。本包不为记忆文件本身
23
+ 引入新的会话事件。
24
+
25
+ ## 与 sandbox 的关系:为什么由插件而非 fork 落盘
26
+
27
+ 记忆目录位于 harness home,在任何会话 workspace 之外。fork subagent 继承父会话
28
+ 的 sandbox 策略,因此在 `workspace-write`(或 `read-only`)下,所有指向记忆目录
29
+ 的模型侧 `write`/`edit` 都会被围栏拦截(`FS_SANDBOX_DENIED`);后台 job 又无法
30
+ 走 escalation 重试——escalation 需要弹审批,而 job 的审批策略是 `never`。所以在
31
+ 任何 sandboxed 会话里,模型侧的记忆写入注定失败。
32
+
33
+ 因此 fork 不再持有任何写工具:它们通过 `outputSchema`(driver 注入的
34
+ `structured_output` 工具)上报文件集,由插件——可信的 host 代码——亲自落盘。
35
+ 写入目标是**触发 agent 自己所在工作区的目录**——`<memoryHome>/projects/<slug>/`,
36
+ 由 `resolveWorkspaceMemoryDir` 按 agent 的规范 git 根解析——而不是共享的 home 根
37
+ (home 根是显式全局层,由 `dsh-memory` 的 `memory_save` 以 `scope: "global"` 写入):
38
+
39
+ 1. `validateMemoryWrites` 校验这份不可信负载:仅允许扁平 `.md` 文件名(不允许
40
+ 分隔符、`..`、绝对路径、点文件),不允许重名,并施加硬上限(32 个文件 /
41
+ 单文件 64 KiB / 单批 256 KiB)。任何违规整批拒绝。
42
+ 2. `writeMemoryFiles` 经 `ctx.fs` 缝写入,并为每次调用盖上
43
+ `{ mode: 'workspace-write', workspaceRoot: <记忆目录> }` 的 per-call 策略——
44
+ 围栏仍然生效,只是可写根恰好就是记忆目录。sandbox 在校验之外再兜一层;
45
+ 记忆目录之外的任何路径都不可写。
46
+
47
+ job 状态反映真实结局:非 completed 的 `stopReason`、缺失/非法的负载、落盘失败
48
+ 都会映射为 `failed` 并带 detail,而不是静默地假 `completed`。
49
+
50
+ ## 使用
51
+
52
+ 以 `@dsh-cc/memory-consolidation` 加载插件。配置:
53
+
54
+ | Key | 默认值 | 含义 |
55
+ |---|---|---|
56
+ | `memoryHome` | harness home `memory/` | 记忆 home 根;抽取/dream 写入触发 agent 所在仓库的 `projects/<slug>/` |
57
+ | `extractEnabled` | `true` | 运行轮末抽取 |
58
+ | `dreamEnabled` | `true` | 运行三重门 dream |
59
+ | `minHours` | `24` | 两次整合间的最小间隔小时数 |
60
+ | `minSessions` | `5` | 需要整合的最小新 transcript 数 |
61
+ | `lockStaleMs` | `3_600_000` | 锁持有者过期窗口 |
62
+ | `subagentProviderName` | `fork` | fork 使用的一次性 provider |
63
+
64
+ ```ts
65
+ import consolidation from '@dsh-cc/memory-consolidation'
66
+ await ctx.plugin(consolidation, { minHours: 24, minSessions: 5 })
67
+ ```
68
+
69
+ ## Model Experience
70
+
71
+ 门关闭时,turn-stopping 监听器几乎无成本(一次锁读取)。当时间门与会话门打开时,
72
+ 每次整合运行一个 fork subagent,限制为读/搜索工具加 `structured_output` 上报工具;
73
+ 其输出不会追加到主 transcript。每轮抽取可能启动一个短暂后台 fork。
74
+
75
+ ## API
76
+
77
+ - `tryAcquireLock(fs, dir, pid, now, policy?)` / `rollbackLock(fs, dir, priorAt, policy?)` /
78
+ `readLastConsolidatedAt(fs, dir)` —— 整合锁。
79
+ - `gatesPass(input)` / `timeGatePasses(...)` / `sessionGatePasses(...)` —— 门谓词。
80
+ - `MEMORY_TOOL_FILTER` / `MEMORY_AGENT_TOOLS` —— 记忆作用域工具集(读/搜索 +
81
+ `structured_output`)。
82
+ - `MEMORY_WRITES_SCHEMA` —— 每个 fork 上报的 `outputSchema` 契约。
83
+ - `validateMemoryWrites(input)` / `writeMemoryFiles(fs, dir, writes)` /
84
+ `memoryWritePolicy(dir)` —— host 侧落盘(由记忆目录的拥有者
85
+ `@dsh-cc/memory` 持有,此处 re-export)。
86
+ - `buildExtractionPrompt` / `buildConsolidationPrompt` —— fork 的提示词。
87
+
88
+ ## 已知限制与延期工作
89
+
90
+ - `ctx.fs` 缝不暴露 mtime,因此锁将持有者 PID 与上次整合时间戳存入锁文件正文而非
91
+ 文件 mtime;崩溃恢复依赖过期窗口而非进程存活。
92
+ - 会话门当前通过 `ctx.sessions` 统计存活会话并将其视为新会话;带时钟的 transcript
93
+ 查询已延期。
94
+ - 没有删除通道:dream 会把过期记忆从 `MEMORY.md` 移除,但失去引用的主题文件仍留在
95
+ 盘上,直到被覆写。主题文件删除已延期(fork 的 allow-list 本来也没有 remove 工具)。
96
+ - 并行会话的抽取并写时为 last-writer-wins;dream 锁只串行化整合。
package/lib/gates.d.ts ADDED
@@ -0,0 +1,42 @@
1
+ /**
2
+ * The three dream gates: time, session count, and lock. Combinable pure
3
+ * predicates over inputs a caller reads from the seam, plus a composite check.
4
+ * @module @dsh-cc/memory-consolidation/gates
5
+ */
6
+ /** Inputs to the time and session gates. */
7
+ export interface ConsolidationGateInput {
8
+ /** Epoch of the last consolidation (0 when none / absent lock). */
9
+ lastConsolidatedAt: number;
10
+ /** Current epoch. */
11
+ now: number;
12
+ /** Minimum hours since the last consolidation. */
13
+ minHours: number;
14
+ /** Number of transcripts touched since the last consolidation. */
15
+ sessionCount: number;
16
+ /** Minimum transcripts to review. */
17
+ minSessions: number;
18
+ }
19
+ /**
20
+ * Time gate: at least `minHours` since the last consolidation.
21
+ * @param lastConsolidatedAt - last consolidated epoch (0 opens the gate).
22
+ * @param now - current epoch.
23
+ * @param minHours - minimum elapsed hours.
24
+ * @returns whether the time gate passes.
25
+ */
26
+ export declare function timeGatePasses(lastConsolidatedAt: number, now: number, minHours: number): boolean;
27
+ /**
28
+ * Session gate: at least `minSessions` transcripts touched since the last
29
+ * consolidation.
30
+ * @param sessionCount - transcripts touched since the last consolidation.
31
+ * @param minSessions - minimum transcripts to review.
32
+ * @returns whether the session gate passes.
33
+ */
34
+ export declare function sessionGatePasses(sessionCount: number, minSessions: number): boolean;
35
+ /**
36
+ * Composite check: the time and session gates together. The lock gate is a
37
+ * separate acquisition step (see {@link tryAcquireLock}).
38
+ * @param input - gate inputs.
39
+ * @returns whether both the time and session gates pass.
40
+ */
41
+ export declare function gatesPass(input: ConsolidationGateInput): boolean;
42
+ //# sourceMappingURL=gates.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"gates.d.ts","sourceRoot":"","sources":["../src/gates.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,4CAA4C;AAC5C,MAAM,WAAW,sBAAsB;IACrC,mEAAmE;IACnE,kBAAkB,EAAE,MAAM,CAAA;IAC1B,qBAAqB;IACrB,GAAG,EAAE,MAAM,CAAA;IACX,kDAAkD;IAClD,QAAQ,EAAE,MAAM,CAAA;IAChB,kEAAkE;IAClE,YAAY,EAAE,MAAM,CAAA;IACpB,qCAAqC;IACrC,WAAW,EAAE,MAAM,CAAA;CACpB;AAED;;;;;;GAMG;AACH,wBAAgB,cAAc,CAAC,kBAAkB,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,OAAO,CAIjG;AAED;;;;;;GAMG;AACH,wBAAgB,iBAAiB,CAAC,YAAY,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,GAAG,OAAO,CAEpF;AAED;;;;;GAKG;AACH,wBAAgB,SAAS,CAAC,KAAK,EAAE,sBAAsB,GAAG,OAAO,CAGhE"}
package/lib/gates.js ADDED
@@ -0,0 +1,39 @@
1
+ /**
2
+ * The three dream gates: time, session count, and lock. Combinable pure
3
+ * predicates over inputs a caller reads from the seam, plus a composite check.
4
+ * @module @dsh-cc/memory-consolidation/gates
5
+ */
6
+ /**
7
+ * Time gate: at least `minHours` since the last consolidation.
8
+ * @param lastConsolidatedAt - last consolidated epoch (0 opens the gate).
9
+ * @param now - current epoch.
10
+ * @param minHours - minimum elapsed hours.
11
+ * @returns whether the time gate passes.
12
+ */
13
+ export function timeGatePasses(lastConsolidatedAt, now, minHours) {
14
+ // A zero last-consolidation means none ever happened: open the gate.
15
+ if (lastConsolidatedAt <= 0)
16
+ return true;
17
+ return now - lastConsolidatedAt >= minHours * 3_600_000;
18
+ }
19
+ /**
20
+ * Session gate: at least `minSessions` transcripts touched since the last
21
+ * consolidation.
22
+ * @param sessionCount - transcripts touched since the last consolidation.
23
+ * @param minSessions - minimum transcripts to review.
24
+ * @returns whether the session gate passes.
25
+ */
26
+ export function sessionGatePasses(sessionCount, minSessions) {
27
+ return sessionCount >= minSessions;
28
+ }
29
+ /**
30
+ * Composite check: the time and session gates together. The lock gate is a
31
+ * separate acquisition step (see {@link tryAcquireLock}).
32
+ * @param input - gate inputs.
33
+ * @returns whether both the time and session gates pass.
34
+ */
35
+ export function gatesPass(input) {
36
+ return timeGatePasses(input.lastConsolidatedAt, input.now, input.minHours)
37
+ && sessionGatePasses(input.sessionCount, input.minSessions);
38
+ }
39
+ //# sourceMappingURL=gates.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"gates.js","sourceRoot":"","sources":["../src/gates.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAgBH;;;;;;GAMG;AACH,MAAM,UAAU,cAAc,CAAC,kBAA0B,EAAE,GAAW,EAAE,QAAgB;IACtF,qEAAqE;IACrE,IAAI,kBAAkB,IAAI,CAAC;QAAE,OAAO,IAAI,CAAA;IACxC,OAAO,GAAG,GAAG,kBAAkB,IAAI,QAAQ,GAAG,SAAS,CAAA;AACzD,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,iBAAiB,CAAC,YAAoB,EAAE,WAAmB;IACzE,OAAO,YAAY,IAAI,WAAW,CAAA;AACpC,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,SAAS,CAAC,KAA6B;IACrD,OAAO,cAAc,CAAC,KAAK,CAAC,kBAAkB,EAAE,KAAK,CAAC,GAAG,EAAE,KAAK,CAAC,QAAQ,CAAC;WACrE,iBAAiB,CAAC,KAAK,CAAC,YAAY,EAAE,KAAK,CAAC,WAAW,CAAC,CAAA;AAC/D,CAAC"}
package/lib/index.d.ts ADDED
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Background memory consolidation: turn-end extraction and the three-gate
3
+ * dream rewrite.
4
+ *
5
+ * `agent/turn-stopping` fires an extraction subagent (via `ctx.jobs` +
6
+ * `ctx.subagents`, tools restricted to read/search) that reports durable facts
7
+ * as structured output, and evaluates the dream gates (time, session count,
8
+ * lock) to schedule a read-only review whose structured output rewrites
9
+ * MEMORY.md and the topic files. The forks hold no write tools — the memory
10
+ * directory sits outside the session workspace, so the fs sandbox would fence
11
+ * every model-side write with no escalation path from a background job; the
12
+ * plugin validates each reported batch and writes it host-side under a
13
+ * per-call policy confined to the memory directory (see `writeback.ts`). A
14
+ * failed dream rolls back the lock so the time gate re-opens.
15
+ *
16
+ * @module @dsh-cc/memory-consolidation
17
+ */
18
+ import type { Context } from '@deepseek-ai/cordis';
19
+ import z from '@deepseek-ai/schemastery';
20
+ export { LOCK_FILE, LOCK_STALE_MS, readLastConsolidatedAt, rollbackLock, tryAcquireLock } from './lock.ts';
21
+ export { gatesPass, timeGatePasses, sessionGatePasses } from './gates.ts';
22
+ export type { ConsolidationGateInput } from './gates.ts';
23
+ export { MEMORY_AGENT_TOOLS, MEMORY_TOOL_FILTER } from './tools.ts';
24
+ export { buildConsolidationPrompt, buildExtractionPrompt } from './prompts.ts';
25
+ export { MEMORY_WRITES_SCHEMA, WRITEBACK_MAX_FILE_BYTES, WRITEBACK_MAX_FILES, WRITEBACK_MAX_TOTAL_BYTES, memoryWritePolicy, validateMemoryWrites, writeMemoryFiles, } from '@dsh-cc/memory';
26
+ export type { MemoryWrite, MemoryWritePolicy } from '@dsh-cc/memory';
27
+ export declare const name = "memory-consolidation";
28
+ /** Services required for background jobs and the subagent provider. */
29
+ export declare const inject: string[];
30
+ /** Memory consolidation configuration. */
31
+ export interface Config {
32
+ /** Memory directory root. Defaults to the harness home `memory/`. */
33
+ memoryHome?: string;
34
+ /** Turn-end extraction runs (default true). */
35
+ extractEnabled?: boolean;
36
+ /** The three-gate dream runs (default true). */
37
+ dreamEnabled?: boolean;
38
+ /** Minimum hours between consolidations (default 24). */
39
+ minHours?: number;
40
+ /** Minimum new transcripts to consolidate (default 5). */
41
+ minSessions?: number;
42
+ /** A lock holder is stale past this window (default 1 hour). */
43
+ lockStaleMs?: number;
44
+ /** One-shot subagent provider for forks (default `fork`). */
45
+ subagentProviderName?: string;
46
+ }
47
+ export declare const Config: z<Config>;
48
+ /**
49
+ * Register the consolidation plugin.
50
+ * @param ctx - the host context with jobs, subagents, fs, and sessions.
51
+ * @param config - consolidation behavior knobs.
52
+ */
53
+ export declare function apply(ctx: Context, config?: Config): void;
54
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AAGH,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,qBAAqB,CAAA;AAClD,OAAO,CAAC,MAAM,0BAA0B,CAAA;AAiBxC,OAAO,EAAE,SAAS,EAAE,aAAa,EAAE,sBAAsB,EAAE,YAAY,EAAE,cAAc,EAAE,MAAM,WAAW,CAAA;AAC1G,OAAO,EAAE,SAAS,EAAE,cAAc,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAA;AACzE,YAAY,EAAE,sBAAsB,EAAE,MAAM,YAAY,CAAA;AACxD,OAAO,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAA;AACnE,OAAO,EAAE,wBAAwB,EAAE,qBAAqB,EAAE,MAAM,cAAc,CAAA;AAG9E,OAAO,EACL,oBAAoB,EACpB,wBAAwB,EACxB,mBAAmB,EACnB,yBAAyB,EACzB,iBAAiB,EACjB,oBAAoB,EACpB,gBAAgB,GACjB,MAAM,gBAAgB,CAAA;AACvB,YAAY,EAAE,WAAW,EAAE,iBAAiB,EAAE,MAAM,gBAAgB,CAAA;AAEpE,eAAO,MAAM,IAAI,yBAAyB,CAAA;AAC1C,uEAAuE;AACvE,eAAO,MAAM,MAAM,UAAwB,CAAA;AAE3C,0CAA0C;AAC1C,MAAM,WAAW,MAAM;IACrB,qEAAqE;IACrE,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,+CAA+C;IAC/C,cAAc,CAAC,EAAE,OAAO,CAAA;IACxB,gDAAgD;IAChD,YAAY,CAAC,EAAE,OAAO,CAAA;IACtB,yDAAyD;IACzD,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB,0DAA0D;IAC1D,WAAW,CAAC,EAAE,MAAM,CAAA;IACpB,gEAAgE;IAChE,WAAW,CAAC,EAAE,MAAM,CAAA;IACpB,6DAA6D;IAC7D,oBAAoB,CAAC,EAAE,MAAM,CAAA;CAC9B;AAED,eAAO,MAAM,MAAM,EAAE,CAAC,CAAC,MAAM,CAQ3B,CAAA;AAyHF;;;;GAIG;AACH,wBAAgB,KAAK,CAAC,GAAG,EAAE,OAAO,EAAE,MAAM,GAAE,MAAW,GAAG,IAAI,CAkD7D"}