@dsh-cc/compaction-pinning 0.0.0-stage → 0.9.6-rc.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.
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 check:readme --write
5
+ README.md: a6b35f5f2c3ae90342c9bc0e1813b57660f75591
6
+ README.zh.md: b011aec35fe8a7bc42e3c17319b974603cb2b998
package/README.md CHANGED
@@ -1,3 +1,56 @@
1
- # Temporary Holding Version
1
+ # @dsh-cc/compaction-pinning
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ English | [中文](README.zh.md)
4
+
5
+ Governed-message pinning across compaction. Behavioral-governance messages — turn-rule reminders, post-edit-verify recovery hints — travel as ordinary `user/message` events, so summarization compaction can replace the whole region holding them with one checkpoint message and leave the instructions to survive only as whatever the summary kept. This plugin captures those messages verbatim in a bounded per-session ring and restores them verbatim once the checkpoint commits, so a governance instruction keeps its durable effect for the whole session instead of only until the next compaction.
6
+
7
+ ## How it works
8
+
9
+ - **Capture:** one observation-only `session/event` listener. For every `user/message` whose `source.kind` is one of the configured kinds, the WHOLE message object (content blocks plus source metadata, by reference, never cloned or destructured) is stored in that session's ring together with its seq and timestamp. The ring is FIFO-bounded by entry count and by estimated message bytes; the oldest entries are evicted first.
10
+ - **Restore:** the compaction's summary names the shadowed seqs, and that summary is provisional evidence only, because the engine appends `compaction/summary` before the checkpoint commit. A per-`compactionId` restore schedule therefore has to settle before it drains, and only settled pins are re-appended verbatim, oldest first, each as its own append so source boundaries survive. Rule (a): a successful `compaction/end` for that id proves the checkpoint committed, so the pins drain in the same pass. Rule (b): with no `compaction/end` of any kind, a schedule becomes eligible once it has aged at least one turn and the checkpoint commit was actually witnessed by the replacement `user/message` citing the summary's seq; that witness gate keeps a summary-only phantom from being restored over a live original. An `end` carrying `error` cancels the schedule outright, and a schedule that never becomes eligible is garbage-collected after two turns. Restored messages re-enter the ring naturally under a new seq, which makes re-shadowing self-healing rather than a loop.
11
+ - **Bounded:** two caps (entries and bytes) and a fixed kind list keep capture cheap and the restoration batch small. Nothing is appended from inside the event observer — restores drain from the agent's pre-step seam.
12
+ - **Defaults:** on, with the two durable behavioral-constraint kinds. Turning the feature off stops capture and restore; a ring is never retroactively rebuilt.
13
+
14
+ ## Settings (namespace `cc-compaction-pinning`)
15
+
16
+ Hot-read: the value is re-read on every message, so a settings edit applies immediately.
17
+
18
+ | Key | Type | Default | Bounds / meaning |
19
+ |---|---|---|---|
20
+ | `enabled` | bool | `true` | — Disabling stops capture and restore. |
21
+ | `pinned-source-kinds` | string[] | `['turn-rules','edit-recovery-hint']` | Each entry ≤ 64 chars; an empty or fully invalid list falls back to the default pair. |
22
+ | `max-pinned` | int | `16` | `1..64` — ring entry cap. |
23
+ | `max-pinned-bytes` | int | `16384` | `1024..262144` — ring byte cap. |
24
+
25
+ ```json
26
+ {
27
+ "cc-compaction-pinning": {
28
+ "max-pinned": 24,
29
+ "pinned-source-kinds": ["turn-rules", "edit-recovery-hint"]
30
+ }
31
+ }
32
+ ```
33
+
34
+ ## API
35
+
36
+ - `createScheduleStore()` returns the per-session restore-schedule store (`arm`, `get`, `succeed`, `cancel`, `commit`, `isEligible`, `eligible`, `pending`, `drop`, `gcDead`, `clear`). `raiseTurn(state, turn)` raises the monotonic rule-(b) turn clock, and `RULE_B_TURNS` / `SCHEDULE_GC_TURNS` export the two windows.
37
+ - `getPinningHealth()` / `bumpPinningHealth(key, by?)` / `resetPinningHealth()` expose process-wide counters `captured`, `restored`, `evicted`, `dropped`. They exist for tests: no user-facing notice, no ledger, no durable record.
38
+
39
+ ## Known gaps
40
+
41
+ - **Resume-generation gap.** The ring is process memory. A compaction in a session that was resumed by this process can shadow pins this process never captured; the producer re-fires over time (turn-rule reminders especially), but the interim is unprotected. Reconstructing immediately-present pins from the session's own projection at mount is a possible later version, deliberately out of scope here.
42
+ - **In-request one-request gap.** Compaction triggered inside a request retry (context overflow, model switch) commits after the retried request's messages were already derived, and a session event observer cannot append (re-entering publication throws). Pins return on the next step, so exactly one request can run without them. Closing it needs an engine-side seam that exempts pinned messages from span selection.
43
+ - **No summary input linkage.** The summarizer never sees the restored content; restoration mirrors the post-commit remedy rather than repairing the summary.
44
+
45
+ ## Usage
46
+
47
+ ```ts
48
+ import type { Context } from '@deepseek-ai/cordis'
49
+ import * as CompactionPinning from '@dsh-cc/compaction-pinning'
50
+
51
+ export function apply(ctx: Context): void {
52
+ ctx.plugin(CompactionPinning)
53
+ }
54
+ ```
55
+
56
+ Plain plugin, non-isolate. Settings live in `<dshHome>/settings.json`; the package registers its namespace for `/config` UX and validation and re-reads it per message, and it also exports a raw user-layer reader for callers that must exclude project scope entirely.
package/README.zh.md ADDED
@@ -0,0 +1,56 @@
1
+ # @dsh-cc/compaction-pinning
2
+
3
+ [English](README.md) | 中文
4
+
5
+ 压缩过程中的治理消息钉扎。行为治理类消息——回合规则提醒、编辑后验证的恢复提示——以普通 `user/message` 事件的形式传输,因此摘要压缩可以把包含它们的整个区间替换成一条检查点消息,让这些指令只剩下摘要恰好保留的部分。本插件把这些消息逐字捕获进一个有界的按会话环形缓冲,并在检查点提交后逐字恢复它们,使一条治理指令的约束力贯穿整个会话,而不是只维持到下一次压缩。
6
+
7
+ ## 工作方式
8
+
9
+ - **捕获:** 一个纯观察的 `session/event` 监听器。对每条 `source.kind` 属于已配置种类的 `user/message`,把**整个**消息对象(内容块加 source 元数据,按引用保留,绝不克隆或解构)连同其 seq 与时间戳存入该会话的环形缓冲。缓冲按条目数和估算字节数做 FIFO 上限;最旧的条目先被淘汰。
10
+ - **恢复:** 压缩的摘要会列出被遮蔽的 seq,而该摘要只是暂定证据,因为引擎在检查点提交之前就已追加 `compaction/summary`。因此每个 `compactionId` 对应一份恢复计划,必须先完成结算才能排空,只有已结算的钉扎消息才会按原 seq 升序逐字重新追加,每条各自追加一次,以便来源边界保留。规则 (a):该 id 收到一次成功的 `compaction/end` 即证明检查点已提交,钉扎消息在同一次排空中恢复。规则 (b):完全没有见到任何 `compaction/end` 时,计划需同时满足已老化至少一个回合、且检查点提交确实被目睹(引用摘要 seq 的替换 `user/message`)才具备资格;这道目睹门槛避免把只有摘要的幻影覆盖到仍然存活的原文之上。携带 `error` 的 `end` 直接取消该计划,始终无法具备资格的计划在两个回合后被垃圾回收。恢复后的消息以新的 seq 自然重新进入环形缓冲,因此再次被遮蔽会自愈而不是死循环。
11
+ - **有界:** 两个上限(条目数与字节数)加一份固定种类表,让捕获开销低、恢复批次小。事件观察回调内绝不追加消息——恢复从代理的 pre-step 接缝排空。
12
+ - **默认:** 开启,种类为两种持久的行为约束来源。关闭该功能会停止捕获与恢复;环形缓冲从不被回溯重建。
13
+
14
+ ## 配置(命名空间 `cc-compaction-pinning`)
15
+
16
+ 热读取:每条消息都会重新读取配置值,因此修改设置立即生效。
17
+
18
+ | 键 | 类型 | 默认 | 范围 / 含义 |
19
+ |---|---|---|---|
20
+ | `enabled` | bool | `true` | — 关闭后停止捕获与恢复。 |
21
+ | `pinned-source-kinds` | string[] | `['turn-rules','edit-recovery-hint']` | 每项 ≤ 64 字符;空列表或全部非法时回退到默认两项。 |
22
+ | `max-pinned` | int | `16` | `1..64` — 环形缓冲条目上限。 |
23
+ | `max-pinned-bytes` | int | `16384` | `1024..262144` — 环形缓冲字节上限。 |
24
+
25
+ ```json
26
+ {
27
+ "cc-compaction-pinning": {
28
+ "max-pinned": 24,
29
+ "pinned-source-kinds": ["turn-rules", "edit-recovery-hint"]
30
+ }
31
+ }
32
+ ```
33
+
34
+ ## API
35
+
36
+ - `createScheduleStore()` 返回每会话的恢复计划存储(`arm`、`get`、`succeed`、`cancel`、`commit`、`isEligible`、`eligible`、`pending`、`drop`、`gcDead`、`clear`)。`raiseTurn(state, turn)` 单调抬高规则 (b) 的回合时钟,`RULE_B_TURNS` / `SCHEDULE_GC_TURNS` 导出两个窗口。
37
+ - `getPinningHealth()` / `bumpPinningHealth(key, by?)` / `resetPinningHealth()` 暴露进程级计数器 `captured`、`restored`、`evicted`、`dropped`。它们只服务于测试:没有面向用户的通告、没有账本、没有持久记录。
38
+
39
+ ## 已知缺口
40
+
41
+ - **恢复代际缺口(resume-generation gap)。** 环形缓冲是进程内存。本进程恢复的会话里发生的压缩,可能遮蔽本进程从未捕获的钉扎消息;生产者会随时间重新触发(尤其回合规则提醒),但中间这段没有保护。挂载时从会话自身的投影重建当下已存在的钉扎消息,是后续版本的可行方向,此处刻意不做。
42
+ - **请求内一步缺失(in-request one-request gap)。** 在请求重试内部触发的压缩(上下文溢出、模型切换)发生在其重试请求的消息已派生之后,而会话事件观察者无法追加消息(重新进入发布流程会抛错)。钉扎消息在下一步恢复,因此恰好有一个请求可能缺少它们。要彻底闭合,需要引擎侧接缝,把钉扎消息从区间选择中豁免。
43
+ - **摘要无输入联动。** 摘要器看不到恢复的内容;恢复对应的是提交后的补救措施,而不是修复摘要本身。
44
+
45
+ ## 用法
46
+
47
+ ```ts
48
+ import type { Context } from '@deepseek-ai/cordis'
49
+ import * as CompactionPinning from '@dsh-cc/compaction-pinning'
50
+
51
+ export function apply(ctx: Context): void {
52
+ ctx.plugin(CompactionPinning)
53
+ }
54
+ ```
55
+
56
+ 普通插件,非 isolate。配置位于 `<dshHome>/settings.json`;本包注册自己的命名空间用于 `/config` UX 与校验,并在每条消息上重新读取它,同时导出原始的用户层读取器,供需要完全排除项目作用域的调用方使用。
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Detect half (design docs/plans/2026-11-12-compaction-governed-pinning.md
3
+ * §Detect): turn `compaction/*` traffic into restore schedules.
4
+ *
5
+ * One observation-only `{ global: true }` `session/event` listener — appends are
6
+ * forbidden here (`reenter`, harness core/session/src/index.ts
7
+ * `publicationEntry`), so this half only ever mutates per-session memory.
8
+ *
9
+ * Event vocabulary (harness `compaction/compaction/src/types.ts` in the pinned
10
+ * copy): `compaction/summary` carries `{compactionId, shadowedSeqs, …}` and is
11
+ * appended BEFORE the checkpoint commit; `compaction/end` carries only
12
+ * `{compactionId, sourceCommandId?, turn, error?}`. Reading `shadowedSeqs` off
13
+ * the end event is the shape bug this split exists to prevent.
14
+ *
15
+ * The three things this listener does:
16
+ *
17
+ * 1. **Arms** a schedule on `compaction/summary` when the summary carries
18
+ * `shadowedSeqs` and at least one of them is still in the capture ring
19
+ * (`restorable = shadowedSeqs ∩ ring`, ascending). The summary is
20
+ * provisional, so nothing here decides that a restore is owed.
21
+ * 2. **Settles** on `compaction/end`: an end carrying `error` CANCELS the
22
+ * schedule (the belt — the failed-commit path at `region.ts` appends that
23
+ * end after the summary was already logged); a clean end marks the schedule
24
+ * restorable (rule (a)).
25
+ * 3. **Witnesses the checkpoint commit** for rule (b): the replacement
26
+ * `user/message` the engine appends immediately after the summary carries
27
+ * `surfaceOp: { op: 'replace', … }` and `sourceEventSeqs` include the
28
+ * summary's own seq (contractual adjacency — a consumer may pair a
29
+ * replacement with the metering event directly before it). That citation is
30
+ * the only durable proof the shadowing actually happened, and rule (b)
31
+ * requires it (see `./schedule.ts` for why: the F3 double-failure window).
32
+ *
33
+ * TURN SIGNAL (rule (b) ageing, §Detect). The per-session turn clock is fed by
34
+ * `'turn/start'` session events (`{turn}`, harness core/session/src/types.ts;
35
+ * the loop appends one per turn before that turn's first `agent/pre-step`),
36
+ * raised monotonically and additionally by the drain from its `agent/pre-step`
37
+ * payload `turn` (the loop's authoritative position). Why not
38
+ * `compaction/end.turn`? That field is `number | null` and is `null` on the
39
+ * idle paths (manual `/compact`, cost-gate idle), i.e. exactly the compactions
40
+ * where rule (b) matters; and it is absent from `compaction/summary`
41
+ * altogether. `turn/start` is the only signal present for every turn.
42
+ *
43
+ * @module
44
+ */
45
+ import type { Context } from '@deepseek-ai/cordis';
46
+ import type { PinningStateRegistry } from './index.ts';
47
+ import type { CompactionPinningSettings } from './settings.ts';
48
+ /**
49
+ * Register the detect listener (design §Detect). Observe-only; every fault is
50
+ * contained — nothing may throw across the firehose boundary.
51
+ * @param ctx - the plug context.
52
+ * @param readSettings - live settings reader (hot-read).
53
+ * @param states - the per-session state registry (shared with capture/drain).
54
+ */
55
+ export declare function registerDetect(ctx: Context, readSettings: () => CompactionPinningSettings, states: PinningStateRegistry): void;
56
+ //# sourceMappingURL=detect.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"detect.d.ts","sourceRoot":"","sources":["../src/detect.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2CG;AAEH,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,qBAAqB,CAAA;AAElD,OAAO,KAAK,EAAgB,oBAAoB,EAAE,MAAM,YAAY,CAAA;AAEpE,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,eAAe,CAAA;AAgG9D;;;;;;GAMG;AACH,wBAAgB,cAAc,CAC5B,GAAG,EAAE,OAAO,EACZ,YAAY,EAAE,MAAM,yBAAyB,EAC7C,MAAM,EAAE,oBAAoB,GAC3B,IAAI,CAwCN"}
package/lib/detect.js ADDED
@@ -0,0 +1,183 @@
1
+ /**
2
+ * Detect half (design docs/plans/2026-11-12-compaction-governed-pinning.md
3
+ * §Detect): turn `compaction/*` traffic into restore schedules.
4
+ *
5
+ * One observation-only `{ global: true }` `session/event` listener — appends are
6
+ * forbidden here (`reenter`, harness core/session/src/index.ts
7
+ * `publicationEntry`), so this half only ever mutates per-session memory.
8
+ *
9
+ * Event vocabulary (harness `compaction/compaction/src/types.ts` in the pinned
10
+ * copy): `compaction/summary` carries `{compactionId, shadowedSeqs, …}` and is
11
+ * appended BEFORE the checkpoint commit; `compaction/end` carries only
12
+ * `{compactionId, sourceCommandId?, turn, error?}`. Reading `shadowedSeqs` off
13
+ * the end event is the shape bug this split exists to prevent.
14
+ *
15
+ * The three things this listener does:
16
+ *
17
+ * 1. **Arms** a schedule on `compaction/summary` when the summary carries
18
+ * `shadowedSeqs` and at least one of them is still in the capture ring
19
+ * (`restorable = shadowedSeqs ∩ ring`, ascending). The summary is
20
+ * provisional, so nothing here decides that a restore is owed.
21
+ * 2. **Settles** on `compaction/end`: an end carrying `error` CANCELS the
22
+ * schedule (the belt — the failed-commit path at `region.ts` appends that
23
+ * end after the summary was already logged); a clean end marks the schedule
24
+ * restorable (rule (a)).
25
+ * 3. **Witnesses the checkpoint commit** for rule (b): the replacement
26
+ * `user/message` the engine appends immediately after the summary carries
27
+ * `surfaceOp: { op: 'replace', … }` and `sourceEventSeqs` include the
28
+ * summary's own seq (contractual adjacency — a consumer may pair a
29
+ * replacement with the metering event directly before it). That citation is
30
+ * the only durable proof the shadowing actually happened, and rule (b)
31
+ * requires it (see `./schedule.ts` for why: the F3 double-failure window).
32
+ *
33
+ * TURN SIGNAL (rule (b) ageing, §Detect). The per-session turn clock is fed by
34
+ * `'turn/start'` session events (`{turn}`, harness core/session/src/types.ts;
35
+ * the loop appends one per turn before that turn's first `agent/pre-step`),
36
+ * raised monotonically and additionally by the drain from its `agent/pre-step`
37
+ * payload `turn` (the loop's authoritative position). Why not
38
+ * `compaction/end.turn`? That field is `number | null` and is `null` on the
39
+ * idle paths (manual `/compact`, cost-gate idle), i.e. exactly the compactions
40
+ * where rule (b) matters; and it is absent from `compaction/summary`
41
+ * altogether. `turn/start` is the only signal present for every turn.
42
+ *
43
+ * @module
44
+ */
45
+ import { raiseTurn } from "./schedule.js";
46
+ /** One `session/event` handler's worth of per-session state, or `undefined`. */
47
+ function stateOf(states, session) {
48
+ return states.peek(String(session.header.id));
49
+ }
50
+ /**
51
+ * Arm a schedule from one `compaction/summary` event.
52
+ * @param state - the session's pinning state.
53
+ * @param event - the summary event.
54
+ */
55
+ function onSummary(state, event) {
56
+ const data = event.data;
57
+ if (typeof data.compactionId !== 'string')
58
+ return;
59
+ if (!Array.isArray(data.shadowedSeqs))
60
+ return;
61
+ const restorable = [];
62
+ for (const raw of data.shadowedSeqs) {
63
+ const seq = Number(raw);
64
+ if (!Number.isSafeInteger(seq))
65
+ continue;
66
+ const entry = state.ring.get(seq);
67
+ if (entry === undefined)
68
+ continue;
69
+ // Keep the message by reference: restore re-appends this exact object, and
70
+ // holding it here means a later ring eviction cannot shrink a scheduled
71
+ // restore batch that was already decided.
72
+ restorable.push({ seq: entry.seq, message: entry.message });
73
+ }
74
+ // Empty intersection (§Detect): nothing was pinned inside the shadowed span.
75
+ if (restorable.length === 0)
76
+ return;
77
+ restorable.sort((left, right) => left.seq - right.seq);
78
+ state.schedules.arm(String(data.compactionId), restorable, state.turn);
79
+ // Provisional evidence only — remembered so a following replacement can
80
+ // prove the commit happened (rule (b)); it is not completion evidence.
81
+ state.lastSummary = { compactionId: String(data.compactionId), summarySeq: Number(event.seq) };
82
+ }
83
+ /**
84
+ * Settle a schedule from one `compaction/end` event: the belt on `error`,
85
+ * rule (a) otherwise.
86
+ * @param state - the session's pinning state.
87
+ * @param event - the end event.
88
+ */
89
+ function onEnd(state, event) {
90
+ const data = event.data;
91
+ if (typeof data.compactionId !== 'string')
92
+ return;
93
+ const compactionId = String(data.compactionId);
94
+ if (state.lastSummary?.compactionId === compactionId)
95
+ state.lastSummary = undefined;
96
+ if (data.error !== undefined) {
97
+ // BELT: a failed commit logged a summary but shadowed nothing, so a
98
+ // restore here would duplicate live governance content.
99
+ state.schedules.cancel(compactionId);
100
+ return;
101
+ }
102
+ state.schedules.succeed(compactionId);
103
+ }
104
+ /**
105
+ * Witness the checkpoint commit from the replacement `user/message` that cites
106
+ * the pending summary (rule (b)'s gate).
107
+ * @param state - the session's pinning state.
108
+ * @param event - a `user/message` event.
109
+ */
110
+ function onCheckpoint(state, event) {
111
+ const witness = state.lastSummary;
112
+ if (witness === undefined)
113
+ return;
114
+ // Single-shot adjacency: the engine appends the replacement immediately after
115
+ // the summary, so the first `user/message` that follows consumes the
116
+ // witness either way — a stale witness can never be claimed later.
117
+ state.lastSummary = undefined;
118
+ const metadata = event;
119
+ const surfaceOp = metadata.surfaceOp;
120
+ if (surfaceOp === undefined || surfaceOp === null || surfaceOp.op !== 'replace')
121
+ return;
122
+ const sources = metadata.sourceEventSeqs;
123
+ if (!Array.isArray(sources) || !sources.includes(witness.summarySeq))
124
+ return;
125
+ state.schedules.commit(witness.compactionId);
126
+ }
127
+ /**
128
+ * Register the detect listener (design §Detect). Observe-only; every fault is
129
+ * contained — nothing may throw across the firehose boundary.
130
+ * @param ctx - the plug context.
131
+ * @param readSettings - live settings reader (hot-read).
132
+ * @param states - the per-session state registry (shared with capture/drain).
133
+ */
134
+ export function registerDetect(ctx, readSettings, states) {
135
+ const debug = (message) => {
136
+ try {
137
+ ctx.logger.debug(`compaction-pinning: ${message}`);
138
+ }
139
+ catch {
140
+ // Never throw into a hot path.
141
+ }
142
+ };
143
+ ctx.on('session/event', (session, event) => {
144
+ try {
145
+ // `compaction/*` and `turn/start` are declared by other packages'
146
+ // augmentations (not this plugin's), so compare as widened strings — the
147
+ // in-repo precedent (progress-rebuild/src/delivery.ts, hooks-claude-code
148
+ // register-events.ts). `user/message` stays a literal: it is a core map
149
+ // member, so `event.data` narrows to `UserMessage`.
150
+ const type = event.type;
151
+ if (type === 'turn/start') {
152
+ // The rule-(b) clock. Kept even while the feature is disabled so a
153
+ // later re-enable never resumes on a stale clock.
154
+ const state = stateOf(states, session);
155
+ if (state !== undefined)
156
+ raiseTurn(state, event.data.turn);
157
+ return;
158
+ }
159
+ if (type === 'user/message') {
160
+ const state = stateOf(states, session);
161
+ if (state !== undefined)
162
+ onCheckpoint(state, event);
163
+ return;
164
+ }
165
+ if (type !== 'compaction/summary' && type !== 'compaction/end')
166
+ return;
167
+ if (!readSettings().enabled)
168
+ return;
169
+ const state = stateOf(states, session);
170
+ if (state === undefined)
171
+ return;
172
+ if (type === 'compaction/summary')
173
+ onSummary(state, event);
174
+ else
175
+ onEnd(state, event);
176
+ }
177
+ catch (error) {
178
+ // §Failure semantics: never cross the firehose boundary.
179
+ debug(`detect failed: ${error instanceof Error ? error.message : String(error)}`);
180
+ }
181
+ }, { global: true });
182
+ }
183
+ //# sourceMappingURL=detect.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"detect.js","sourceRoot":"","sources":["../src/detect.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2CG;AAKH,OAAO,EAAE,SAAS,EAAoB,MAAM,eAAe,CAAA;AAsB3D,gFAAgF;AAChF,SAAS,OAAO,CAAC,MAA4B,EAAE,OAAgB;IAC7D,OAAO,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC,CAAA;AAC/C,CAAC;AAED;;;;GAIG;AACH,SAAS,SAAS,CAAC,KAAmB,EAAE,KAAmB;IACzD,MAAM,IAAI,GAAG,KAAK,CAAC,IAAmB,CAAA;IACtC,IAAI,OAAO,IAAI,CAAC,YAAY,KAAK,QAAQ;QAAE,OAAM;IACjD,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,YAAY,CAAC;QAAE,OAAM;IAC7C,MAAM,UAAU,GAAkB,EAAE,CAAA;IACpC,KAAK,MAAM,GAAG,IAAI,IAAI,CAAC,YAAY,EAAE,CAAC;QACpC,MAAM,GAAG,GAAG,MAAM,CAAC,GAAG,CAAC,CAAA;QACvB,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,GAAG,CAAC;YAAE,SAAQ;QACxC,MAAM,KAAK,GAAG,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,CAAA;QACjC,IAAI,KAAK,KAAK,SAAS;YAAE,SAAQ;QACjC,2EAA2E;QAC3E,wEAAwE;QACxE,0CAA0C;QAC1C,UAAU,CAAC,IAAI,CAAC,EAAE,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D,MAAM,KAAK,GAAG,OAAO,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;gBACtC,IAAI,KAAK,KAAK,SAAS;oBAAE,SAAS,CAAC,KAAK,EAAG,KAAK,CAAC,IAA2B,CAAC,IAAI,CAAC,CAAA;gBAClF,OAAM;YACR,CAAC;YACD,IAAI,IAAI,KAAK,cAAc,EAAE,CAAC;gBAC5B,MAAM,KAAK,GAAG,OAAO,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;gBACtC,IAAI,KAAK,KAAK,SAAS;oBAAE,YAAY,CAAC,KAAK,EAAE,KAAK,CAAC,CAAA;gBACnD,OAAM;YACR,CAAC;YACD,IAAI,IAAI,KAAK,oBAAoB,IAAI,IAAI,KAAK,gBAAgB;gBAAE,OAAM;YACtE,IAAI,CAAC,YAAY,EAAE,CAAC,OAAO;gBAAE,OAAM;YACnC,MAAM,KAAK,GAAG,OAAO,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;YACtC,IAAI,KAAK,KAAK,SAAS;gBAAE,OAAM;YAC/B,IAAI,IAAI,KAAK,oBAAoB;gBAAE,SAAS,CAAC,KAAK,EAAE,KAAK,CAAC,CAAA;;gBACrD,KAAK,CAAC,KAAK,EAAE,KAAK,CAAC,CAAA;QAC1B,CAAC;QAAC,OAAO,KAAc,EAAE,CAAC;YACxB,yDAAyD;YACzD,KAAK,CAAC,kBAAkB,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,CAAA;QACnF,CAAC;IACH,CAAC,EAAE,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,CAAA;AACtB,CAAC"}
@@ -0,0 +1,44 @@
1
+ /**
2
+ * In-process pinning health counters (design
3
+ * docs/plans/2026-11-12-compaction-governed-pinning.md §Failure semantics):
4
+ * `dropped`, `restored`, `evicted`, `captured` live in one process-wide record
5
+ * and are exposed through {@link getPinningHealth} for TESTS only. There is no
6
+ * user-facing notice, no ledger, and no durable record — the counters exist so
7
+ * specs can assert the failure paths (drop on capture error, FIFO eviction, …)
8
+ * that are otherwise invisible by design.
9
+ *
10
+ * Counters are module-level and per process (not per session): the rings
11
+ * themselves are per session, so a test that needs a clean slate calls
12
+ * {@link resetPinningHealth}.
13
+ *
14
+ * @module
15
+ */
16
+ /** The pinning counters (§Failure semantics). */
17
+ export interface PinningHealth {
18
+ /** Capture/store refusals and failures — the entry was NOT stored. */
19
+ dropped: number;
20
+ /** Restores committed by the drain (the restore half owns this increment). */
21
+ restored: number;
22
+ /** FIFO evictions performed on a per-session ring. */
23
+ evicted: number;
24
+ /** Messages stored verbatim into a per-session ring. */
25
+ captured: number;
26
+ }
27
+ /** One counter name. */
28
+ export type PinningHealthKey = keyof PinningHealth;
29
+ /**
30
+ * Snapshot the counters. Returns a copy, so a caller can never mutate live
31
+ * accounting.
32
+ * @returns the current counter values.
33
+ */
34
+ export declare function getPinningHealth(): PinningHealth;
35
+ /**
36
+ * Increment one counter. Never throws — every caller sits in a firehose or
37
+ * cleanup path.
38
+ * @param key - the counter to bump.
39
+ * @param by - increment (defaults to one).
40
+ */
41
+ export declare function bumpPinningHealth(key: PinningHealthKey, by?: number): void;
42
+ /** Reset every counter to zero (test seam — the counters are process-wide). */
43
+ export declare function resetPinningHealth(): void;
44
+ //# sourceMappingURL=health.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"health.d.ts","sourceRoot":"","sources":["../src/health.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,iDAAiD;AACjD,MAAM,WAAW,aAAa;IAC5B,sEAAsE;IACtE,OAAO,EAAE,MAAM,CAAA;IACf,8EAA8E;IAC9E,QAAQ,EAAE,MAAM,CAAA;IAChB,sDAAsD;IACtD,OAAO,EAAE,MAAM,CAAA;IACf,wDAAwD;IACxD,QAAQ,EAAE,MAAM,CAAA;CACjB;AAED,wBAAwB;AACxB,MAAM,MAAM,gBAAgB,GAAG,MAAM,aAAa,CAAA;AAUlD;;;;GAIG;AACH,wBAAgB,gBAAgB,IAAI,aAAa,CAEhD;AAED;;;;;GAKG;AACH,wBAAgB,iBAAiB,CAAC,GAAG,EAAE,gBAAgB,EAAE,EAAE,SAAI,GAAG,IAAI,CAErE;AAED,+EAA+E;AAC/E,wBAAgB,kBAAkB,IAAI,IAAI,CAKzC"}