@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/lib/health.js ADDED
@@ -0,0 +1,47 @@
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 live counters (module state; never exported by reference). */
17
+ const counters = {
18
+ dropped: 0,
19
+ restored: 0,
20
+ evicted: 0,
21
+ captured: 0,
22
+ };
23
+ /**
24
+ * Snapshot the counters. Returns a copy, so a caller can never mutate live
25
+ * accounting.
26
+ * @returns the current counter values.
27
+ */
28
+ export function getPinningHealth() {
29
+ return { ...counters };
30
+ }
31
+ /**
32
+ * Increment one counter. Never throws — every caller sits in a firehose or
33
+ * cleanup path.
34
+ * @param key - the counter to bump.
35
+ * @param by - increment (defaults to one).
36
+ */
37
+ export function bumpPinningHealth(key, by = 1) {
38
+ counters[key] += by;
39
+ }
40
+ /** Reset every counter to zero (test seam — the counters are process-wide). */
41
+ export function resetPinningHealth() {
42
+ counters.dropped = 0;
43
+ counters.restored = 0;
44
+ counters.evicted = 0;
45
+ counters.captured = 0;
46
+ }
47
+ //# sourceMappingURL=health.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"health.js","sourceRoot":"","sources":["../src/health.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAiBH,qEAAqE;AACrE,MAAM,QAAQ,GAAkB;IAC9B,OAAO,EAAE,CAAC;IACV,QAAQ,EAAE,CAAC;IACX,OAAO,EAAE,CAAC;IACV,QAAQ,EAAE,CAAC;CACZ,CAAA;AAED;;;;GAIG;AACH,MAAM,UAAU,gBAAgB;IAC9B,OAAO,EAAE,GAAG,QAAQ,EAAE,CAAA;AACxB,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,iBAAiB,CAAC,GAAqB,EAAE,EAAE,GAAG,CAAC;IAC7D,QAAQ,CAAC,GAAG,CAAC,IAAI,EAAE,CAAA;AACrB,CAAC;AAED,+EAA+E;AAC/E,MAAM,UAAU,kBAAkB;IAChC,QAAQ,CAAC,OAAO,GAAG,CAAC,CAAA;IACpB,QAAQ,CAAC,QAAQ,GAAG,CAAC,CAAA;IACrB,QAAQ,CAAC,OAAO,GAAG,CAAC,CAAA;IACpB,QAAQ,CAAC,QAAQ,GAAG,CAAC,CAAA;AACvB,CAAC"}
package/lib/index.d.ts ADDED
@@ -0,0 +1,134 @@
1
+ /**
2
+ * Compaction governed-message pinning (design
3
+ * docs/plans/2026-11-12-compaction-governed-pinning.md).
4
+ *
5
+ * Behavioral-governance messages (turn-rules reminders, post-edit-verify
6
+ * recovery hints) travel as ordinary `user/message` events. Summarization
7
+ * compaction replaces a whole `[startSeq, endSeq]` region with one checkpoint,
8
+ * so those instructions survive only as whatever the summary kept. This plugin
9
+ * captures them VERBATIM in a bounded per-session ring before they can be
10
+ * shadowed, schedules their restoration when a compaction reports them among
11
+ * its `shadowedSeqs`, and drains that schedule back into the session after the
12
+ * checkpoint commits.
13
+ *
14
+ * Three seams, one settings read:
15
+ *
16
+ * - capture — a `{ global: true }` `session/event` observer (`./ring.ts`,
17
+ * {@link registerCapture});
18
+ * - detect — a second `{ global: true }` `session/event` observer that arms /
19
+ * settles schedules from `compaction/summary` and `compaction/end`
20
+ * (`./detect.ts`, {@link registerDetect});
21
+ * - restore — an `agent/pre-step` listener registered `{ prepend: true }` and
22
+ * delegate-first (`./restore.ts`, {@link registerRestore}).
23
+ *
24
+ * Nothing is appended from inside the firehose — mutation there throws
25
+ * `reenter` (harness core/session/src/index.ts `publicationEntry`) — so the two
26
+ * observers are purely observational and every append happens in the drain.
27
+ *
28
+ * Capture read shape (design §Current behavior, the r1 BLOCKER fix):
29
+ * `'user/message'` events carry the `UserMessage` object ITSELF as `data`
30
+ * (harness core/session/src/types.ts), so the listener reads
31
+ * `event.data.source` / `event.data.content` — never `event.data.message.*`.
32
+ *
33
+ * Plain plugin (not a Service, non-isolate): `apply(ctx)` registers the settings
34
+ * namespace for /config UX and mounts the three seams. Every fault is
35
+ * contained — a throw across the firehose or waterfall boundary is never
36
+ * allowed (§Failure semantics).
37
+ *
38
+ * @module @dsh-cc/compaction-pinning
39
+ */
40
+ import type { Context } from '@deepseek-ai/cordis';
41
+ import { type PinRing } from './ring.ts';
42
+ import { type ScheduleStore } from './schedule.ts';
43
+ import { type CompactionPinningSettings } from './settings.ts';
44
+ export { SETTINGS_NAMESPACE, SettingsSchema, DEFAULT_COMPACTION_PINNING_SETTINGS, DEFAULT_ENABLED, DEFAULT_PINNED_SOURCE_KINDS, DEFAULT_MAX_PINNED, DEFAULT_MAX_PINNED_BYTES, MIN_PINNED, MAX_PINNED, MIN_PINNED_BYTES, MAX_PINNED_BYTES, MAX_SOURCE_KIND_CHARS, registerSettings, readUserSettings, type CompactionPinningSettings, } from './settings.ts';
45
+ export { createPinRing, estimateMessageBytes, type PinRing, type PinRingEntry, type PinRingOptions, } from './ring.ts';
46
+ export { createScheduleStore, raiseTurn, RULE_B_TURNS, SCHEDULE_GC_TURNS, type RestoreItem, type RestoreSchedule, type ScheduleStore, } from './schedule.ts';
47
+ export { registerDetect } from './detect.ts';
48
+ export { registerRestore } from './restore.ts';
49
+ export { getPinningHealth, bumpPinningHealth, resetPinningHealth, type PinningHealth, type PinningHealthKey, } from './health.ts';
50
+ /** Cordis plugin id. */
51
+ export declare const name = "compaction-pinning";
52
+ /**
53
+ * One session's pinning state. The ring is the capture half's payload; the
54
+ * restore half adds its own per-session bookkeeping on the SAME object —
55
+ * pending restore schedules keyed by `compactionId`, the rule-(b) turn clock,
56
+ * and the provisional summary whose checkpoint commit is still unwitnessed
57
+ * (`./detect.ts`). The state object is the single per-session seam, so no
58
+ * second registry is ever needed.
59
+ */
60
+ export interface PinningState {
61
+ /** Bounded FIFO ring of verbatim captured governance messages. */
62
+ readonly ring: PinRing;
63
+ /** Pending restore schedules, keyed by `compactionId` (§Detect). */
64
+ readonly schedules: ScheduleStore;
65
+ /**
66
+ * Highest turn observed for this session — the rule-(b) clock (§Detect).
67
+ * Fed by `turn/start` events and by the drain's `agent/pre-step` payload
68
+ * turn. A state created mid-turn starts at 0 and is corrected by the next
69
+ * `turn/start`; that only ever shortens the rule-(b) wait for a schedule
70
+ * armed in the same turn the state was born, and rule (b) independently
71
+ * requires a witnessed checkpoint commit, so no phantom restore can follow.
72
+ */
73
+ turn: number;
74
+ /**
75
+ * The most recent summary's provisional commit witness: cleared by the next
76
+ * replacement `user/message`, which either proves the commit (rule (b)) or
77
+ * arrives without citing it.
78
+ */
79
+ lastSummary: {
80
+ readonly compactionId: string;
81
+ readonly summarySeq: number;
82
+ } | undefined;
83
+ }
84
+ /** The session-id-keyed state registry both halves read. */
85
+ export interface PinningStateRegistry {
86
+ /**
87
+ * The state for one session, created on first use with the CURRENT
88
+ * hot-read caps.
89
+ * @param sessionId - `String(session.header.id)`.
90
+ */
91
+ stateOf(sessionId: string): PinningState;
92
+ /** The state only if it already exists (no creation). */
93
+ peek(sessionId: string): PinningState | undefined;
94
+ /** Drop one session's state (Session disposal, §Capture TTL honesty). */
95
+ delete(sessionId: string): void;
96
+ /** Live session ids (diagnostics/tests). */
97
+ ids(): string[];
98
+ }
99
+ /**
100
+ * Create the state registry. Caps come from the settings reader at ring
101
+ * creation; the capture listener re-applies them per event so a mid-session
102
+ * settings edit shrinks (or grows) the ring immediately.
103
+ * @param readSettings - live settings reader (hot-read per use).
104
+ * @returns the registry.
105
+ */
106
+ export declare function createPinningStateRegistry(readSettings: () => CompactionPinningSettings): PinningStateRegistry;
107
+ /** Additive plugin config (test seams only; both default to production wiring). */
108
+ export interface PinningPluginConfig {
109
+ /** Test seam: inject a live settings reader instead of the namespace one. */
110
+ readonly readSettings?: () => CompactionPinningSettings;
111
+ /** Test seam: inject a pre-built state registry (the restore half mounts over the same one). */
112
+ readonly states?: PinningStateRegistry;
113
+ }
114
+ /**
115
+ * Register the capture listener (design §Capture) and the Session-disposal
116
+ * cleanup. Observe-only: no append, no waterfall, no mutation.
117
+ * @param ctx - the plug context.
118
+ * @param readSettings - live settings reader.
119
+ * @param states - the per-session state registry.
120
+ */
121
+ export declare function registerCapture(ctx: Context, readSettings: () => CompactionPinningSettings, states: PinningStateRegistry): void;
122
+ /**
123
+ * Mount the plugin: register the settings namespace (for /config UX and
124
+ * validation) and the three seams — capture, detect, restore — over ONE
125
+ * hot-read settings reader and ONE per-session state registry (so capture,
126
+ * detect, and the drain can never disagree about what is pinned or what is
127
+ * scheduled). The listeners re-read the namespace value per use, so a settings
128
+ * edit applies immediately; the raw user-layer reader (`readUserSettings`) is
129
+ * exported for callers that must exclude project scope.
130
+ * @param ctx - the plug context.
131
+ * @param config - optional test seams (settings reader, state registry).
132
+ */
133
+ export declare function apply(ctx: Context, config?: PinningPluginConfig): void;
134
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsCG;AAEH,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,qBAAqB,CAAA;AAKlD,OAAO,EAAiB,KAAK,OAAO,EAAE,MAAM,WAAW,CAAA;AACvD,OAAO,EAAuB,KAAK,aAAa,EAAE,MAAM,eAAe,CAAA;AACvE,OAAO,EAGL,KAAK,yBAAyB,EAC/B,MAAM,eAAe,CAAA;AAEtB,OAAO,EACL,kBAA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D,IAAI,CAAC,SAAS,EAAE,MAAM,GAAG,YAAY,GAAG,SAAS,CAAA;IACjD,yEAAyE;IACzE,MAAM,CAAC,SAAS,EAAE,MAAM,GAAG,IAAI,CAAA;IAC/B,4CAA4C;IAC5C,GAAG,IAAI,MAAM,EAAE,CAAA;CAChB;AAED;;;;;;GAMG;AACH,wBAAgB,0BAA0B,CACxC,YAAY,EAAE,MAAM,yBAAyB,GAC5C,oBAAoB,CAuBtB;AAED,mFAAmF;AACnF,MAAM,WAAW,mBAAmB;IAClC,6EAA6E;IAC7E,QAAQ,CAAC,YAAY,CAAC,EAAE,MAAM,yBAAyB,CAAA;IACvD,gGAAgG;IAChG,QAAQ,CAAC,MAAM,CAAC,EAAE,oBAAoB,CAAA;CACvC;AAED;;;;;;GAMG;AACH,wBAAgB,eAAe,CAC7B,GAAG,EAAE,OAAO,EACZ,YAAY,EAAE,MAAM,yBAAyB,EAC7C,MAAM,EAAE,oBAAoB,GAC3B,IAAI,CAsDN;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,KAAK,CAAC,GAAG,EAAE,OAAO,EAAE,MAAM,GAAE,mBAAwB,GAAG,IAAI,CAc1E"}
package/lib/index.js ADDED
@@ -0,0 +1,178 @@
1
+ /**
2
+ * Compaction governed-message pinning (design
3
+ * docs/plans/2026-11-12-compaction-governed-pinning.md).
4
+ *
5
+ * Behavioral-governance messages (turn-rules reminders, post-edit-verify
6
+ * recovery hints) travel as ordinary `user/message` events. Summarization
7
+ * compaction replaces a whole `[startSeq, endSeq]` region with one checkpoint,
8
+ * so those instructions survive only as whatever the summary kept. This plugin
9
+ * captures them VERBATIM in a bounded per-session ring before they can be
10
+ * shadowed, schedules their restoration when a compaction reports them among
11
+ * its `shadowedSeqs`, and drains that schedule back into the session after the
12
+ * checkpoint commits.
13
+ *
14
+ * Three seams, one settings read:
15
+ *
16
+ * - capture — a `{ global: true }` `session/event` observer (`./ring.ts`,
17
+ * {@link registerCapture});
18
+ * - detect — a second `{ global: true }` `session/event` observer that arms /
19
+ * settles schedules from `compaction/summary` and `compaction/end`
20
+ * (`./detect.ts`, {@link registerDetect});
21
+ * - restore — an `agent/pre-step` listener registered `{ prepend: true }` and
22
+ * delegate-first (`./restore.ts`, {@link registerRestore}).
23
+ *
24
+ * Nothing is appended from inside the firehose — mutation there throws
25
+ * `reenter` (harness core/session/src/index.ts `publicationEntry`) — so the two
26
+ * observers are purely observational and every append happens in the drain.
27
+ *
28
+ * Capture read shape (design §Current behavior, the r1 BLOCKER fix):
29
+ * `'user/message'` events carry the `UserMessage` object ITSELF as `data`
30
+ * (harness core/session/src/types.ts), so the listener reads
31
+ * `event.data.source` / `event.data.content` — never `event.data.message.*`.
32
+ *
33
+ * Plain plugin (not a Service, non-isolate): `apply(ctx)` registers the settings
34
+ * namespace for /config UX and mounts the three seams. Every fault is
35
+ * contained — a throw across the firehose or waterfall boundary is never
36
+ * allowed (§Failure semantics).
37
+ *
38
+ * @module @dsh-cc/compaction-pinning
39
+ */
40
+ import { registerDetect } from "./detect.js";
41
+ import { bumpPinningHealth } from "./health.js";
42
+ import { registerRestore } from "./restore.js";
43
+ import { createPinRing } from "./ring.js";
44
+ import { createScheduleStore } from "./schedule.js";
45
+ import { DEFAULT_COMPACTION_PINNING_SETTINGS, registerSettings, } from "./settings.js";
46
+ export { SETTINGS_NAMESPACE, SettingsSchema, DEFAULT_COMPACTION_PINNING_SETTINGS, DEFAULT_ENABLED, DEFAULT_PINNED_SOURCE_KINDS, DEFAULT_MAX_PINNED, DEFAULT_MAX_PINNED_BYTES, MIN_PINNED, MAX_PINNED, MIN_PINNED_BYTES, MAX_PINNED_BYTES, MAX_SOURCE_KIND_CHARS, registerSettings, readUserSettings, } from "./settings.js";
47
+ export { createPinRing, estimateMessageBytes, } from "./ring.js";
48
+ export { createScheduleStore, raiseTurn, RULE_B_TURNS, SCHEDULE_GC_TURNS, } from "./schedule.js";
49
+ export { registerDetect } from "./detect.js";
50
+ export { registerRestore } from "./restore.js";
51
+ export { getPinningHealth, bumpPinningHealth, resetPinningHealth, } from "./health.js";
52
+ /** Cordis plugin id. */
53
+ export const name = 'compaction-pinning';
54
+ /**
55
+ * Create the state registry. Caps come from the settings reader at ring
56
+ * creation; the capture listener re-applies them per event so a mid-session
57
+ * settings edit shrinks (or grows) the ring immediately.
58
+ * @param readSettings - live settings reader (hot-read per use).
59
+ * @returns the registry.
60
+ */
61
+ export function createPinningStateRegistry(readSettings) {
62
+ const states = new Map();
63
+ return {
64
+ stateOf: (sessionId) => {
65
+ let state = states.get(sessionId);
66
+ if (state === undefined) {
67
+ const settings = readSettings();
68
+ state = {
69
+ ring: createPinRing({ maxPinned: settings.maxPinned, maxPinnedBytes: settings.maxPinnedBytes }),
70
+ schedules: createScheduleStore(),
71
+ turn: 0,
72
+ lastSummary: undefined,
73
+ };
74
+ states.set(sessionId, state);
75
+ }
76
+ return state;
77
+ },
78
+ peek: (sessionId) => states.get(sessionId),
79
+ delete: (sessionId) => {
80
+ states.delete(sessionId);
81
+ },
82
+ ids: () => [...states.keys()],
83
+ };
84
+ }
85
+ /**
86
+ * Register the capture listener (design §Capture) and the Session-disposal
87
+ * cleanup. Observe-only: no append, no waterfall, no mutation.
88
+ * @param ctx - the plug context.
89
+ * @param readSettings - live settings reader.
90
+ * @param states - the per-session state registry.
91
+ */
92
+ export function registerCapture(ctx, readSettings, states) {
93
+ const debug = (message) => {
94
+ try {
95
+ ctx.logger.debug(`compaction-pinning: ${message}`);
96
+ }
97
+ catch {
98
+ // Never throw into a hot path.
99
+ }
100
+ };
101
+ // The firehose observer ({ global: true } so every session's publications are
102
+ // seen — session events dispatch to the session's captured emit scope).
103
+ ctx.on('session/event', (session, event) => {
104
+ try {
105
+ // Direct literal comparison (not the widened `String(event.type)` idiom
106
+ // used for plugin-declared event types): `user/message` is a core map
107
+ // member, so this narrows `event.data` to `UserMessage`.
108
+ if (event.type !== 'user/message')
109
+ return;
110
+ const settings = readSettings();
111
+ if (!settings.enabled)
112
+ return;
113
+ // Capture read shape: the UserMessage IS `event.data` (design §Current
114
+ // behavior). Reading `event.data.message.*` here was the r1 shape bug.
115
+ const kind = event.data.source?.kind;
116
+ if (typeof kind !== 'string' || !settings.pinnedSourceKinds.includes(kind))
117
+ return;
118
+ const sessionId = String(session.header.id);
119
+ const state = states.stateOf(sessionId);
120
+ state.ring.setCaps(settings.maxPinned, settings.maxPinnedBytes);
121
+ // Verbatim: the whole message object goes in by reference (§Capture).
122
+ const stored = state.ring.add({
123
+ seq: Number(event.seq),
124
+ message: event.data,
125
+ ts: event.time,
126
+ });
127
+ if (!stored) {
128
+ bumpPinningHealth('dropped');
129
+ debug(`drop: one ${kind} pin exceeds max-pinned-bytes (${settings.maxPinnedBytes})`);
130
+ return;
131
+ }
132
+ bumpPinningHealth('captured');
133
+ }
134
+ catch (error) {
135
+ // §Failure semantics: drop the entry, debug-log, never cross the boundary.
136
+ bumpPinningHealth('dropped');
137
+ debug(`capture failed: ${error instanceof Error ? error.message : String(error)}`);
138
+ }
139
+ }, { global: true });
140
+ // §Capture TTL honesty: the ring is process memory, so a disposed session
141
+ // leaves nothing behind.
142
+ ctx.on('session/disposed', (session) => {
143
+ try {
144
+ states.delete(String(session.header.id));
145
+ }
146
+ catch {
147
+ // Never throw from cleanup.
148
+ }
149
+ }, { global: true });
150
+ }
151
+ /**
152
+ * Mount the plugin: register the settings namespace (for /config UX and
153
+ * validation) and the three seams — capture, detect, restore — over ONE
154
+ * hot-read settings reader and ONE per-session state registry (so capture,
155
+ * detect, and the drain can never disagree about what is pinned or what is
156
+ * scheduled). The listeners re-read the namespace value per use, so a settings
157
+ * edit applies immediately; the raw user-layer reader (`readUserSettings`) is
158
+ * exported for callers that must exclude project scope.
159
+ * @param ctx - the plug context.
160
+ * @param config - optional test seams (settings reader, state registry).
161
+ */
162
+ export function apply(ctx, config = {}) {
163
+ const namespaceReader = registerSettings(ctx);
164
+ const readSettings = config.readSettings
165
+ ?? (() => {
166
+ try {
167
+ return namespaceReader?.() ?? DEFAULT_COMPACTION_PINNING_SETTINGS;
168
+ }
169
+ catch {
170
+ return DEFAULT_COMPACTION_PINNING_SETTINGS;
171
+ }
172
+ });
173
+ const states = config.states ?? createPinningStateRegistry(readSettings);
174
+ registerCapture(ctx, readSettings, states);
175
+ registerDetect(ctx, readSettings, states);
176
+ registerRestore(ctx, readSettings, states);
177
+ }
178
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsCG;AAIH,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAA;AAC5C,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAA;AAC/C,OAAO,EAAE,eAAe,EAAE,MAAM,cAAc,CAAA;AAC9C,OAAO,EAAE,aAAa,EAAgB,MAAM,WAAW,CAAA;AACvD,OAAO,EAAE,mBAAmB,EAAsB,MAAM,eAAe,CAAA;AACvE,OAAO,EACL,mCAAmC,EACnC,gBAAgB,GAEjB,MAAM,eAAe,CAAA;AAEtB,OAAO,EACL,kBAAkB,EAClB,cAAc,EACd,mCAAmC,EACnC,eAAe,EACf,2BAA2B,EAC3B,kBAAkB,EAClB,wBAAwB,EACxB,UAAU,EACV,UAAU,EACV,gBAAgB,EAChB,gBAAgB,EAChB,qBAAqB,EACrB,gBAAgB,EAChB,gBAAgB,GAEjB,MAAM,eAAe,CAAA;AACtB,OAAO,EACL,aAAa,EACb,oBAAoB,GAIrB,MAAM,WAAW,CAAA;AAClB,OAAO,EACL,mBAAmB,EACnB,SAAS,EACT,YAAY,EACZ,iBAAiB,GAIlB,MAAM,eAAe,CAAA;AACtB,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAA;AAC5C,OAAO,EAAE,eAAe,EAAE,MAAM,cAAc,CAAA;AAC9C,OAAO,EACL,gBAAgB,EAChB,iBAAiB,EACjB,kBAAkB,GAGnB,MAA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,CAAA;IAC1C,cAAc,CAAC,GAAG,EAAE,YAAY,EAAE,MAAM,CAAC,CAAA;IACzC,eAAe,CAAC,GAAG,EAAE,YAAY,EAAE,MAAM,CAAC,CAAA;AAC5C,CAAC"}
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Restore half (design docs/plans/2026-11-12-compaction-governed-pinning.md
3
+ * §Restore + §Restore timing): drain eligible schedules back into the session.
4
+ *
5
+ * The drain runs from an `agent/pre-step` listener registered
6
+ * `{ prepend: true }` and implemented **delegate-first** (`await next()` BEFORE
7
+ * any work). That ordering is the whole timing contract: prepend makes this
8
+ * listener the outermost wrapper, so `await next()` runs every inner listener —
9
+ * including the compaction engine's own pressure trigger, which appends
10
+ * summary → checkpoint → end inside the same pre-step — and only then does the
11
+ * drain append. Schedules created by inner listeners therefore restore before
12
+ * the loop derives the request: the harness pressure path has **no** model-
13
+ * visible exposure (design §Restore timing).
14
+ *
15
+ * `await next()` deliberately sits OUTSIDE the containment block: if the
16
+ * downstream chain already threw, the waterfall is failing and re-invoking it
17
+ * would run every inner hook twice (progress-rebuild's documented shape). Only
18
+ * this listener's own post-processing is fail-soft.
19
+ *
20
+ * Appends: `session.append('user/message', message, { surfaceOp: 'append' })`
21
+ * with the verbatim stored object, one append per pin, ascending by ORIGINAL
22
+ * seq (§Restore: each restore is its own append so source boundaries survive;
23
+ * never batched into one message). A restored message re-enters the capture
24
+ * ring under its new seq with the same kind, which is what makes re-shadowing
25
+ * self-healing instead of a loop.
26
+ *
27
+ * The session is reached through the pre-step payload's `agent.session` — the
28
+ * same seam progress-rebuild / mcp-ready-notice use; the payload is typed
29
+ * structurally so this package needs no `@deepseek-ai/dsh-agent` dependency.
30
+ *
31
+ * @module
32
+ */
33
+ import type { Context } from '@deepseek-ai/cordis';
34
+ import type { PinningStateRegistry } from './index.ts';
35
+ import type { CompactionPinningSettings } from './settings.ts';
36
+ /**
37
+ * Register the restore drain (design §Restore). Delegate-first, `{ prepend: true }`.
38
+ * @param ctx - the plug context.
39
+ * @param readSettings - live settings reader (hot-read).
40
+ * @param states - the per-session state registry (shared with capture/detect).
41
+ */
42
+ export declare function registerRestore(ctx: Context, readSettings: () => CompactionPinningSettings, states: PinningStateRegistry): void;
43
+ //# sourceMappingURL=restore.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"restore.d.ts","sourceRoot":"","sources":["../src/restore.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AAEH,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,qBAAqB,CAAA;AAIlD,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,YAAY,CAAA;AAEtD,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,eAAe,CAAA;AAwE9D;;;;;GAKG;AACH,wBAAgB,eAAe,CAC7B,GAAG,EAAE,OAAO,EACZ,YAAY,EAAE,MAAM,yBAAyB,EAC7C,MAAM,EAAE,oBAAoB,GAC3B,IAAI,CAcN"}
package/lib/restore.js ADDED
@@ -0,0 +1,121 @@
1
+ /**
2
+ * Restore half (design docs/plans/2026-11-12-compaction-governed-pinning.md
3
+ * §Restore + §Restore timing): drain eligible schedules back into the session.
4
+ *
5
+ * The drain runs from an `agent/pre-step` listener registered
6
+ * `{ prepend: true }` and implemented **delegate-first** (`await next()` BEFORE
7
+ * any work). That ordering is the whole timing contract: prepend makes this
8
+ * listener the outermost wrapper, so `await next()` runs every inner listener —
9
+ * including the compaction engine's own pressure trigger, which appends
10
+ * summary → checkpoint → end inside the same pre-step — and only then does the
11
+ * drain append. Schedules created by inner listeners therefore restore before
12
+ * the loop derives the request: the harness pressure path has **no** model-
13
+ * visible exposure (design §Restore timing).
14
+ *
15
+ * `await next()` deliberately sits OUTSIDE the containment block: if the
16
+ * downstream chain already threw, the waterfall is failing and re-invoking it
17
+ * would run every inner hook twice (progress-rebuild's documented shape). Only
18
+ * this listener's own post-processing is fail-soft.
19
+ *
20
+ * Appends: `session.append('user/message', message, { surfaceOp: 'append' })`
21
+ * with the verbatim stored object, one append per pin, ascending by ORIGINAL
22
+ * seq (§Restore: each restore is its own append so source boundaries survive;
23
+ * never batched into one message). A restored message re-enters the capture
24
+ * ring under its new seq with the same kind, which is what makes re-shadowing
25
+ * self-healing instead of a loop.
26
+ *
27
+ * The session is reached through the pre-step payload's `agent.session` — the
28
+ * same seam progress-rebuild / mcp-ready-notice use; the payload is typed
29
+ * structurally so this package needs no `@deepseek-ai/dsh-agent` dependency.
30
+ *
31
+ * @module
32
+ */
33
+ import { bumpPinningHealth } from "./health.js";
34
+ import { raiseTurn } from "./schedule.js";
35
+ /** Debug notice (fail-soft). */
36
+ function debug(ctx, message) {
37
+ try {
38
+ ctx.logger.debug(`compaction-pinning: ${message}`);
39
+ }
40
+ catch {
41
+ // Never throw into a hot path.
42
+ }
43
+ }
44
+ /**
45
+ * Drain every eligible schedule for one session: collect the items ascending by
46
+ * original seq (deduplicated — one live copy per pin), drop the schedules
47
+ * BEFORE appending so a failing append can never re-drain, then append one
48
+ * message at a time.
49
+ * @param ctx - the plug context (logging).
50
+ * @param readSettings - live settings reader.
51
+ * @param states - the per-session state registry.
52
+ * @param payload - the pre-step payload.
53
+ */
54
+ function drain(ctx, readSettings, states, payload) {
55
+ if (!readSettings().enabled)
56
+ return;
57
+ const session = payload.agent?.session;
58
+ if (session === undefined)
59
+ return;
60
+ const state = states.peek(String(session.header.id));
61
+ if (state === undefined)
62
+ return;
63
+ const turn = raiseTurn(state, payload.turn);
64
+ // Bounded memory: schedules that aged past the rule-(b) window without ever
65
+ // becoming eligible are dead (model `Dead`), never a growing backlog.
66
+ state.schedules.gcDead(turn);
67
+ const eligible = state.schedules.eligible(turn);
68
+ if (eligible.length === 0)
69
+ return;
70
+ const restored = new Set();
71
+ const queue = [];
72
+ for (const schedule of eligible) {
73
+ state.schedules.drop(schedule.compactionId);
74
+ for (const item of schedule.items) {
75
+ if (restored.has(item.seq))
76
+ continue;
77
+ restored.add(item.seq);
78
+ queue.push(item);
79
+ }
80
+ }
81
+ queue.sort((left, right) => left.seq - right.seq);
82
+ for (const item of queue) {
83
+ try {
84
+ // Verbatim payload, surface intent REQUIRED (`surfaceOp: 'append'` is the
85
+ // only legal form for a plain user/message append —
86
+ // core/session/src/index.ts + surface.ts in the pinned harness copy).
87
+ session.append('user/message', item.message, { surfaceOp: 'append' });
88
+ bumpPinningHealth('restored');
89
+ }
90
+ catch (error) {
91
+ // §Failure semantics: drop the entry, count it, keep draining — a
92
+ // disposed session must never throw across the waterfall boundary.
93
+ bumpPinningHealth('dropped');
94
+ debug(ctx, `restore of seq ${item.seq} dropped: ${error instanceof Error ? error.message : String(error)}`);
95
+ }
96
+ }
97
+ }
98
+ /**
99
+ * Register the restore drain (design §Restore). Delegate-first, `{ prepend: true }`.
100
+ * @param ctx - the plug context.
101
+ * @param readSettings - live settings reader (hot-read).
102
+ * @param states - the per-session state registry (shared with capture/detect).
103
+ */
104
+ export function registerRestore(ctx, readSettings, states) {
105
+ ctx.on('agent/pre-step', async (payload, next) => {
106
+ // Delegate FIRST and outside the try: the whole waterfall (compaction
107
+ // engine included) runs here, so schedules it creates are drainable below.
108
+ const decision = await next();
109
+ try {
110
+ // A rejected step derives no request; leave the schedules pending so the
111
+ // next admitted step restores them (nothing is lost, nothing is wasted).
112
+ if (decision.kind === 'enter')
113
+ drain(ctx, readSettings, states, payload);
114
+ }
115
+ catch (error) {
116
+ debug(ctx, `drain failed: ${error instanceof Error ? error.message : String(error)}`);
117
+ }
118
+ return decision;
119
+ }, { prepend: true });
120
+ }
121
+ //# sourceMappingURL=restore.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"restore.js","sourceRoot":"","sources":["../src/restore.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AAKH,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAA;AAE/C,OAAO,EAAE,SAAS,EAAoB,MAAM,eAAe,CAAA;AAU3D,gCAA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G,EAAE,YAAY,EAAE,MAAM,EAAE,OAAO,CAAC,CAAA;QAC1E,CAAC;QAAC,OAAO,KAAc,EAAE,CAAC;YACxB,KAAK,CAAC,GAAG,EAAE,iBAAiB,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,CAAA;QACvF,CAAC;QACD,OAAO,QAAQ,CAAA;IACjB,CAAC,EAAE,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC,CAAA;AACvB,CAAC"}
package/lib/ring.d.ts ADDED
@@ -0,0 +1,87 @@
1
+ /**
2
+ * Per-session pinned-message ring (design
3
+ * docs/plans/2026-11-12-compaction-governed-pinning.md §Capture).
4
+ *
5
+ * Every entry stores the WHOLE `user/message` payload **by reference** — the
6
+ * captured object is the exact object the session published, never a clone and
7
+ * never a destructured projection. That is load-bearing beyond capture: the
8
+ * restore half re-appends the stored object verbatim, so structure the capture
9
+ * never removed cannot be lost on the way back (§Capture, r1 MAJOR #10).
10
+ *
11
+ * Caps are FIFO: adding an entry that pushes the ring past `maxPinned` entries
12
+ * or past `maxPinnedBytes` evicts oldest-first until both hold. Evictions bump
13
+ * the process-wide `evicted` health counter.
14
+ *
15
+ * BYTE ESTIMATOR: `JSON.stringify(message).length` — a cheap upper-ish bound on
16
+ * the UTF-16 code units the message occupies, deliberately not a token count
17
+ * and not `Buffer.byteLength` (UTF-8) so the number stays allocation-free and
18
+ * provider-agnostic. It over-counts multi-byte text slightly (code units ≤
19
+ * bytes for the ASCII-heavy governance messages this ring holds) and it counts
20
+ * JSON scaffolding, which is exactly the conservative direction a cap wants.
21
+ * A message that cannot be stringified (cyclic, BigInt) falls back to the sum
22
+ * of its text-block lengths.
23
+ *
24
+ * @module
25
+ */
26
+ import type { UserMessage } from '@deepseek-ai/dsh-llm';
27
+ /** One pinned message: the capture event's coordinates plus the payload itself. */
28
+ export interface PinRingEntry {
29
+ /** Session log seq of the captured `user/message` event (the restore key). */
30
+ readonly seq: number;
31
+ /** The whole `UserMessage` event payload, by reference (§Capture verbatim rule). */
32
+ readonly message: UserMessage;
33
+ /** Unix epoch ms of the capturing event. */
34
+ readonly ts: number;
35
+ }
36
+ /** Ring bounds; supplied from the hot-read settings at capture time. */
37
+ export interface PinRingOptions {
38
+ /** Maximum entries retained (oldest evicted first). */
39
+ maxPinned: number;
40
+ /** Maximum estimated bytes retained (oldest evicted first). */
41
+ maxPinnedBytes: number;
42
+ }
43
+ /** The per-session ring face the capture and restore halves share. */
44
+ export interface PinRing {
45
+ /**
46
+ * Store one entry verbatim, then FIFO-evict until both caps hold.
47
+ * @param entry - the captured entry (the message is kept by reference).
48
+ * @returns `true` when stored; `false` when refused because this single
49
+ * message alone exceeds `maxPinnedBytes` (the ring never holds an
50
+ * over-cap entry — the caller records the drop).
51
+ */
52
+ add(entry: PinRingEntry): boolean;
53
+ /** Whether a captured seq is currently pinned. */
54
+ has(seq: number): boolean;
55
+ /** Captured seqs, oldest first. */
56
+ keys(): number[];
57
+ /** The entry for one captured seq, or `undefined`. */
58
+ get(seq: number): PinRingEntry | undefined;
59
+ /** Every entry, oldest first (a snapshot array; the entries are the live objects). */
60
+ entries(): PinRingEntry[];
61
+ /** Drop every entry. */
62
+ clear(): void;
63
+ /** Live entry count. */
64
+ readonly size: number;
65
+ /** Live estimated bytes. */
66
+ readonly bytes: number;
67
+ /**
68
+ * Re-apply hot-read caps (settings can change mid-session), evicting
69
+ * oldest-first until the ring fits.
70
+ * @returns the number of evictions performed.
71
+ */
72
+ setCaps(maxPinned: number, maxPinnedBytes: number): number;
73
+ }
74
+ /**
75
+ * Estimated bytes of one message (see the module doc for the estimator and its
76
+ * deliberate conservatism). Never throws.
77
+ * @param message - the captured message.
78
+ * @returns estimated size in UTF-16 code units of the JSON rendering.
79
+ */
80
+ export declare function estimateMessageBytes(message: UserMessage): number;
81
+ /**
82
+ * Create one session's ring.
83
+ * @param options - initial caps (hot-read from settings at creation).
84
+ * @returns the ring face.
85
+ */
86
+ export declare function createPinRing(options: PinRingOptions): PinRing;
87
+ //# sourceMappingURL=ring.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ring.d.ts","sourceRoot":"","sources":["../src/ring.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AAEH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAA;AAGvD,mFAAmF;AACnF,MAAM,WAAW,YAAY;IAC3B,8EAA8E;IAC9E,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAA;IACpB,oFAAoF;IACpF,QAAQ,CAAC,OAAO,EAAE,WAAW,CAAA;IAC7B,4CAA4C;IAC5C,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAA;CACpB;AAED,wEAAwE;AACxE,MAAM,WAAW,cAAc;IAC7B,uDAAuD;IACvD,SAAS,EAAE,MAAM,CAAA;IACjB,+DAA+D;IAC/D,cAAc,EAAE,MAAM,CAAA;CACvB;AAED,sEAAsE;AACtE,MAAM,WAAW,OAAO;IACtB;;;;;;OAMG;IACH,GAAG,CAAC,KAAK,EAAE,YAAY,GAAG,OAAO,CAAA;IACjC,kDAAkD;IAClD,GAAG,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAA;IACzB,mCAAmC;IACnC,IAAI,IAAI,MAAM,EAAE,CAAA;IAChB,sDAAsD;IACtD,GAAG,CAAC,GAAG,EAAE,MAAM,GAAG,YAAY,GAAG,SAAS,CAAA;IAC1C,sFAAsF;IACtF,OAAO,IAAI,YAAY,EAAE,CAAA;IACzB,wBAAwB;IACxB,KAAK,IAAI,IAAI,CAAA;IACb,wBAAwB;IACxB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;IACrB,4BAA4B;IAC5B,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAA;IACtB;;;;OAIG;IACH,OAAO,CAAC,SAAS,EAAE,MAAM,EAAE,cAAc,EAAE,MAAM,GAAG,M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