@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/ring.js ADDED
@@ -0,0 +1,123 @@
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 { bumpPinningHealth } from "./health.js";
27
+ /** A positive integer cap, or the fallback when the value is unusable. */
28
+ function normalizeCap(value, fallback) {
29
+ if (!Number.isFinite(value) || value < 1)
30
+ return fallback;
31
+ return Math.trunc(value);
32
+ }
33
+ /**
34
+ * Estimated bytes of one message (see the module doc for the estimator and its
35
+ * deliberate conservatism). Never throws.
36
+ * @param message - the captured message.
37
+ * @returns estimated size in UTF-16 code units of the JSON rendering.
38
+ */
39
+ export function estimateMessageBytes(message) {
40
+ try {
41
+ return JSON.stringify(message)?.length ?? 0;
42
+ }
43
+ catch {
44
+ // Unserializable payload: fall back to text-block lengths rather than
45
+ // letting the estimate (and the caller's cap) evaporate.
46
+ const content = message.content;
47
+ if (!Array.isArray(content))
48
+ return 0;
49
+ return content.reduce((total, block) => {
50
+ const text = block?.text;
51
+ return total + (typeof text === 'string' ? text.length : 0);
52
+ }, 0);
53
+ }
54
+ }
55
+ /**
56
+ * Create one session's ring.
57
+ * @param options - initial caps (hot-read from settings at creation).
58
+ * @returns the ring face.
59
+ */
60
+ export function createPinRing(options) {
61
+ let maxPinned = normalizeCap(options.maxPinned, 1);
62
+ let maxPinnedBytes = normalizeCap(options.maxPinnedBytes, 1);
63
+ /** Live entries with their pre-measured size (measured once, at add time). */
64
+ const items = [];
65
+ let bytes = 0;
66
+ /** Drop the oldest entry; `false` when the ring is already empty. */
67
+ const evictOldest = () => {
68
+ const oldest = items.shift();
69
+ if (oldest === undefined)
70
+ return false;
71
+ bytes -= oldest.bytes;
72
+ bumpPinningHealth('evicted');
73
+ return true;
74
+ };
75
+ /** FIFO-evict until both caps hold; returns the eviction count. */
76
+ const fit = () => {
77
+ let evicted = 0;
78
+ while (items.length > maxPinned) {
79
+ if (!evictOldest())
80
+ break;
81
+ evicted += 1;
82
+ }
83
+ while (bytes > maxPinnedBytes) {
84
+ if (!evictOldest())
85
+ break;
86
+ evicted += 1;
87
+ }
88
+ return evicted;
89
+ };
90
+ return {
91
+ add(entry) {
92
+ const entryBytes = estimateMessageBytes(entry.message);
93
+ // A single message larger than the whole byte budget is refused outright:
94
+ // accepting it would leave the ring permanently over its cap.
95
+ if (entryBytes > maxPinnedBytes)
96
+ return false;
97
+ items.push({ entry, bytes: entryBytes });
98
+ bytes += entryBytes;
99
+ fit();
100
+ return true;
101
+ },
102
+ has: (seq) => items.some((item) => item.entry.seq === seq),
103
+ keys: () => items.map((item) => item.entry.seq),
104
+ get: (seq) => items.find((item) => item.entry.seq === seq)?.entry,
105
+ entries: () => items.map((item) => item.entry),
106
+ clear: () => {
107
+ items.length = 0;
108
+ bytes = 0;
109
+ },
110
+ get size() {
111
+ return items.length;
112
+ },
113
+ get bytes() {
114
+ return bytes;
115
+ },
116
+ setCaps(nextMaxPinned, nextMaxPinnedBytes) {
117
+ maxPinned = normalizeCap(nextMaxPinned, maxPinned);
118
+ maxPinnedBytes = normalizeCap(nextMaxPinnedBytes, maxPinnedBytes);
119
+ return fit();
120
+ },
121
+ };
122
+ }
123
+ //# sourceMappingURL=ring.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ring.js","sourceRoot":"","sources":["../src/ring.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AAGH,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAA;AAoD/C,0EAA0E;AAC1E,SAAS,YAAY,CAAC,KAAa,EAAE,QAAgB;IACnD,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAI,KAAK,GAAG,CAAC;QAAE,OAAO,QAAQ,CAAA;IACzD,OAAO,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAA;AAC1B,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,oBAAoB,CAAC,OAAoB;IACvD,IAAI,CAAC;QACH,OAAO,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,EAAE,MAAM,IAAI,CAAC,CAAA;IAC7C,CAAC;IAAC,MAAM,CAAC;QACP,sEAAsE;QACtE,yDAAyD;QACzD,MAAM,OAAO,GAAI,OAAiC,CAAC,OAAO,CAAA;QAC1D,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC;YAAE,OAAO,CAAC,CAAA;QACrC,OAAO,OAAO,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,KAAK,EAAE,EAAE;YACrC,MAAM,IAAI,GAAI,KAAmC,EAAE,IAAI,CAAA;YACvD,OAAO,KAAK,GAAG,CAAC,OAAO,IAAI,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAI,CA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128 @@
1
+ /**
2
+ * Restore schedules — the detect half's per-session bookkeeping (design
3
+ * docs/plans/2026-11-12-compaction-governed-pinning.md §Detect, semantics
4
+ * pinned by the verified model `specs/tla/compaction-pin-restore`).
5
+ *
6
+ * One schedule exists per `compactionId` whose summary reported at least one
7
+ * restorable pin (`shadowedSeqs ∩ ring`). The summary is **provisional**
8
+ * evidence: the engine appends `compaction/summary` BEFORE the checkpoint
9
+ * commit (`packages/compaction/compaction-basic/src/region.ts`
10
+ * `commitCompactionBody` in the pinned harness copy), so a logged summary with
11
+ * `shadowedSeqs` can exist while nothing was actually shadowed. Two outcomes
12
+ * settle a schedule:
13
+ *
14
+ * - **rule (a)** — a successful `compaction/end` arrived for that id
15
+ * ({@link ScheduleStore.succeed}): the checkpoint committed (the engine only
16
+ * reaches the end append after `commitCompactionBody` returned — the same
17
+ * file's `closing = true` ordering), so the pins really are gone from the
18
+ * surface and may be re-appended in the very same drain;
19
+ * - **rule (b)** — the conservative rule: no end of any kind has been seen,
20
+ * the schedule has existed for ≥ {@link RULE_B_TURNS} turn, AND the
21
+ * compaction's checkpoint commit was actually WITNESSED
22
+ * ({@link ScheduleStore.commit}, set by the replacement `user/message` that
23
+ * cites the summary's seq). The commit gate is load-bearing, not decoration:
24
+ * the model's `RequireCheckpoint` constant is the difference between the
25
+ * verified convention and the red `strict-blind-rule-b` probe — without it
26
+ * the F3 double failure (checkpoint append fails AND the error-end append
27
+ * fails) leaves a summary-only phantom that rule (b) would "restore" over a
28
+ * live original (`NoPhantom` / `AtMostOneLivePerPin` violations). See
29
+ * `specs/tla/compaction-pin-restore/design.md` R4 and the model's
30
+ * "Notes for implementers".
31
+ * - **cancelled** — an end carrying `error` deletes the schedule outright
32
+ * ({@link ScheduleStore.cancel}): the belt, §Detect.
33
+ *
34
+ * Schedules that never become eligible age out after
35
+ * {@link SCHEDULE_GC_TURNS} turns ({@link ScheduleStore.gcDead}), mirroring the
36
+ * model's `Dead` predicate — a session cannot accumulate stranded schedules
37
+ * from compacted-away failure windows.
38
+ *
39
+ * @module
40
+ */
41
+ import type { UserMessage } from '@deepseek-ai/dsh-llm';
42
+ /**
43
+ * One restorable pin: the shadowed seq and the exact message object captured
44
+ * for it. The message is the object the session published — restore re-appends
45
+ * it verbatim (§Restore), so nothing destructured it on the way here.
46
+ */
47
+ export interface RestoreItem {
48
+ /** Session log seq of the shadowed `user/message` event (the drain order key). */
49
+ readonly seq: number;
50
+ /** The verbatim captured message (§Capture verbatim rule). */
51
+ readonly message: UserMessage;
52
+ }
53
+ /** Turns a schedule must survive before rule (b) may make it eligible. */
54
+ export declare const RULE_B_TURNS = 1;
55
+ /** Turns a non-eligible schedule survives before the drain garbage-collects it. */
56
+ export declare const SCHEDULE_GC_TURNS = 2;
57
+ /** One pending restore schedule, keyed by the compaction that produced it. */
58
+ export interface RestoreSchedule {
59
+ /** The `compactionId` all three lifecycle events share. */
60
+ readonly compactionId: string;
61
+ /** Restorable pins, ascending by original seq. */
62
+ readonly items: readonly RestoreItem[];
63
+ /** Turn-clock value when the summary was observed (rule (b) ageing). */
64
+ readonly createdTurn: number;
65
+ /** Rule (a): a successful `compaction/end` arrived. */
66
+ succeeded: boolean;
67
+ /** The checkpoint replacement citing this compaction's summary was observed. */
68
+ committed: boolean;
69
+ }
70
+ /** Per-session schedule storage: the restore half's whole mutable state. */
71
+ export interface ScheduleStore {
72
+ /** Pending schedules (diagnostics/tests). */
73
+ readonly size: number;
74
+ /**
75
+ * Schedule (or extend) the restores for one compaction. Re-reporting the
76
+ * same id unions the pin sets and keeps the earliest creation turn, so a
77
+ * duplicate summary can never rewind rule-(b) ageing.
78
+ * @param compactionId - the lifecycle id.
79
+ * @param items - restorable pins for this report.
80
+ * @param createdTurn - the turn clock when the summary was observed.
81
+ * @returns the live schedule.
82
+ */
83
+ arm(compactionId: string, items: readonly RestoreItem[], createdTurn: number): RestoreSchedule;
84
+ /** One schedule, without creating it. */
85
+ get(compactionId: string): RestoreSchedule | undefined;
86
+ /** Record a successful end (rule (a)). `false` when nothing was pending. */
87
+ succeed(compactionId: string): boolean;
88
+ /** The belt: drop the schedule for an end that carried `error`. */
89
+ cancel(compactionId: string): boolean;
90
+ /** Record the witnessed checkpoint commit (rule (b)'s gate). */
91
+ commit(compactionId: string): boolean;
92
+ /**
93
+ * Whether one schedule may drain at the given turn: rule (a), or rule (b)
94
+ * (aged at least {@link RULE_B_TURNS} turn AND a witnessed checkpoint).
95
+ */
96
+ isEligible(schedule: RestoreSchedule, turn: number): boolean;
97
+ /** Every eligible schedule, in creation order. */
98
+ eligible(turn: number): RestoreSchedule[];
99
+ /** Every pending schedule, in creation order. */
100
+ pending(): RestoreSchedule[];
101
+ /** Remove one schedule (the drain consumes eligible ones this way). */
102
+ drop(compactionId: string): void;
103
+ /**
104
+ * Drop schedules aged past the rule-(b) window without becoming eligible.
105
+ * @param turn - the current turn-clock value.
106
+ * @returns how many were collected.
107
+ */
108
+ gcDead(turn: number): number;
109
+ /** Drop every schedule (session disposal / tests). */
110
+ clear(): void;
111
+ }
112
+ /**
113
+ * Raise one session's turn clock monotonically (the rule-(b) signal; the
114
+ * caller documents where the value comes from). Structure-typed on purpose: the
115
+ * clock lives on `PinningState` and this module owns no per-session state.
116
+ * @param state - the object carrying the clock.
117
+ * @param turn - a candidate turn value (ignored unless a safe integer).
118
+ * @returns the clock's value after the raise.
119
+ */
120
+ export declare function raiseTurn(state: {
121
+ turn: number;
122
+ }, turn: unknown): number;
123
+ /**
124
+ * Create one session's schedule store.
125
+ * @returns the store (empty).
126
+ */
127
+ export declare function createScheduleStore(): ScheduleStore;
128
+ //# sourceMappingURL=schedule.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"schedule.d.ts","sourceRoot":"","sources":["../src/schedule.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuCG;AAEH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAA;AAEvD;;;;GAIG;AACH,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,MAAM,GAAG,eAAe,EAAE,CAAA;IACzC,iDAAiD;IACjD,OAAO,IAAI,eAAe,EAAE,CAAA;IAC5B,uEAAuE;IACvE,IAAI,CAAC,YAAY,EAAE,MAAM,GAAG,IAAI,CAAA;IAChC;;;;OAIG;IACH,MAAM,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAAA;IAC5B,sDAAsD;IACtD,KAAK,IAAI,IAAI,CAAA;CACd;AAWD;;;;;;;GAOG;AACH,wBAAgB,SAAS,CAAC,KAAK,EAAE;IAAE,IAAI,EAAE,MAAM,CAAA;CAAE,EAAE,IAAI,EAAE,OAAO,GAAG,MAAM,CAGxE;AAED;;;GAGG;AACH,wBAAgB,mBAAmB,IAAI,aAAa,CAqEnD"}
@@ -0,0 +1,141 @@
1
+ /**
2
+ * Restore schedules — the detect half's per-session bookkeeping (design
3
+ * docs/plans/2026-11-12-compaction-governed-pinning.md §Detect, semantics
4
+ * pinned by the verified model `specs/tla/compaction-pin-restore`).
5
+ *
6
+ * One schedule exists per `compactionId` whose summary reported at least one
7
+ * restorable pin (`shadowedSeqs ∩ ring`). The summary is **provisional**
8
+ * evidence: the engine appends `compaction/summary` BEFORE the checkpoint
9
+ * commit (`packages/compaction/compaction-basic/src/region.ts`
10
+ * `commitCompactionBody` in the pinned harness copy), so a logged summary with
11
+ * `shadowedSeqs` can exist while nothing was actually shadowed. Two outcomes
12
+ * settle a schedule:
13
+ *
14
+ * - **rule (a)** — a successful `compaction/end` arrived for that id
15
+ * ({@link ScheduleStore.succeed}): the checkpoint committed (the engine only
16
+ * reaches the end append after `commitCompactionBody` returned — the same
17
+ * file's `closing = true` ordering), so the pins really are gone from the
18
+ * surface and may be re-appended in the very same drain;
19
+ * - **rule (b)** — the conservative rule: no end of any kind has been seen,
20
+ * the schedule has existed for ≥ {@link RULE_B_TURNS} turn, AND the
21
+ * compaction's checkpoint commit was actually WITNESSED
22
+ * ({@link ScheduleStore.commit}, set by the replacement `user/message` that
23
+ * cites the summary's seq). The commit gate is load-bearing, not decoration:
24
+ * the model's `RequireCheckpoint` constant is the difference between the
25
+ * verified convention and the red `strict-blind-rule-b` probe — without it
26
+ * the F3 double failure (checkpoint append fails AND the error-end append
27
+ * fails) leaves a summary-only phantom that rule (b) would "restore" over a
28
+ * live original (`NoPhantom` / `AtMostOneLivePerPin` violations). See
29
+ * `specs/tla/compaction-pin-restore/design.md` R4 and the model's
30
+ * "Notes for implementers".
31
+ * - **cancelled** — an end carrying `error` deletes the schedule outright
32
+ * ({@link ScheduleStore.cancel}): the belt, §Detect.
33
+ *
34
+ * Schedules that never become eligible age out after
35
+ * {@link SCHEDULE_GC_TURNS} turns ({@link ScheduleStore.gcDead}), mirroring the
36
+ * model's `Dead` predicate — a session cannot accumulate stranded schedules
37
+ * from compacted-away failure windows.
38
+ *
39
+ * @module
40
+ */
41
+ /** Turns a schedule must survive before rule (b) may make it eligible. */
42
+ export const RULE_B_TURNS = 1;
43
+ /** Turns a non-eligible schedule survives before the drain garbage-collects it. */
44
+ export const SCHEDULE_GC_TURNS = 2;
45
+ /** Union two item lists by seq, ascending — later reports never duplicate a pin. */
46
+ function mergeItems(previous, incoming) {
47
+ const bySeq = new Map();
48
+ for (const item of [...previous, ...incoming]) {
49
+ if (!bySeq.has(item.seq))
50
+ bySeq.set(item.seq, item);
51
+ }
52
+ return [...bySeq.values()].sort((left, right) => left.seq - right.seq);
53
+ }
54
+ /**
55
+ * Raise one session's turn clock monotonically (the rule-(b) signal; the
56
+ * caller documents where the value comes from). Structure-typed on purpose: the
57
+ * clock lives on `PinningState` and this module owns no per-session state.
58
+ * @param state - the object carrying the clock.
59
+ * @param turn - a candidate turn value (ignored unless a safe integer).
60
+ * @returns the clock's value after the raise.
61
+ */
62
+ export function raiseTurn(state, turn) {
63
+ if (typeof turn === 'number' && Number.isSafeInteger(turn) && turn > state.turn)
64
+ state.turn = turn;
65
+ return state.turn;
66
+ }
67
+ /**
68
+ * Create one session's schedule store.
69
+ * @returns the store (empty).
70
+ */
71
+ export function createScheduleStore() {
72
+ const schedules = new Map();
73
+ const isEligible = (schedule, turn) => schedule.succeeded
74
+ || (turn - schedule.createdTurn >= RULE_B_TURNS && schedule.committed);
75
+ return {
76
+ get size() {
77
+ return schedules.size;
78
+ },
79
+ arm(compactionId, items, createdTurn) {
80
+ const existing = schedules.get(compactionId);
81
+ if (existing !== undefined) {
82
+ const merged = {
83
+ compactionId,
84
+ items: mergeItems(existing.items, items),
85
+ createdTurn: Math.min(existing.createdTurn, createdTurn),
86
+ succeeded: existing.succeeded,
87
+ committed: existing.committed,
88
+ };
89
+ schedules.set(compactionId, merged);
90
+ return merged;
91
+ }
92
+ const schedule = {
93
+ compactionId,
94
+ items: mergeItems([], items),
95
+ createdTurn,
96
+ succeeded: false,
97
+ committed: false,
98
+ };
99
+ schedules.set(compactionId, schedule);
100
+ return schedule;
101
+ },
102
+ get: (compactionId) => schedules.get(compactionId),
103
+ succeed(compactionId) {
104
+ const existing = schedules.get(compactionId);
105
+ if (existing === undefined)
106
+ return false;
107
+ existing.succeeded = true;
108
+ return true;
109
+ },
110
+ cancel: (compactionId) => schedules.delete(compactionId),
111
+ commit(compactionId) {
112
+ const existing = schedules.get(compactionId);
113
+ if (existing === undefined)
114
+ return false;
115
+ existing.committed = true;
116
+ return true;
117
+ },
118
+ isEligible,
119
+ eligible: (turn) => [...schedules.values()].filter((schedule) => isEligible(schedule, turn)),
120
+ pending: () => [...schedules.values()],
121
+ drop: (compactionId) => {
122
+ schedules.delete(compactionId);
123
+ },
124
+ gcDead(turn) {
125
+ let collected = 0;
126
+ for (const schedule of [...schedules.values()]) {
127
+ if (isEligible(schedule, turn))
128
+ continue;
129
+ if (turn - schedule.createdTurn < SCHEDULE_GC_TURNS)
130
+ continue;
131
+ schedules.delete(schedule.compactionId);
132
+ collected += 1;
133
+ }
134
+ return collected;
135
+ },
136
+ clear: () => {
137
+ schedules.clear();
138
+ },
139
+ };
140
+ }
141
+ //# sourceMappingURL=schedule.js.map
@@ -0,0 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CAAC,KAAK,EAAE,CAAA;QACnB,CAAC;KACF,CAAA;AACH,CAAC"}
@@ -0,0 +1,81 @@
1
+ /**
2
+ * Settings for compaction governed-message pinning (design
3
+ * docs/plans/2026-11-12-compaction-governed-pinning.md §Settings), two halves —
4
+ * the same split as post-edit-verify / turn-rules:
5
+ *
6
+ * 1. namespace registration via `@dsh-cc/settings/ns` (schema uses the kebab
7
+ * keys users author in settings.json), for /config UX and validation only;
8
+ * 2. a RAW user-layer read of `<dshHome>/settings.json` that bypasses the
9
+ * merged cascade entirely, re-read per use (a few KB) — free hot reload.
10
+ *
11
+ * FOUR-SURFACE DEFAULT DISCIPLINE (repo hard rule): the schema `.default()`
12
+ * values, {@link DEFAULT_COMPACTION_PINNING_SETTINGS}, the raw reader's
13
+ * fallbacks, and the plugin wiring all derive from the `DEFAULT_*` constants
14
+ * below. Never restate a default as a literal anywhere else.
15
+ *
16
+ * @module
17
+ */
18
+ import type { Context } from '@deepseek-ai/cordis';
19
+ import type { SettingsNamespace } from '@dsh-cc/settings';
20
+ import z from '@deepseek-ai/schemastery';
21
+ /** The settings namespace carrying the pinning flags. */
22
+ export declare const SETTINGS_NAMESPACE: SettingsNamespace;
23
+ /** Resolved settings shape (camelCase internal; config keys are kebab). */
24
+ export interface CompactionPinningSettings {
25
+ /** Capture and restore run; disabling stops both (a ring is never retroactively rebuilt, §Settings). */
26
+ enabled: boolean;
27
+ /** Message-source kinds treated as durable behavioral constraints (§Kind defaults). */
28
+ pinnedSourceKinds: string[];
29
+ /** Ring entry cap (§Settings bounds `MIN_PINNED`..`MAX_PINNED`). */
30
+ maxPinned: number;
31
+ /** Ring byte cap (§Settings bounds `MIN_PINNED_BYTES`..`MAX_PINNED_BYTES`). */
32
+ maxPinnedBytes: number;
33
+ }
34
+ /** Default: capture (and, once the restore half lands, restore) run. */
35
+ export declare const DEFAULT_ENABLED = true;
36
+ /**
37
+ * Default pinned kinds (§Kind defaults): the durable behavioral-constraint
38
+ * producers — turn-rules reminders and post-edit-verify recovery hints. Both
39
+ * already exist as `MessageSourceMap` producers; this package introduces no
40
+ * source kind of its own.
41
+ */
42
+ export declare const DEFAULT_PINNED_SOURCE_KINDS: readonly string[];
43
+ /** Default ring entry cap (§Settings bounds 1..64). */
44
+ export declare const DEFAULT_MAX_PINNED = 16;
45
+ /** Default ring byte cap (§Settings bounds 1024..262144). */
46
+ export declare const DEFAULT_MAX_PINNED_BYTES = 16384;
47
+ /** Lower bound of `max-pinned`. */
48
+ export declare const MIN_PINNED = 1;
49
+ /** Upper bound of `max-pinned`. */
50
+ export declare const MAX_PINNED = 64;
51
+ /** Lower bound of `max-pinned-bytes`. */
52
+ export declare const MIN_PINNED_BYTES = 1024;
53
+ /** Upper bound of `max-pinned-bytes`. */
54
+ export declare const MAX_PINNED_BYTES = 262144;
55
+ /** Per-kind length bound of `pinned-source-kinds` entries. */
56
+ export declare const MAX_SOURCE_KIND_CHARS = 64;
57
+ /**
58
+ * Namespace schema. Wrapped in the z.const(undefined) union (post-edit-verify
59
+ * convention) so a genuinely absent namespace value stays absent instead of
60
+ * materializing defaults into the cascade.
61
+ */
62
+ export declare const SettingsSchema: z<Record<string, unknown>>;
63
+ /**
64
+ * Promoted defaults, used when the user file is absent or malformed. Every
65
+ * value is derived from the `DEFAULT_*` constants the schema above also uses.
66
+ */
67
+ export declare const DEFAULT_COMPACTION_PINNING_SETTINGS: CompactionPinningSettings;
68
+ /**
69
+ * Register the settings namespace (for /config UX and validation only — the
70
+ * listeners read the raw user file). Returns the live reader, or `undefined`
71
+ * when the host has no settings provider.
72
+ */
73
+ export declare function registerSettings(ctx: Context): (() => CompactionPinningSettings) | undefined;
74
+ /**
75
+ * Read the settings DIRECTLY from `<dshHome>/settings.json`, bypassing the
76
+ * merged cascade (user-layer only, §Settings). Fail-soft: absent file, parse
77
+ * error, or a malformed section yields the documented defaults. Project scope
78
+ * is never read — invisible, not refused.
79
+ */
80
+ export declare function readUserSettings(dshHome: string): Promise<CompactionPinningSettings>;
81
+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,mCAAmC,EAAE,yBAKjD,CAAA;AAkCD;;;;GAIG;AACH,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,OAAO,GAAG,CAAC,MAAM,yBAAyB,CAAC,GAAG,SAAS,CAmB5F;AAED;;;;;GAKG;AACH,wBAAsB,gBAAgB,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,yBAAyB,CAAC,CAqB1F"}
@@ -0,0 +1,158 @@
1
+ /**
2
+ * Settings for compaction governed-message pinning (design
3
+ * docs/plans/2026-11-12-compaction-governed-pinning.md §Settings), two halves —
4
+ * the same split as post-edit-verify / turn-rules:
5
+ *
6
+ * 1. namespace registration via `@dsh-cc/settings/ns` (schema uses the kebab
7
+ * keys users author in settings.json), for /config UX and validation only;
8
+ * 2. a RAW user-layer read of `<dshHome>/settings.json` that bypasses the
9
+ * merged cascade entirely, re-read per use (a few KB) — free hot reload.
10
+ *
11
+ * FOUR-SURFACE DEFAULT DISCIPLINE (repo hard rule): the schema `.default()`
12
+ * values, {@link DEFAULT_COMPACTION_PINNING_SETTINGS}, the raw reader's
13
+ * fallbacks, and the plugin wiring all derive from the `DEFAULT_*` constants
14
+ * below. Never restate a default as a literal anywhere else.
15
+ *
16
+ * @module
17
+ */
18
+ import { readFile } from 'node:fs/promises';
19
+ import { join } from 'node:path';
20
+ import z from '@deepseek-ai/schemastery';
21
+ import { registerNamespaceSafe } from '@dsh-cc/settings/ns';
22
+ /** The settings namespace carrying the pinning flags. */
23
+ export const SETTINGS_NAMESPACE = 'cc-compaction-pinning';
24
+ // ---------------------------------------------------------------------------
25
+ // Defaults + bounds: the single source every surface (schema defaults, the
26
+ // resolved-defaults object, the raw reader, and the plugin wiring) reads.
27
+ // ---------------------------------------------------------------------------
28
+ /** Default: capture (and, once the restore half lands, restore) run. */
29
+ export const DEFAULT_ENABLED = true;
30
+ /**
31
+ * Default pinned kinds (§Kind defaults): the durable behavioral-constraint
32
+ * producers — turn-rules reminders and post-edit-verify recovery hints. Both
33
+ * already exist as `MessageSourceMap` producers; this package introduces no
34
+ * source kind of its own.
35
+ */
36
+ export const DEFAULT_PINNED_SOURCE_KINDS = ['turn-rules', 'edit-recovery-hint'];
37
+ /** Default ring entry cap (§Settings bounds 1..64). */
38
+ export const DEFAULT_MAX_PINNED = 16;
39
+ /** Default ring byte cap (§Settings bounds 1024..262144). */
40
+ export const DEFAULT_MAX_PINNED_BYTES = 16_384;
41
+ /** Lower bound of `max-pinned`. */
42
+ export const MIN_PINNED = 1;
43
+ /** Upper bound of `max-pinned`. */
44
+ export const MAX_PINNED = 64;
45
+ /** Lower bound of `max-pinned-bytes`. */
46
+ export const MIN_PINNED_BYTES = 1024;
47
+ /** Upper bound of `max-pinned-bytes`. */
48
+ export const MAX_PINNED_BYTES = 262_144;
49
+ /** Per-kind length bound of `pinned-source-kinds` entries. */
50
+ export const MAX_SOURCE_KIND_CHARS = 64;
51
+ const opt = (t) => z.union([t, z.const(undefined)]);
52
+ /** Inner object shape (kebab keys). Absence resolves to defaults via schemastery. */
53
+ const SettingsObject = z.object({
54
+ enabled: z.boolean().default(DEFAULT_ENABLED),
55
+ 'pinned-source-kinds': z.array(z.string()).default([...DEFAULT_PINNED_SOURCE_KINDS]),
56
+ 'max-pinned': z.number().default(DEFAULT_MAX_PINNED).min(MIN_PINNED).max(MAX_PINNED).step(1),
57
+ 'max-pinned-bytes': z.number().default(DEFAULT_MAX_PINNED_BYTES).min(MIN_PINNED_BYTES).max(MAX_PINNED_BYTES).step(1),
58
+ });
59
+ /**
60
+ * Namespace schema. Wrapped in the z.const(undefined) union (post-edit-verify
61
+ * convention) so a genuinely absent namespace value stays absent instead of
62
+ * materializing defaults into the cascade.
63
+ */
64
+ export const SettingsSchema = opt(SettingsObject);
65
+ /**
66
+ * Promoted defaults, used when the user file is absent or malformed. Every
67
+ * value is derived from the `DEFAULT_*` constants the schema above also uses.
68
+ */
69
+ export const DEFAULT_COMPACTION_PINNING_SETTINGS = {
70
+ enabled: DEFAULT_ENABLED,
71
+ pinnedSourceKinds: [...DEFAULT_PINNED_SOURCE_KINDS],
72
+ maxPinned: DEFAULT_MAX_PINNED,
73
+ maxPinnedBytes: DEFAULT_MAX_PINNED_BYTES,
74
+ };
75
+ /**
76
+ * Read the configured kinds defensively. Schemastery has no string-length
77
+ * constraint, so the per-kind 64-char bound (§Settings) is applied here: invalid
78
+ * or over-long entries are dropped. A configured list that yields no valid kind
79
+ * falls back to the documented default pair — turning capture off is
80
+ * `enabled: false`, not an empty list.
81
+ */
82
+ function sourceKindsOf(value) {
83
+ const kinds = (Array.isArray(value) ? value : []).filter((kind) => typeof kind === 'string' && kind.length > 0 && kind.length <= MAX_SOURCE_KIND_CHARS);
84
+ return kinds.length > 0 ? kinds : [...DEFAULT_PINNED_SOURCE_KINDS];
85
+ }
86
+ /**
87
+ * Map the kebab schema shape onto the camelCase internal shape. Out-of-range
88
+ * numerics make schemastery throw, and every caller below contains that throw
89
+ * and returns {@link DEFAULT_COMPACTION_PINNING_SETTINGS} (fail soft, never a
90
+ * hot-path throw) — the diagnostic for a bad value is /config validation in the
91
+ * namespace path.
92
+ */
93
+ function resolveSettings(section) {
94
+ const resolved = SettingsObject(section);
95
+ return {
96
+ enabled: resolved.enabled,
97
+ pinnedSourceKinds: sourceKindsOf(resolved['pinned-source-kinds']),
98
+ maxPinned: resolved['max-pinned'],
99
+ maxPinnedBytes: resolved['max-pinned-bytes'],
100
+ };
101
+ }
102
+ /**
103
+ * Register the settings namespace (for /config UX and validation only — the
104
+ * listeners read the raw user file). Returns the live reader, or `undefined`
105
+ * when the host has no settings provider.
106
+ */
107
+ export function registerSettings(ctx) {
108
+ const settings = ctx.get('settings');
109
+ if (settings === undefined)
110
+ return undefined;
111
+ const read = registerNamespaceSafe(ctx, SETTINGS_NAMESPACE, SettingsSchema);
112
+ return () => {
113
+ try {
114
+ const value = read();
115
+ return value === undefined
116
+ ? DEFAULT_COMPACTION_PINNING_SETTINGS
117
+ : resolveSettings(value);
118
+ }
119
+ catch {
120
+ // Malformed live scope → documented defaults; never throw into a hot path.
121
+ return DEFAULT_COMPACTION_PINNING_SETTINGS;
122
+ }
123
+ };
124
+ }
125
+ /**
126
+ * Read the settings DIRECTLY from `<dshHome>/settings.json`, bypassing the
127
+ * merged cascade (user-layer only, §Settings). Fail-soft: absent file, parse
128
+ * error, or a malformed section yields the documented defaults. Project scope
129
+ * is never read — invisible, not refused.
130
+ */
131
+ export async function readUserSettings(dshHome) {
132
+ let text;
133
+ try {
134
+ text = await readFile(join(dshHome, 'settings.json'), 'utf8');
135
+ }
136
+ catch {
137
+ return DEFAULT_COMPACTION_PINNING_SETTINGS;
138
+ }
139
+ let root;
140
+ try {
141
+ root = JSON.parse(text);
142
+ }
143
+ catch {
144
+ return DEFAULT_COMPACTION_PINNING_SETTINGS;
145
+ }
146
+ if (typeof root !== 'object' || root === null)
147
+ return DEFAULT_COMPACTION_PINNING_SETTINGS;
148
+ const section = root[SETTINGS_NAMESPACE];
149
+ if (typeof section !== 'object' || section === null)
150
+ return DEFAULT_COMPACTION_PINNING_SETTINGS;
151
+ try {
152
+ return resolveSettings(section);
153
+ }
154
+ catch {
155
+ return DEFAULT_COMPACTION_PINNING_SETTINGS;
156
+ }
157
+ }
158
+ //# sourceMappingURL=settings.js.map