@chenhw7/dsh-memory 0.9.3 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/README.i18n.yaml +2 -2
  2. package/README.md +88 -70
  3. package/README.zh.md +87 -69
  4. package/cordis.patch.yml +17 -8
  5. package/lib/client/index.js +2169 -2168
  6. package/lib/context/index.d.ts +35 -124
  7. package/lib/context/index.d.ts.map +1 -1
  8. package/lib/context/index.js +75 -201
  9. package/lib/context/index.js.map +1 -1
  10. package/lib/context/settings.d.ts +67 -0
  11. package/lib/context/settings.d.ts.map +1 -0
  12. package/lib/context/settings.js +69 -0
  13. package/lib/context/settings.js.map +1 -0
  14. package/lib/identity/index.d.ts +29 -8
  15. package/lib/identity/index.d.ts.map +1 -1
  16. package/lib/identity/index.js +31 -37
  17. package/lib/identity/index.js.map +1 -1
  18. package/lib/identity/settings.d.ts +26 -12
  19. package/lib/identity/settings.d.ts.map +1 -1
  20. package/lib/identity/settings.js +29 -13
  21. package/lib/identity/settings.js.map +1 -1
  22. package/lib/index.d.ts +12 -0
  23. package/lib/index.d.ts.map +1 -1
  24. package/lib/index.js +1 -0
  25. package/lib/index.js.map +1 -1
  26. package/lib/notes/index.d.ts +35 -4
  27. package/lib/notes/index.d.ts.map +1 -1
  28. package/lib/notes/index.js +26 -31
  29. package/lib/notes/index.js.map +1 -1
  30. package/lib/notes/settings.d.ts +30 -10
  31. package/lib/notes/settings.d.ts.map +1 -1
  32. package/lib/notes/settings.js +29 -9
  33. package/lib/notes/settings.js.map +1 -1
  34. package/lib/remote/index.d.ts +7 -7
  35. package/lib/remote/index.d.ts.map +1 -1
  36. package/lib/review/accumulator.d.ts.map +1 -1
  37. package/lib/review/accumulator.js +8 -12
  38. package/lib/review/accumulator.js.map +1 -1
  39. package/lib/review/consolidate.d.ts.map +1 -1
  40. package/lib/review/consolidate.js +2 -1
  41. package/lib/review/consolidate.js.map +1 -1
  42. package/lib/review/extract.d.ts.map +1 -1
  43. package/lib/review/extract.js +2 -1
  44. package/lib/review/extract.js.map +1 -1
  45. package/lib/review/index.d.ts +40 -4
  46. package/lib/review/index.d.ts.map +1 -1
  47. package/lib/review/index.js +83 -66
  48. package/lib/review/index.js.map +1 -1
  49. package/lib/review/sweep.d.ts.map +1 -1
  50. package/lib/review/sweep.js +2 -1
  51. package/lib/review/sweep.js.map +1 -1
  52. package/lib/sources.d.ts +37 -0
  53. package/lib/sources.d.ts.map +1 -0
  54. package/lib/sources.js +16 -0
  55. package/lib/sources.js.map +1 -0
  56. package/lib/store/index.d.ts +37 -15
  57. package/lib/store/index.d.ts.map +1 -1
  58. package/lib/store/index.js +20 -8
  59. package/lib/store/index.js.map +1 -1
  60. package/lib/store/settings.d.ts +84 -0
  61. package/lib/store/settings.d.ts.map +1 -0
  62. package/lib/store/settings.js +77 -0
  63. package/lib/store/settings.js.map +1 -0
  64. package/lib/store/sqlite.d.ts +6 -0
  65. package/lib/store/sqlite.d.ts.map +1 -1
  66. package/lib/store/sqlite.js +7 -0
  67. package/lib/store/sqlite.js.map +1 -1
  68. package/lib/tool/index.d.ts +10 -10
  69. package/lib/tool/index.d.ts.map +1 -1
  70. package/lib/tool/index.js +29 -60
  71. package/lib/tool/index.js.map +1 -1
  72. package/lib/types.d.ts +2 -2
  73. package/package.json +47 -47
  74. package/lib/invariant.d.ts +0 -27
  75. package/lib/invariant.d.ts.map +0 -1
  76. package/lib/invariant.js +0 -42
  77. package/lib/invariant.js.map +0 -1
@@ -1,5 +1,6 @@
1
1
  /**
2
- * System-prompt memory context injection and the `memory` settings namespace.
2
+ * System-prompt memory context injection and the `memory-autorecall` settings
3
+ * entry.
3
4
  *
4
5
  * This function plugin contributes four system-prompt sections: `memory` at
5
6
  * order 6000 and `project-notes` at 6001 — after the host's tool guidance
@@ -23,13 +24,13 @@
23
24
  * fences of BM25 hits — both merged into at most one plugin message per step,
24
25
  * so the frozen prefix itself never changes mid-session.
25
26
  *
26
- * The memory-family settings namespaces are registered through `ctx.settings`,
27
- * one per plugin-configuration card (`memory`, `memory-notes`,
28
- * `memory-autorecall`, `memory-identity`): the harness's plugins tab dispatches
29
- * a card only when its slot key names a namespace the Host serves, so each
30
- * card's key IS its namespace here. All are `applies: 'live'` — a change takes
31
- * effect on the next assembly without a restart. The composition config stays
32
- * one full shape, and each namespace's base layer projects its slice from it.
27
+ * The memory-family settings are four profile entries, each declaring its own
28
+ * `Config`: `memory` (the store: injection budgets, search cap, decay),
29
+ * `memory-notes`, `memory-autorecall` (this plugin), and `memory-identity`.
30
+ * This plugin owns only the auto-recall slice and reads the other three from
31
+ * the services that own them (`ctx.memory`, `ctx.projectNotes`,
32
+ * `ctx.identity`), so every value a card writes is read back from the plugin
33
+ * that declared it rather than from a shared namespace.
33
34
  *
34
35
  * @module @chenhw7/dsh-memory/context
35
36
  */
@@ -37,7 +38,10 @@ import type { Context } from '@deepseek-ai/cordis';
37
38
  import z from '@deepseek-ai/schemastery';
38
39
  import type { MemoryEntry, MemoryId } from '../types.ts';
39
40
  import type { MemoryStore } from '../index.ts';
40
- import { type MemoryMode } from './policy.ts';
41
+ import type { NotesSettings } from '../notes/settings.ts';
42
+ import type { IdentitySettings } from '../identity/settings.ts';
43
+ import type { MemoryInjectionSettings } from '../store/settings.ts';
44
+ import type { AutoRecallSettings } from './settings.ts';
41
45
  export { buildMemorySectionText, buildAutoRecallBlock, buildMemoryDigestText, renderMemoryIndex, MEMORY_POLICY_TEXT, MEMORY_DIGEST_POLICY_HINT, MEMORY_CONTEXT_NOTE, MEMORY_INDEX_NOTE, AUTO_RECALL_NOTE } from './policy.ts';
42
46
  export { buildNotesSectionText, buildSoulSectionText, buildUserProfileSectionText, PROJECT_NOTES_NOTE, SOUL_NOTE, USER_PROFILE_NOTE } from './policy.ts';
43
47
  export type { MemoryMode, IndexEntry } from './policy.ts';
@@ -46,115 +50,17 @@ export declare const name = "memory-context";
46
50
  /** The prompt registry is required; settings and memory are optional. */
47
51
  export declare const inject: string[];
48
52
  /**
49
- * The memory-family settings shape, validated by the same-named schemastery
50
- * schemas and doubling as the plugin's `cordis.yml` config. The composition
51
- * config stays ONE full shape; the four settings namespaces project their
52
- * slices from it as each namespace's `base` layer, and the user settings
53
- * document overlays each slice in its own section. Every field is optional in
54
- * yml; the schema defaults supply the rest.
55
- *
56
- * The split follows the host's plugin-card contract (one card per served
57
- * namespace), so the slice boundaries are the card boundaries:
58
- * `MemoryInjectionConfig` → the curated memory card / `memory` namespace,
59
- * `MemoryNotesConfig` → the Project Notes card / `memory-notes`,
60
- * `MemoryAutoRecallConfig` → the Auto Recall card / `memory-autorecall`,
61
- * `MemoryIdentityConfig` → the Identity card / `memory-identity`.
53
+ * The merged runtime view the injection surfaces read: the four settings
54
+ * slices, each owned by the plugin entry that declares it. `memory-context`
55
+ * owns only the auto-recall slice; the injection budgets come from the store
56
+ * entry (`ctx.memory`), the notes budgets from the notes entry
57
+ * (`ctx.projectNotes`), and the identity budgets from the identity entry
58
+ * (`ctx.identity`) — the host's per-entry configuration model gives each
59
+ * plugin its own `Config`, so shared knobs ride the owning service.
62
60
  */
63
- export interface MemoryInjectionConfig {
64
- /** How recalled memory reaches the system prompt; defaults to `digest` (a one-time inventory message + per-step recall fences, nothing resident). */
65
- memoryMode: MemoryMode;
66
- /** User-supplied custom policy text, used only when `memoryMode` is `custom`. */
67
- memoryPolicyCustomText?: string;
68
- /** Character budget for the frozen memory content snapshot; defaults to `5000`. */
69
- memoryCharLimit: number;
70
- /**
71
- * Character budget for the one-time `<memory-digest>` inventory message in
72
- * `digest` mode (≈250 tokens at the 4-chars/token estimate; CJK topics run
73
- * higher). `0` disables the digest message while keeping the mode's section
74
- * guidance. Defaults to `800`.
75
- */
76
- memoryDigestCharLimit: number;
77
- /**
78
- * Maximum number of entries injected into the memory snapshot regardless of
79
- * the character budget (P0-6). Entries beyond this count are rolled up into
80
- * a count-only summary line. `0` = no entry-count limit. Defaults to `20`.
81
- */
82
- memoryMaxEntries: number;
83
- /** Max entries returned by `memory_search` / `memory_list` when the call omits `limit`; defaults to `50`. `0` = no limit. */
84
- maxSearchResults: number;
85
- /** Days without recall before a project-scoped entry is decayed by the janitor. `0` = disabled. Defaults to `30`. */
86
- decayDays: number;
87
- }
88
- export interface MemoryNotesConfig {
89
- /** Enable the `project-notes` prompt section; defaults to `true`. */
90
- notesEnabled: boolean;
91
- /**
92
- * Character budget for the rendered conventions half of the notes section.
93
- * Absent inherits the resolver default (`1600`); the deprecated combined
94
- * `notesCharLimit` derives it (60%) when it is the only key set.
95
- */
96
- notesConventionsCharLimit?: number;
97
- /**
98
- * Character budget for the rendered pitfalls half of the notes section.
99
- * Absent inherits the resolver default (`800`); the deprecated combined
100
- * `notesCharLimit` derives it (40%) when it is the only key set.
101
- */
102
- notesPitfallsCharLimit?: number;
103
- /** Max entries selected into the notes section (the rest fold into count lines); defaults to `100`. */
104
- notesMaxEntriesPerFile: number;
105
- }
106
- export interface MemoryAutoRecallConfig {
107
- /**
108
- * Append a fenced auto-recall block to each step's messages (BM25 over the
109
- * store). Defaults to `true` — the digest-mode complement: the digest says
110
- * WHAT is stored (once per session), the fence recalls WHAT it says (per
111
- * step, at the step tail). Fence hits stamp `lastRecalledAt` only, never
112
- * `accessCount`.
113
- */
114
- autoRecallEnabled: boolean;
115
- /** Max entries in one auto-recall fence; defaults to `5`. */
116
- autoRecallLimit: number;
117
- /** Skip recall when the step's user text is shorter than this many characters. Defaults to `12`. */
118
- autoRecallMinChars: number;
119
- /**
120
- * Enable the usage-hit signal (write-path rework Step 2): when the
121
- * assistant's answer echoes an injected entry's tokens/anchors (IDF-weighted
122
- * overlap above {@link hitSignalThreshold}), the entry gains one `hitCount`.
123
- * The periodic sweep's selection is the only consumer. Defaults to `false`.
124
- */
125
- hitSignalEnabled: boolean;
126
- /**
127
- * Weighted token-overlap between an injected entry and the assistant's
128
- * answer above which the answer counts as a hit: the IDF-weighted share of
129
- * the entry's tokens the answer restates. Defaults to `0.25` — mid-band of
130
- * the measured calibration (genuine restatement 0.5–0.7, incidental
131
- * mention 0.05–0.12, unrelated ~0).
132
- */
133
- hitSignalThreshold: number;
134
- }
135
- export interface MemoryIdentityConfig {
136
- /**
137
- * Enable the identity layer: the `soul` and `user-profile` prompt sections
138
- * plus the `identity_update` agent tool's write surface. Opt-in; defaults
139
- * to `false`.
140
- */
141
- identityEnabled: boolean;
142
- /** Character budget for the injected soul section; defaults to `2000`. */
143
- soulCharLimit: number;
144
- /** Character budget for the injected user-profile section; defaults to `3000`. */
145
- userCharLimit: number;
146
- /**
147
- * Optional directory holding custom identity seed files (`SOUL.md` /
148
- * `USER.md`); empty uses the builtin Chinese seeds. Validated loudly at
149
- * load when identity is enabled; a missing file for one kind keeps that
150
- * kind's builtin seed (partial override).
151
- */
152
- identitySeedDir?: string;
153
- }
154
- /** The full memory-family settings shape: the composition config and the merged runtime view. */
155
- export type MemoryConfig = MemoryInjectionConfig & MemoryNotesConfig & MemoryAutoRecallConfig & MemoryIdentityConfig;
156
- /** Runtime schema for the composition config: the union of the four namespace slices. */
157
- export declare const Config: z<MemoryConfig>;
61
+ export type MemoryConfig = MemoryInjectionSettings & NotesSettings & AutoRecallSettings & IdentitySettings;
62
+ /** The `memory-autorecall` entry config — this plugin's own settings page. */
63
+ export declare const Config: z<AutoRecallSettings>;
158
64
  /**
159
65
  * Rough estimate of the token count for a text blob (P0-6). Uses the
160
66
  * commonly cited ~4-characters-per-token approximation for English; CJK
@@ -196,15 +102,20 @@ export declare function readMemorySnapshot(memory: MemoryStore, charLimit: numbe
196
102
  */
197
103
  export declare function readMemoryIndex(memory: MemoryStore, charLimit: number, exclude?: (entry: MemoryEntry) => boolean): string;
198
104
  /**
199
- * Register the `memory` settings namespace and the `memory` system-prompt
200
- * section. The section text is a function evaluated at each assembly: it reads
201
- * the live settings mode and the session's frozen memory snapshot, so a
202
- * settings change takes effect on the next assembly while the recalled
203
- * content stays frozen for the session.
105
+ * Register the four memory system-prompt sections and the step-tail injection.
106
+ * The section text is a function evaluated at each assembly: it reads the live
107
+ * settings and the session's frozen memory snapshot, so a settings change takes
108
+ * effect on the next assembly while the recalled content stays frozen for the
109
+ * session.
110
+ *
111
+ * Settings reach this plugin from two places: its own entry config (the
112
+ * auto-recall slice) and the services that own the other three entries. The
113
+ * host re-runs `apply` when a card commits a change, so every read here sees
114
+ * the value the user just saved.
204
115
  * @param ctx - Cordis context carrying the prompt registry.
205
- * @param config - resolved plugin entry config, used as the settings `base`.
116
+ * @param config - the `memory-autorecall` entry config.
206
117
  */
207
- export declare function apply(ctx: Context, config: MemoryConfig): void;
118
+ export declare function apply(ctx: Context, config?: AutoRecallSettings): void;
208
119
  /**
209
120
  * One injected entry awaiting a possible hit: its id plus the token bag the
210
121
  * hit computation weighs (content + summary + anchors). Recorded into the
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/context/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AAEH,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,qBAAqB,CAAA;AAClD,OAAO,CAAC,MAAM,0BAA0B,CAAA;AAKxC,OAAO,KAAK,EAAE,WAAW,EAAE,QAAQ,EAAe,MAAM,aAAa,CAAA;AACrE,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,aAAa,CAAA;AAoC9C,OAAO,EAAuN,KAAK,UAAU,EAAmB,MAAM,aAAa,CAAA;AAEnR,OAAO,EAAE,sBAAsB,EAAE,oBAAoB,EAAE,qBAAqB,EAAE,iBAAiB,EAAE,kBAAkB,EAAE,yBAAyB,EAAE,mBAAmB,EAAE,iBAAiB,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAA;AAC7N,OAAO,EAAE,qBAAqB,EAAE,oBAAoB,EAAE,2BAA2B,EAAE,kBAAkB,EAAE,SAAS,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAA;AACxJ,YAAY,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,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AW,EACnB,SAAS,EAAE,MAAM,EACjB,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,WAAW,KAAK,OAAO,EACzC,UAAU,GAAE,MAAU,GACrB,MAAM,CA6CR;AAED;;;;;;;;;GASG;AACH,wBAAgB,eAAe,CAAC,MAAM,EAAE,WAAW,EAAE,SAAS,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,WAAW,KAAK,OAAO,GAAG,MAAM,CAuBzH;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAgB,KAAK,CAAC,GAAG,EAAE,OAAO,EAAE,MAAM,GAAE,kBAAiD,GAAG,IAAI,CAwUnG;AAYD;;;;GAIG;AACH,MAAM,WAAW,WAAW;IAC1B,QAAQ,CAAC,EAAE,EAAE,QAAQ,CAAA;IACrB,mEAAmE;IACnE,QAAQ,CAAC,MAAM,EAAE,WAAW,CAAC,MAAM,CAAC,CAAA;CACrC;AAwBD;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,WAAW,CAAC,MAAM,EAAE,SAAS,WAAW,EAAE,EAAE,UAAU,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,QAAQ,EAAE,CAmB7G"}
@@ -1,5 +1,6 @@
1
1
  /**
2
- * System-prompt memory context injection and the `memory` settings namespace.
2
+ * System-prompt memory context injection and the `memory-autorecall` settings
3
+ * entry.
3
4
  *
4
5
  * This function plugin contributes four system-prompt sections: `memory` at
5
6
  * order 6000 and `project-notes` at 6001 — after the host's tool guidance
@@ -23,13 +24,13 @@
23
24
  * fences of BM25 hits — both merged into at most one plugin message per step,
24
25
  * so the frozen prefix itself never changes mid-session.
25
26
  *
26
- * The memory-family settings namespaces are registered through `ctx.settings`,
27
- * one per plugin-configuration card (`memory`, `memory-notes`,
28
- * `memory-autorecall`, `memory-identity`): the harness's plugins tab dispatches
29
- * a card only when its slot key names a namespace the Host serves, so each
30
- * card's key IS its namespace here. All are `applies: 'live'` — a change takes
31
- * effect on the next assembly without a restart. The composition config stays
32
- * one full shape, and each namespace's base layer projects its slice from it.
27
+ * The memory-family settings are four profile entries, each declaring its own
28
+ * `Config`: `memory` (the store: injection budgets, search cap, decay),
29
+ * `memory-notes`, `memory-autorecall` (this plugin), and `memory-identity`.
30
+ * This plugin owns only the auto-recall slice and reads the other three from
31
+ * the services that own them (`ctx.memory`, `ctx.projectNotes`,
32
+ * `ctx.identity`), so every value a card writes is read back from the plugin
33
+ * that declared it rather than from a shared namespace.
33
34
  *
34
35
  * @module @chenhw7/dsh-memory/context
35
36
  */
@@ -39,10 +40,12 @@ import { buildCorpusStats, tokenizeForSearch, uniqueTokens, idfOf } from '../sto
39
40
  import { messageText } from '../review/accumulator.js';
40
41
  import { annotateConflicts } from './conflict.js';
41
42
  import { isRenderedEntry } from '../notes/scope.js';
42
- import { DEFAULT_NOTES_ENABLED, DEFAULT_NOTES_MAX_ENTRIES_PER_FILE, resolveNotesSettings, } from '../notes/settings.js';
43
+ import { DEFAULT_NOTES_SETTINGS } from '../notes/settings.js';
43
44
  import { EMPTY_IDENTITY } from '../identity/index.js';
44
45
  import { validateSeedDir } from '../identity/seeds.js';
45
- import { DEFAULT_IDENTITY_ENABLED, DEFAULT_SOUL_CHAR_LIMIT, DEFAULT_USER_CHAR_LIMIT, } from '../identity/settings.js';
46
+ import { DEFAULT_IDENTITY_SETTINGS } from '../identity/settings.js';
47
+ import { DEFAULT_INJECTION_SETTINGS } from '../store/settings.js';
48
+ import { AUTORECALL_FIELDS, DEFAULT_AUTO_RECALL_SETTINGS, resolveAutoRecallSettings, } from './settings.js';
46
49
  import { createUserMessage } from '@deepseek-ai/dsh-llm';
47
50
  import { buildMemorySectionText, buildNotesSectionText, buildAutoRecallBlock, buildSoulSectionText, buildUserProfileSectionText, buildMemoryDigestText, renderMemoryIndex, AUTO_RECALL_CHAR_LIMIT } from './policy.js';
48
51
  export { buildMemorySectionText, buildAutoRecallBlock, buildMemoryDigestText, renderMemoryIndex, MEMORY_POLICY_TEXT, MEMORY_DIGEST_POLICY_HINT, MEMORY_CONTEXT_NOTE, MEMORY_INDEX_NOTE, AUTO_RECALL_NOTE } from './policy.js';
@@ -51,38 +54,6 @@ export { buildNotesSectionText, buildSoulSectionText, buildUserProfileSectionTex
51
54
  export const name = 'memory-context';
52
55
  /** The prompt registry is required; settings and memory are optional. */
53
56
  export const inject = ['systemPrompt'];
54
- /**
55
- * The settings namespaces this plugin owns — one per plugin-configuration
56
- * card: the harness's plugins tab dispatches a card only when its slot key
57
- * names a namespace the Host serves, so each card's key IS its namespace.
58
- */
59
- const NS = 'memory';
60
- const NOTES_NS = 'memory-notes';
61
- const AUTORECALL_NS = 'memory-autorecall';
62
- const IDENTITY_NS = 'memory-identity';
63
- // Factory default is `digest`: the system prompt carries only the frozen
64
- // policy guidance, while a one-time <memory-digest> inventory (category
65
- // counts + anchor topics) rides the first step's tail and per-step recall
66
- // fences answer "what does it actually say". The data never resides in the
67
- // prefix, so a re-freeze or store change never disturbs the cached prefix.
68
- // This rewrites rather than overturns the index-default promotion: the
69
- // existence awareness the index carried as 80-char lines now lives in the
70
- // digest's counts and topic words (see the implemented Agent Note
71
- // index-default-promotion and this change's own). `index`/`full` remain
72
- // explicit opt-ins for prefix-resident data; `policy-only`/`off` trim further.
73
- const DEFAULT_MEMORY_MODE = 'digest';
74
- const DEFAULT_MEMORY_CHAR_LIMIT = 5000;
75
- /** Character budget for the one-time digest inventory (≈250 tokens); `0` = off. */
76
- const DEFAULT_MEMORY_DIGEST_CHAR_LIMIT = 800;
77
- const DEFAULT_MAX_SEARCH_RESULTS = 50;
78
- const DEFAULT_DECAY_DAYS = 30;
79
- /**
80
- * Default maximum number of memory entries injected into the system-prompt
81
- * snapshot, regardless of the character budget (P0-6). Prevents a large
82
- * store from flooding the prompt even when the character budget allows it.
83
- * `0` = no entry-count limit (character budget only).
84
- */
85
- const DEFAULT_MEMORY_MAX_ENTRIES = 20;
86
57
  /** The empty project-notes snapshot (notes disabled, service absent, or no cwd). */
87
58
  const EMPTY_NOTES = { conventions: '', pitfalls: '' };
88
59
  /** The `memory` system-prompt section name. */
@@ -108,98 +79,8 @@ const USER_PROFILE_SECTION_NAME = 'user-profile';
108
79
  const USER_PROFILE_SECTION_ORDER = 81;
109
80
  /** Scopes read into the frozen per-session memory snapshot, in render order. */
110
81
  const SNAPSHOT_SCOPES = ['global', 'project', 'user'];
111
- /**
112
- * Schema fragments shared between the four namespace schemas and the plugin
113
- * config — one home per default, so the composition layer and the settings
114
- * namespaces cannot drift.
115
- */
116
- const INJECTION_FIELDS = {
117
- memoryMode: z.union(['full', 'policy-only', 'custom', 'off', 'index', 'digest']).default(DEFAULT_MEMORY_MODE),
118
- memoryPolicyCustomText: z.string(),
119
- memoryCharLimit: z.number().step(1).min(0).default(DEFAULT_MEMORY_CHAR_LIMIT),
120
- memoryDigestCharLimit: z.number().step(1).min(0).default(DEFAULT_MEMORY_DIGEST_CHAR_LIMIT),
121
- memoryMaxEntries: z.number().step(1).min(0).default(DEFAULT_MEMORY_MAX_ENTRIES),
122
- maxSearchResults: z.number().step(1).min(0).default(DEFAULT_MAX_SEARCH_RESULTS),
123
- decayDays: z.number().step(1).min(0).default(DEFAULT_DECAY_DAYS),
124
- };
125
- const NOTES_FIELDS = {
126
- notesEnabled: z.boolean().default(DEFAULT_NOTES_ENABLED),
127
- // No schema default on the two budgets on purpose: absence is the signal
128
- // the deprecated `notesCharLimit` fallback reads (60/40 derivation in
129
- // resolveNotesSettings — the one home for the builtin defaults too).
130
- notesConventionsCharLimit: z.number().step(1).min(0),
131
- notesPitfallsCharLimit: z.number().step(1).min(0),
132
- notesMaxEntriesPerFile: z.number().step(1).min(0).default(DEFAULT_NOTES_MAX_ENTRIES_PER_FILE),
133
- };
134
- const AUTORECALL_FIELDS = {
135
- autoRecallEnabled: z.boolean().default(true),
136
- autoRecallLimit: z.number().step(1).min(1).default(5),
137
- autoRecallMinChars: z.number().step(1).min(1).default(12),
138
- hitSignalEnabled: z.boolean().default(false),
139
- hitSignalThreshold: z.number().min(0).max(1).default(0.25),
140
- };
141
- const IDENTITY_FIELDS = {
142
- identityEnabled: z.boolean().default(DEFAULT_IDENTITY_ENABLED),
143
- soulCharLimit: z.number().step(1).min(0).default(DEFAULT_SOUL_CHAR_LIMIT),
144
- userCharLimit: z.number().step(1).min(0).default(DEFAULT_USER_CHAR_LIMIT),
145
- identitySeedDir: z.string(),
146
- };
147
- /** Runtime schema for the composition config: the union of the four namespace slices. */
148
- export const Config = z.object({
149
- ...INJECTION_FIELDS,
150
- ...NOTES_FIELDS,
151
- ...AUTORECALL_FIELDS,
152
- ...IDENTITY_FIELDS,
153
- });
154
- /** Per-namespace schemas — each plugin-configuration card's settings slice. */
155
- const MemorySectionSchema = z.object(INJECTION_FIELDS);
156
- const NotesSectionSchema = z.object(NOTES_FIELDS);
157
- const AutoRecallSectionSchema = z.object(AUTORECALL_FIELDS);
158
- const IdentitySectionSchema = z.object(IDENTITY_FIELDS);
159
- /** Base-layer projections: each namespace's composition slice of the plugin config. */
160
- function injectionEntry(config) {
161
- return {
162
- memoryMode: config.memoryMode,
163
- // Optional composition keys are carried only when set (exactOptionalPropertyTypes).
164
- ...config.memoryPolicyCustomText === undefined ? {} : { memoryPolicyCustomText: config.memoryPolicyCustomText },
165
- memoryCharLimit: config.memoryCharLimit,
166
- memoryDigestCharLimit: config.memoryDigestCharLimit,
167
- memoryMaxEntries: config.memoryMaxEntries,
168
- maxSearchResults: config.maxSearchResults,
169
- decayDays: config.decayDays,
170
- };
171
- }
172
- function notesEntry(config) {
173
- // The deprecated `notesCharLimit` rides along untyped (schemastery's
174
- // non-strict object passes unknown keys through) so resolveNotesSettings
175
- // can derive both budgets from it — one derivation home, no second
176
- // implementation here.
177
- const legacy = config.notesCharLimit;
178
- return {
179
- notesEnabled: config.notesEnabled,
180
- ...config.notesConventionsCharLimit === undefined ? {} : { notesConventionsCharLimit: config.notesConventionsCharLimit },
181
- ...config.notesPitfallsCharLimit === undefined ? {} : { notesPitfallsCharLimit: config.notesPitfallsCharLimit },
182
- notesMaxEntriesPerFile: config.notesMaxEntriesPerFile,
183
- ...(typeof legacy === 'number' ? { notesCharLimit: legacy } : {}),
184
- };
185
- }
186
- function autoRecallEntry(config) {
187
- return {
188
- autoRecallEnabled: config.autoRecallEnabled,
189
- autoRecallLimit: config.autoRecallLimit,
190
- autoRecallMinChars: config.autoRecallMinChars,
191
- hitSignalEnabled: config.hitSignalEnabled,
192
- hitSignalThreshold: config.hitSignalThreshold,
193
- };
194
- }
195
- function identityEntry(config) {
196
- return {
197
- identityEnabled: config.identityEnabled,
198
- soulCharLimit: config.soulCharLimit,
199
- userCharLimit: config.userCharLimit,
200
- ...config.identitySeedDir === undefined ? {} : { identitySeedDir: config.identitySeedDir },
201
- };
202
- }
82
+ /** The `memory-autorecall` entry config — this plugin's own settings page. */
83
+ export const Config = z.object(AUTORECALL_FIELDS);
203
84
  /**
204
85
  * Render one scope's entries as a bulleted list under a `## <scope>` heading.
205
86
  *
@@ -348,39 +229,43 @@ export function readMemoryIndex(memory, charLimit, exclude) {
348
229
  return text;
349
230
  }
350
231
  /**
351
- * Register the `memory` settings namespace and the `memory` system-prompt
352
- * section. The section text is a function evaluated at each assembly: it reads
353
- * the live settings mode and the session's frozen memory snapshot, so a
354
- * settings change takes effect on the next assembly while the recalled
355
- * content stays frozen for the session.
232
+ * Register the four memory system-prompt sections and the step-tail injection.
233
+ * The section text is a function evaluated at each assembly: it reads the live
234
+ * settings and the session's frozen memory snapshot, so a settings change takes
235
+ * effect on the next assembly while the recalled content stays frozen for the
236
+ * session.
237
+ *
238
+ * Settings reach this plugin from two places: its own entry config (the
239
+ * auto-recall slice) and the services that own the other three entries. The
240
+ * host re-runs `apply` when a card commits a change, so every read here sees
241
+ * the value the user just saved.
356
242
  * @param ctx - Cordis context carrying the prompt registry.
357
- * @param config - resolved plugin entry config, used as the settings `base`.
243
+ * @param config - the `memory-autorecall` entry config.
358
244
  */
359
- export function apply(ctx, config) {
360
- // Load-time loud gate for the composition layer: the owner of the `memory`
361
- // namespace validates its own config before mounting. Cordis swallows
362
- // throws from `ctx.inject` callbacks (verified against the installed
363
- // runtime), so the gate cannot live in the identity plugin; settings-overlay
364
- // changes made live through the UI degrade observably instead (reported
365
- // failure + builtin-seed fallback, surfaced through health()).
366
- const seedDir = config.identitySeedDir ?? '';
367
- if (config.identityEnabled && seedDir.trim().length > 0) {
245
+ export function apply(ctx, config = DEFAULT_AUTO_RECALL_SETTINGS) {
246
+ const recall = resolveAutoRecallSettings(config);
247
+ // Load-time loud gate for the identity entry: this plugin assembles the
248
+ // identity sections, so it validates the seed directory before mounting.
249
+ // Cordis swallows throws from `ctx.inject` callbacks (verified against the
250
+ // installed runtime), so the gate cannot live in the identity plugin;
251
+ // settings-overlay changes made live through the UI degrade observably
252
+ // instead (reported failure + builtin-seed fallback, surfaced through
253
+ // health()).
254
+ const identitySettings = () => ctx.get('identity')?.settings() ?? DEFAULT_IDENTITY_SETTINGS;
255
+ const seedDir = identitySettings().identitySeedDir;
256
+ if (identitySettings().identityEnabled && seedDir.trim().length > 0) {
368
257
  validateSeedDir(seedDir);
369
258
  }
370
- // Source thunks for the current resolved settings slices: the settings
371
- // scopes while one is attached, the composition projections otherwise
372
- // (reassigned by `installSection` on attach and detach). The merged view
373
- // keeps every consumer reading the one MemoryConfig shape.
374
- let memorySource = () => injectionEntry(config);
375
- let notesSource = () => notesEntry(config);
376
- let recallSource = () => autoRecallEntry(config);
377
- let identitySource = () => identityEntry(config);
378
- /** The merged runtime view across the four namespaces, re-read per event/call. */
259
+ /**
260
+ * The merged runtime view across the four entries, re-read per event/call.
261
+ * Each slice comes from the service that owns its entry; the builtin
262
+ * defaults stand in when a service is not composed.
263
+ */
379
264
  const current = () => ({
380
- ...memorySource(),
381
- ...notesSource(),
382
- ...recallSource(),
383
- ...identitySource(),
265
+ ...ctx.get('memory')?.settings() ?? DEFAULT_INJECTION_SETTINGS,
266
+ ...ctx.get('projectNotes')?.settings() ?? DEFAULT_NOTES_SETTINGS,
267
+ ...recall,
268
+ ...identitySettings(),
384
269
  });
385
270
  /**
386
271
  * The resolved notes settings. Notes budgets (and the deprecated
@@ -388,7 +273,7 @@ export function apply(ctx, config) {
388
273
  * {@link resolveNotesSettings} — so the injection side and the notes
389
274
  * service cannot drift.
390
275
  */
391
- const notesResolved = () => resolveNotesSettings(notesSource());
276
+ const notesResolved = () => ctx.get('projectNotes')?.settings() ?? DEFAULT_NOTES_SETTINGS;
392
277
  // Per-session frozen memory snapshots (content + index), read once at session/created.
393
278
  const sessionMemory = new WeakMap();
394
279
  // Sessions that already received their one-time digest message. The flag is
@@ -401,38 +286,6 @@ export function apply(ctx, config) {
401
286
  // `assistant/message` listener weighs the answer against these and books the
402
287
  // echoes as store hits. A WeakMap: the ledger dies with its session.
403
288
  const hitLedger = new WeakMap();
404
- ctx.inject(['settings'], (settingsCtx) => {
405
- // One namespace per plugin-configuration card; each base layer projects
406
- // its slice of the composition config. A card whose slot key is not a
407
- // served namespace is never dispatched by the host's plugins tab, so
408
- // these registrations are what make the four cards visible.
409
- settingsCtx.settings.installSection(ctx, NS, MemorySectionSchema, injectionEntry(config), {
410
- setSource: (source) => {
411
- memorySource = source;
412
- },
413
- // The section text provider reads settings live at each assembly, so a
414
- // committed change is picked up without re-judging registration-level facts.
415
- onChange: () => { },
416
- });
417
- settingsCtx.settings.installSection(ctx, NOTES_NS, NotesSectionSchema, notesEntry(config), {
418
- setSource: (source) => {
419
- notesSource = source;
420
- },
421
- onChange: () => { },
422
- });
423
- settingsCtx.settings.installSection(ctx, AUTORECALL_NS, AutoRecallSectionSchema, autoRecallEntry(config), {
424
- setSource: (source) => {
425
- recallSource = source;
426
- },
427
- onChange: () => { },
428
- });
429
- settingsCtx.settings.installSection(ctx, IDENTITY_NS, IdentitySectionSchema, identityEntry(config), {
430
- setSource: (source) => {
431
- identitySource = source;
432
- },
433
- onChange: () => { },
434
- });
435
- });
436
289
  /** Infer the current project name from a session's cwd (basename). */
437
290
  const projectNameOf = (session) => {
438
291
  const cwd = session.header?.cwd;
@@ -464,7 +317,7 @@ export function apply(ctx, config) {
464
317
  return;
465
318
  }
466
319
  const charLimit = settings.memoryCharLimit;
467
- const maxEntries = settings.memoryMaxEntries ?? DEFAULT_MEMORY_MAX_ENTRIES;
320
+ const maxEntries = settings.memoryMaxEntries;
468
321
  // No double injection: entries rendered into the project-notes section
469
322
  // are excluded from the memory section's snapshot/index while notes are
470
323
  // enabled.
@@ -510,6 +363,20 @@ export function apply(ctx, config) {
510
363
  return items;
511
364
  };
512
365
  ctx.on('session/created', freezeFor, { global: true });
366
+ /**
367
+ * The session's frozen snapshot, freezing it on first touch. Sessions created
368
+ * before this fiber (re)applied — a settings change re-runs `apply`, which
369
+ * replaces the per-session maps — have no entry yet; freezing lazily here
370
+ * keeps their sections filled instead of blanking them until the next
371
+ * `session/created`.
372
+ */
373
+ const snapshotOf = (session) => {
374
+ const frozen = sessionMemory.get(session);
375
+ if (frozen !== undefined)
376
+ return frozen;
377
+ freezeFor(session);
378
+ return sessionMemory.get(session) ?? { content: '', index: '', notes: EMPTY_NOTES, identity: EMPTY_IDENTITY };
379
+ };
513
380
  // Compaction is the one sanctioned moment to break the KV-cache prefix —
514
381
  // the prompt rebuilds anyway — so re-freeze here to surface memories that
515
382
  // were learned mid-session (review/flush extraction) without paying the
@@ -589,9 +456,16 @@ export function apply(ctx, config) {
589
456
  if (digestBlock.length === 0 && recallBlock.length === 0)
590
457
  return next();
591
458
  const text = [digestBlock, recallBlock].filter(block => block.length > 0).join('\n\n');
459
+ // The digest inventory and the recall fence are one message: a `snapshot`
460
+ // with one named contribution each, so a consumer can present them apart
461
+ // and knows a later fence supersedes this round's set.
462
+ const sections = [
463
+ ...digestBlock.length > 0 ? [{ name: 'memory-digest', text: digestBlock }] : [],
464
+ ...recallBlock.length > 0 ? [{ name: 'recalled-memory', text: recallBlock }] : [],
465
+ ];
592
466
  const message = createUserMessage({
593
467
  content: [{ type: 'text', text }],
594
- source: { kind: 'plugin', plugin: 'dsh-memory-context' },
468
+ source: { kind: 'memory-context', form: 'snapshot', sections },
595
469
  });
596
470
  // Committed to emitting: mark the digest sent only now, so any failure
597
471
  // above falls through with the flag intact and the digest re-tries.
@@ -647,7 +521,7 @@ export function apply(ctx, config) {
647
521
  text: (context) => {
648
522
  const settings = current();
649
523
  const session = context.agent?.session;
650
- const snapshot = session === undefined ? undefined : sessionMemory.get(session);
524
+ const snapshot = session === undefined ? undefined : snapshotOf(session);
651
525
  const memoryContent = snapshot?.content ?? '';
652
526
  const indexContent = snapshot?.index ?? '';
653
527
  return buildMemorySectionText(settings.memoryMode, settings.memoryPolicyCustomText, memoryContent, indexContent);
@@ -661,7 +535,7 @@ export function apply(ctx, config) {
661
535
  if (!notes.notesEnabled)
662
536
  return '';
663
537
  const session = context.agent?.session;
664
- const snapshot = session === undefined ? undefined : sessionMemory.get(session);
538
+ const snapshot = session === undefined ? undefined : snapshotOf(session);
665
539
  // The frozen snapshot already applied the entry-level budgets at freeze
666
540
  // time; the live budgets here are the assembly-side final defense
667
541
  // (fenceWithin caps the whole section at their sum plus the fence frame).
@@ -676,7 +550,7 @@ export function apply(ctx, config) {
676
550
  if (!settings.identityEnabled)
677
551
  return '';
678
552
  const session = context.agent?.session;
679
- const snapshot = session === undefined ? undefined : sessionMemory.get(session);
553
+ const snapshot = session === undefined ? undefined : snapshotOf(session);
680
554
  return buildSoulSectionText(snapshot?.identity.soul ?? '', settings.soulCharLimit);
681
555
  },
682
556
  }), 'memory-context.soul-section()');
@@ -688,7 +562,7 @@ export function apply(ctx, config) {
688
562
  if (!settings.identityEnabled)
689
563
  return '';
690
564
  const session = context.agent?.session;
691
- const snapshot = session === undefined ? undefined : sessionMemory.get(session);
565
+ const snapshot = session === undefined ? undefined : snapshotOf(session);
692
566
  return buildUserProfileSectionText(snapshot?.identity.user ?? '', settings.userCharLimit);
693
567
  },
694
568
  }), 'memory-context.user-profile-section()');