@lmzhen/dsh-evolution-activity 0.43.2-rc.1 → 0.45.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/feedback/index.js +690 -0
- package/lib/index.js +23 -18
- package/lib/learning-graph/index.js +538 -0
- package/lib/replay/index.js +286 -0
- package/lib/threat/index.js +70 -0
- package/lib/types/feedback/index.d.ts +179 -0
- package/lib/types/feedback/index.js +899 -0
- package/lib/types/index.js +335 -0
- package/lib/types/learning-graph/index.d.ts +178 -0
- package/lib/types/learning-graph/index.js +712 -0
- package/lib/types/replay/index.d.ts +182 -0
- package/lib/types/replay/index.js +404 -0
- package/lib/types/threat/index.d.ts +35 -0
- package/lib/types/threat/index.js +119 -0
- package/locale/de.json +6 -0
- package/locale/en.json +6 -0
- package/locale/es.json +6 -0
- package/locale/feedback/de.json +6 -0
- package/locale/feedback/en.json +6 -0
- package/locale/feedback/es.json +6 -0
- package/locale/feedback/fr.json +6 -0
- package/locale/feedback/ja.json +6 -0
- package/locale/feedback/pt.json +6 -0
- package/locale/feedback/ru.json +6 -0
- package/locale/feedback/zh.json +6 -0
- package/locale/fr.json +6 -0
- package/locale/ja.json +6 -0
- package/locale/learning-graph/de.json +6 -0
- package/locale/learning-graph/en.json +6 -0
- package/locale/learning-graph/es.json +6 -0
- package/locale/learning-graph/fr.json +6 -0
- package/locale/learning-graph/ja.json +6 -0
- package/locale/learning-graph/pt.json +6 -0
- package/locale/learning-graph/ru.json +6 -0
- package/locale/learning-graph/zh.json +6 -0
- package/locale/pt.json +6 -0
- package/locale/replay/de.json +6 -0
- package/locale/replay/en.json +6 -0
- package/locale/replay/es.json +6 -0
- package/locale/replay/fr.json +6 -0
- package/locale/replay/ja.json +6 -0
- package/locale/replay/pt.json +6 -0
- package/locale/replay/ru.json +6 -0
- package/locale/replay/zh.json +6 -0
- package/locale/ru.json +6 -0
- package/locale/threat/de.json +6 -0
- package/locale/threat/en.json +6 -0
- package/locale/threat/es.json +6 -0
- package/locale/threat/fr.json +6 -0
- package/locale/threat/ja.json +6 -0
- package/locale/threat/pt.json +6 -0
- package/locale/threat/ru.json +6 -0
- package/locale/threat/zh.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +31 -7
|
@@ -0,0 +1,335 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Durable activity store for self-evolution plan outcomes.
|
|
3
|
+
*
|
|
4
|
+
* Adjudication (rc.42, A-line P0-1): plan outcomes are process events on the
|
|
5
|
+
* cordis bus (a session log carrying `evolution/*` types is refused wholesale
|
|
6
|
+
* at resume), so the retired session projection is replaced by this driver:
|
|
7
|
+
* it subscribes to `evolution/plan-applied` (payload v2, with sessionId) and
|
|
8
|
+
* persists every outcome to `$DSH_HOME/evolution/activity.json` through the
|
|
9
|
+
* evolution IO seam — the same best-effort sidecar posture as
|
|
10
|
+
* `feedback.json` and the curator reports. A storage-domain table is deferred
|
|
11
|
+
* until a consumer needs domain routing (the domain spec version-gates its
|
|
12
|
+
* media, so adding a table is not a free schema addition).
|
|
13
|
+
*
|
|
14
|
+
* The sidecar is append-merge (load → fold → save under an in-process queue),
|
|
15
|
+
* so records survive host restarts and are readable without a session.
|
|
16
|
+
* @module @lmzhen/dsh-evolution-activity
|
|
17
|
+
*/
|
|
18
|
+
import z from '@deepseek-ai/schemastery';
|
|
19
|
+
import { evolutionHome, evolutionIoAdapter, transactIo } from '@lmzhen/dsh-evolution-core';
|
|
20
|
+
import { join } from 'node:path';
|
|
21
|
+
/** Version of the `activity.json` shape; writers always emit the current one. */
|
|
22
|
+
export const ACTIVITY_FILE_VERSION = 2;
|
|
23
|
+
/** Default bound on the retained sidecar (S6.4: also the fallback for a
|
|
24
|
+
* non-finite `maxItems`). */
|
|
25
|
+
export const DEFAULT_MAX_ITEMS = 200;
|
|
26
|
+
/** Bound on the retained final review text; the full length stays in finalTextChars. */
|
|
27
|
+
export const REVIEW_TEXT_PREVIEW_CHARS = 2000;
|
|
28
|
+
export function activityFile(root) {
|
|
29
|
+
return join(root, 'activity.json');
|
|
30
|
+
}
|
|
31
|
+
/** Fold one plan-applied payload into a bounded record list (pure). */
|
|
32
|
+
export function applyActivityEvent(items, event, maxItems, at = Date.now()) {
|
|
33
|
+
// H-05: EVERY optional field is conditionally spread, so an absent
|
|
34
|
+
// value leaves the key ABSENT instead of present-with-undefined — the same
|
|
35
|
+
// 口径 as the executionFailures/executionError pair (V6-10). Previously
|
|
36
|
+
// policyFingerprint/evidenceQuotes/estimatedInputChars were assigned
|
|
37
|
+
// unconditionally, so `'x' in record` behaved asymmetrically across the
|
|
38
|
+
// optional fields (a future bug seed for consumers keying on key presence;
|
|
39
|
+
// JSON output was already identical since stringify drops undefined).
|
|
40
|
+
const record = {
|
|
41
|
+
sessionId: event.sessionId,
|
|
42
|
+
planId: event.planId,
|
|
43
|
+
...event.policyFingerprint !== undefined ? { policyFingerprint: event.policyFingerprint } : {},
|
|
44
|
+
memoryApplied: event.memoryApplied,
|
|
45
|
+
skillApplied: event.skillApplied,
|
|
46
|
+
rejectedOps: event.rejectedOps,
|
|
47
|
+
// R-03: a plan whose ops were ALL skipped (session never read the skill)
|
|
48
|
+
// has nothing accepted and nothing rejected — keep the third dimension.
|
|
49
|
+
...event.skippedUnread !== undefined ? { skippedUnread: event.skippedUnread } : {},
|
|
50
|
+
// V6-10 (0.3.36): a plan that failed entirely at execution must not fold
|
|
51
|
+
// into a clean "0/0" record — keep the failure dimension (V5-19 payload).
|
|
52
|
+
...event.executionFailures !== undefined ? { executionFailures: event.executionFailures } : {},
|
|
53
|
+
...event.executionError !== undefined ? { executionError: event.executionError } : {},
|
|
54
|
+
...event.evidenceQuotes !== undefined ? { evidenceQuotes: event.evidenceQuotes } : {},
|
|
55
|
+
...event.estimatedInputChars !== undefined ? { estimatedInputChars: event.estimatedInputChars } : {},
|
|
56
|
+
...event.evidenceClassReports !== undefined ? { evidenceClassReports: event.evidenceClassReports } : {},
|
|
57
|
+
at,
|
|
58
|
+
};
|
|
59
|
+
// A non-positive cap would disable the window entirely (`slice(-0)` keeps
|
|
60
|
+
// everything), so it clamps to at least one record (rc.42 regression guard).
|
|
61
|
+
// A non-finite cap (NaN/±Infinity) also disables the window (`slice(-NaN)`
|
|
62
|
+
// keeps everything), so it falls back to the default bound (S6.4) — the
|
|
63
|
+
// caller with a logger owns the diagnostic warn.
|
|
64
|
+
const cap = Number.isFinite(maxItems) ? Math.max(1, maxItems) : DEFAULT_MAX_ITEMS;
|
|
65
|
+
return [...items, record].slice(-cap);
|
|
66
|
+
}
|
|
67
|
+
/** Fold one review-completed payload into a bounded review list (pure). */
|
|
68
|
+
export function applyReviewActivityEvent(reviews, event, maxItems, at = Date.now()) {
|
|
69
|
+
const record = {
|
|
70
|
+
reviewId: event.reviewId,
|
|
71
|
+
sessionId: event.sessionId,
|
|
72
|
+
...event.branchSessionId === undefined ? {} : { branchSessionId: event.branchSessionId },
|
|
73
|
+
kind: event.kind,
|
|
74
|
+
status: event.status,
|
|
75
|
+
trigger: event.trigger,
|
|
76
|
+
finalText: event.finalText.length <= REVIEW_TEXT_PREVIEW_CHARS ? event.finalText : event.finalText.slice(0, REVIEW_TEXT_PREVIEW_CHARS),
|
|
77
|
+
finalTextChars: event.finalText.length,
|
|
78
|
+
actions: event.actions,
|
|
79
|
+
...event.usage === undefined ? {} : { usage: event.usage },
|
|
80
|
+
startedAt: event.startedAt,
|
|
81
|
+
finishedAt: event.finishedAt,
|
|
82
|
+
...event.model === undefined ? {} : { model: event.model },
|
|
83
|
+
...event.promptVersion === undefined ? {} : { promptVersion: event.promptVersion },
|
|
84
|
+
...event.error === undefined ? {} : { error: event.error },
|
|
85
|
+
at,
|
|
86
|
+
};
|
|
87
|
+
const cap = Number.isFinite(maxItems) ? Math.max(1, maxItems) : DEFAULT_MAX_ITEMS;
|
|
88
|
+
return [...reviews, record].slice(-cap);
|
|
89
|
+
}
|
|
90
|
+
/** Single-source activity sidecar serialization (F-304): the `apply()`
|
|
91
|
+
* listener emits the versioned envelope through this one function, so a
|
|
92
|
+
* format change cannot drift across hand-written writers.
|
|
93
|
+
* `parseActivityContent` is the matching single reader. */
|
|
94
|
+
export function serializeActivity(items, reviews = []) {
|
|
95
|
+
return JSON.stringify({ version: ACTIVITY_FILE_VERSION, items, ...reviews.length === 0 ? {} : { reviews } }, null, 2);
|
|
96
|
+
}
|
|
97
|
+
export function parseActivityContent(raw) {
|
|
98
|
+
if (raw === null)
|
|
99
|
+
return [];
|
|
100
|
+
const isCount = (value) => typeof value === 'number' && Number.isFinite(value);
|
|
101
|
+
// `at` is epoch-ms (finite number) — a hand-edited NaN/missing timestamp
|
|
102
|
+
// would render as "Invalid Date" in every report.
|
|
103
|
+
const isTimestampEpochMs = (value) => typeof value === 'number' && Number.isFinite(value);
|
|
104
|
+
const isOptionalCount = (value) => value === undefined || isCount(value);
|
|
105
|
+
try {
|
|
106
|
+
const parsed = JSON.parse(raw);
|
|
107
|
+
const items = typeof parsed === 'object' && parsed !== null && Array.isArray(parsed.items)
|
|
108
|
+
? parsed.items
|
|
109
|
+
: [];
|
|
110
|
+
return items.filter((item) => typeof item === 'object' && item !== null
|
|
111
|
+
&& typeof item.planId === 'string'
|
|
112
|
+
&& typeof item.sessionId === 'string'
|
|
113
|
+
// P3-23 (v14): the op counters are consumed by numeric math downstream;
|
|
114
|
+
// a malformed sidecar entry must be dropped rather than propagating NaN
|
|
115
|
+
// (same finite-number discipline feedback applies to its own records).
|
|
116
|
+
&& isCount(item.memoryApplied)
|
|
117
|
+
&& isCount(item.skillApplied)
|
|
118
|
+
&& isCount(item.rejectedOps)
|
|
119
|
+
// P3 (v15): `at` is the timestamp every report renders; the optional
|
|
120
|
+
// numeric dimensions must stay finite for the same reason as the
|
|
121
|
+
// counters. A hand-edited sidecar entry missing/NaN on any of these is
|
|
122
|
+
// dropped instead of half-parsed.
|
|
123
|
+
&& isTimestampEpochMs(item.at)
|
|
124
|
+
&& isOptionalCount(item.skippedUnread)
|
|
125
|
+
&& isOptionalCount(item.executionFailures)
|
|
126
|
+
&& isOptionalCount(item.evidenceQuotes)
|
|
127
|
+
&& isOptionalCount(item.estimatedInputChars)
|
|
128
|
+
// 0.10.0: the evidence-class dimension is a count like its siblings — a hand-edited sidecar
|
|
129
|
+
// that puts a string here is dropped, not half-parsed into a report that renders it raw.
|
|
130
|
+
&& isOptionalCount(item.evidenceClassReports));
|
|
131
|
+
}
|
|
132
|
+
catch {
|
|
133
|
+
// Unparsable bytes fold to empty so every READER stays total; the single
|
|
134
|
+
// WRITE path (see apply) quarantines those bytes before it can overwrite
|
|
135
|
+
// them, which is where the loss would actually happen.
|
|
136
|
+
return [];
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
/** Parse the review history sidecar array; malformed entries are dropped. */
|
|
140
|
+
export function parseActivityReviews(raw) {
|
|
141
|
+
if (raw === null)
|
|
142
|
+
return [];
|
|
143
|
+
try {
|
|
144
|
+
const parsed = JSON.parse(raw);
|
|
145
|
+
const reviews = typeof parsed === 'object' && parsed !== null && Array.isArray(parsed.reviews)
|
|
146
|
+
? parsed.reviews
|
|
147
|
+
: [];
|
|
148
|
+
return reviews.filter((item) => typeof item === 'object' && item !== null
|
|
149
|
+
&& typeof item.reviewId === 'string'
|
|
150
|
+
&& typeof item.sessionId === 'string'
|
|
151
|
+
&& typeof item.finalText === 'string'
|
|
152
|
+
&& typeof item.at === 'number'
|
|
153
|
+
&& Number.isFinite(item.at));
|
|
154
|
+
}
|
|
155
|
+
catch {
|
|
156
|
+
return [];
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
/**
|
|
160
|
+
* One parse, one verdict — every reader-facing answer above is derived from this one call.
|
|
161
|
+
* @param raw - the sidecar bytes, or null when the file is absent.
|
|
162
|
+
* @returns the verdict.
|
|
163
|
+
*/
|
|
164
|
+
function activityVerdict(raw) {
|
|
165
|
+
if (raw === null)
|
|
166
|
+
return 'absent';
|
|
167
|
+
try {
|
|
168
|
+
const parsed = JSON.parse(raw);
|
|
169
|
+
if (typeof parsed !== 'object' || parsed === null || !Array.isArray(parsed.items))
|
|
170
|
+
return 'unreadable';
|
|
171
|
+
const version = parsed.version;
|
|
172
|
+
return version !== undefined && version !== ACTIVITY_FILE_VERSION ? 'foreign' : 'readable';
|
|
173
|
+
}
|
|
174
|
+
catch {
|
|
175
|
+
// Unparsable bytes are the one shape that is corruption on both sides: nothing readable, and
|
|
176
|
+
// nothing worth preserving beyond the quarantine copy.
|
|
177
|
+
return 'unreadable';
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
/**
|
|
181
|
+
* H-06: the read barrier over the sidecar, with the two verdicts it must not conflate.
|
|
182
|
+
*
|
|
183
|
+
* @param root - the evolution state root (the sidecar lives under it).
|
|
184
|
+
* @param io - the IO provider to read through.
|
|
185
|
+
* @returns the parsed records, plus whether they are MISSING (`corrupt`) and whether a newer
|
|
186
|
+
* writer wrote the envelope (`foreignVersion`).
|
|
187
|
+
*/
|
|
188
|
+
export async function loadActivityState(root, io) {
|
|
189
|
+
const raw = await io.readText(activityFile(root));
|
|
190
|
+
const verdict = activityVerdict(raw);
|
|
191
|
+
return {
|
|
192
|
+
records: parseActivityContent(raw),
|
|
193
|
+
corrupt: verdict === 'unreadable',
|
|
194
|
+
foreignVersion: verdict === 'foreign',
|
|
195
|
+
};
|
|
196
|
+
}
|
|
197
|
+
/**
|
|
198
|
+
* H-06: the read barrier over the sidecar — records only, no corruption
|
|
199
|
+
* verdict. @internal Test-only: no production caller (verified by grep
|
|
200
|
+
* 2026-09-16); replay consumes {@link loadActivityState} — the V24-13 claim
|
|
201
|
+
* that `loadActivity` "HAS a production consumer — evolution-replay" was
|
|
202
|
+
* inaccurate (PLAN S5.2). Kept exported so the published surface does not
|
|
203
|
+
* break. The single-writer rule is unchanged: `apply()`'s transact listener
|
|
204
|
+
* remains the only WRITE path. Consumers that must not read an unreadable
|
|
205
|
+
* sidecar as "no history" use {@link loadActivityState}.
|
|
206
|
+
*/
|
|
207
|
+
export async function loadActivity(root, io) {
|
|
208
|
+
return (await loadActivityState(root, io)).records;
|
|
209
|
+
}
|
|
210
|
+
/** Read durable review history without a plan-record read. */
|
|
211
|
+
export async function loadReviewActivity(root, io) {
|
|
212
|
+
return parseActivityReviews(await io.readText(activityFile(root)));
|
|
213
|
+
}
|
|
214
|
+
/**
|
|
215
|
+
* The WRITE side's quarantine predicate: should these bytes be preserved under `.corrupt` before a
|
|
216
|
+
* current-version file replaces them?
|
|
217
|
+
*
|
|
218
|
+
* v43 audit (H-3 / J-6 / FLOW6-6): yes for an envelope declaring an UNSUPPORTED version. The read
|
|
219
|
+
* side has always ignored `version` and taken `items` as-is, so a future-version sidecar used to
|
|
220
|
+
* fold fine and then be rewritten as `version: ACTIVITY_FILE_VERSION` on the next append — a silent
|
|
221
|
+
* downgrade that destroyed whatever the newer format carried. This is the `foreign` verdict from
|
|
222
|
+
* {@link activityVerdict}, which is why this predicate is NOT the read side's `corrupt`: a foreign
|
|
223
|
+
* envelope's records ARE read (only the bytes are worth preserving), while `corrupt` means there
|
|
224
|
+
* were no readable records in the first place.
|
|
225
|
+
* @internal Exported for this package's own tests (siblings `parseActivityContent`
|
|
226
|
+
* and `serializeActivity` are exported for the same reason).
|
|
227
|
+
*/
|
|
228
|
+
export function isCorruptActivity(raw) {
|
|
229
|
+
const verdict = activityVerdict(raw);
|
|
230
|
+
return verdict === 'unreadable' || verdict === 'foreign';
|
|
231
|
+
}
|
|
232
|
+
export const name = 'evolution-activity';
|
|
233
|
+
export const Config = z.object({
|
|
234
|
+
// G3.1 (0.3.23): a non-positive bound would disable the retention window
|
|
235
|
+
// (`slice(-0)` keeps everything), so 0/negative fail loud at the schema. The
|
|
236
|
+
// assembly-time S6.4 clamp (non-finite -> default) covers NaN/±Infinity,
|
|
237
|
+
// which a bare `z.number()` lets through.
|
|
238
|
+
maxItems: z.number().min(1).default(DEFAULT_MAX_ITEMS),
|
|
239
|
+
});
|
|
240
|
+
export function apply(ctx, rawConfig = {}) {
|
|
241
|
+
// S6.4: a non-finite `maxItems` (NaN slips through `z.number()` since
|
|
242
|
+
// `typeof NaN === 'number'`) would disable the window; resolve it once here,
|
|
243
|
+
// warn when it was bad, and let the pure fold fall back for direct callers.
|
|
244
|
+
const configuredMaxItems = rawConfig.maxItems ?? DEFAULT_MAX_ITEMS;
|
|
245
|
+
let maxItems;
|
|
246
|
+
if (!Number.isFinite(configuredMaxItems)) {
|
|
247
|
+
maxItems = DEFAULT_MAX_ITEMS;
|
|
248
|
+
ctx.logger.warn(`evolution-activity: maxItems is not a finite number; falling back to the default ${DEFAULT_MAX_ITEMS}`);
|
|
249
|
+
}
|
|
250
|
+
else if (configuredMaxItems < 1) {
|
|
251
|
+
// V4-42: the schema `.min(1)` rejects 0/negative on the loader path, but a
|
|
252
|
+
// direct/programmatic assembly can bypass it. A non-positive bound would
|
|
253
|
+
// disable the window (`slice(-0)` keeps everything), so clamp to 1 and warn
|
|
254
|
+
// — the same loud posture the other family packages apply to a 0 config.
|
|
255
|
+
maxItems = 1;
|
|
256
|
+
ctx.logger.warn(`evolution-activity: maxItems=${String(configuredMaxItems)} is invalid; falling back to 1`);
|
|
257
|
+
}
|
|
258
|
+
else {
|
|
259
|
+
maxItems = configuredMaxItems;
|
|
260
|
+
}
|
|
261
|
+
// Deferred binding (S6.4, tool-* pattern): subscribe only once the evolution
|
|
262
|
+
// IO provider mounts, so a provider registered after this plugin still wires
|
|
263
|
+
// persistence instead of being skipped by an apply-time probe. Without the
|
|
264
|
+
// provider the listener never registers, matching the previous no-op.
|
|
265
|
+
ctx.inject(['evolutionIo'], (ioCtx) => {
|
|
266
|
+
const ioRegistry = ioCtx.evolutionIo;
|
|
267
|
+
// Lazy adapter: forwards transact (N-4) when the backend provides it — the
|
|
268
|
+
// fold then runs inside one cross-process lock, so a second process sharing
|
|
269
|
+
// DSH_HOME cannot interleave between our read and write.
|
|
270
|
+
const io = evolutionIoAdapter(() => ioRegistry.provider());
|
|
271
|
+
const root = evolutionHome();
|
|
272
|
+
const authority = ioCtx.get('evolutionMutationAuthority');
|
|
273
|
+
const commit = (path, task) => transactIo(io, path, task);
|
|
274
|
+
/** The ONE cross-process writer: a home fence when the authority provides one, else the seam. */
|
|
275
|
+
const write = async (path, task) => {
|
|
276
|
+
if (authority?.homeFence !== undefined)
|
|
277
|
+
await authority.homeFence.run(async () => { await commit(path, task); });
|
|
278
|
+
else
|
|
279
|
+
await commit(path, task);
|
|
280
|
+
};
|
|
281
|
+
/**
|
|
282
|
+
* One durable fold over the activity file, used by BOTH events.
|
|
283
|
+
*
|
|
284
|
+
* W9/02-P1.3: the review branch used to call transactIo directly while the plan branch went
|
|
285
|
+
* through `write`. Both are read-modify-write over the same file, so the asymmetry meant plan
|
|
286
|
+
* records excluded other processes and review records did not — a review written while another
|
|
287
|
+
* plane appended a plan read a stale snapshot and silently dropped it. One helper, two events.
|
|
288
|
+
*/
|
|
289
|
+
const foldActivity = async (task) => {
|
|
290
|
+
await write(activityFile(root), async (current) => {
|
|
291
|
+
const file = activityFile(root);
|
|
292
|
+
if (!isCorruptActivity(current))
|
|
293
|
+
return await task(current);
|
|
294
|
+
// Fold would restart from [] and overwrite bytes that are still recoverable — quarantine first.
|
|
295
|
+
const rescued = await io.writeText(`${file}.corrupt`, current).then(() => true, () => false);
|
|
296
|
+
if (!rescued) {
|
|
297
|
+
ioCtx.logger.warn(`evolution-activity: ${file} is unreadable; the .corrupt copy could not be written — refusing this write so the original bytes stay recoverable`);
|
|
298
|
+
return current;
|
|
299
|
+
}
|
|
300
|
+
ioCtx.logger.warn(`evolution-activity: ${file} is unreadable (unparsable JSON or wrong top-level shape); the original bytes were copied to ${file}.corrupt and the store restarts from the readable entries`);
|
|
301
|
+
return await task(current);
|
|
302
|
+
});
|
|
303
|
+
};
|
|
304
|
+
// In-process serialization: each event is one transactIo cycle, so
|
|
305
|
+
// concurrent outcomes in THIS process can never overwrite each other's
|
|
306
|
+
// newest record (the backend lock covers other processes).
|
|
307
|
+
let chain = Promise.resolve();
|
|
308
|
+
ioCtx.on('evolution/plan-applied', (event) => {
|
|
309
|
+
const run = chain.then(() => foldActivity(async (current) => {
|
|
310
|
+
const items = applyActivityEvent(parseActivityContent(current), event, maxItems);
|
|
311
|
+
return serializeActivity(items, parseActivityReviews(current));
|
|
312
|
+
}));
|
|
313
|
+
chain = run.then(() => undefined, () => undefined);
|
|
314
|
+
run.catch((error) => {
|
|
315
|
+
// Persistence is best-effort: the outcome was already applied upstream.
|
|
316
|
+
ioCtx.logger.warn(error instanceof Error ? error : String(error));
|
|
317
|
+
});
|
|
318
|
+
});
|
|
319
|
+
// Round 28: a headless host may dispose immediately after the review
|
|
320
|
+
// summary; await the in-process write chain so the review record is not
|
|
321
|
+
// lost between event emission and host teardown.
|
|
322
|
+
ioCtx.effect(() => () => chain, 'evolution-activity.flush');
|
|
323
|
+
ioCtx.on('evolution/review-completed', (event) => {
|
|
324
|
+
const run = chain.then(() => foldActivity(async (current) => {
|
|
325
|
+
const reviews = applyReviewActivityEvent(parseActivityReviews(current), event, maxItems);
|
|
326
|
+
return serializeActivity(parseActivityContent(current), reviews);
|
|
327
|
+
}));
|
|
328
|
+
chain = run.then(() => undefined, () => undefined);
|
|
329
|
+
run.catch((error) => {
|
|
330
|
+
ioCtx.logger.warn(error instanceof Error ? error : String(error));
|
|
331
|
+
});
|
|
332
|
+
});
|
|
333
|
+
});
|
|
334
|
+
}
|
|
335
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Learning graph over skills and memory, plus node-level commands
|
|
3
|
+
* (`graph [detail|edit|delete] <nodeId>` — P2-33 (v11): the command is a
|
|
4
|
+
* TOP-LEVEL `graph` command, not `/evolution graph`; README is accurate)
|
|
5
|
+
* aligned with the Hermes
|
|
6
|
+
* journey surface: a skill node is its name, a memory node is
|
|
7
|
+
* `memory:<source>:<index>` (source = memory|user, index = position in that
|
|
8
|
+
* file's entries). Memory node ids carry a trailing snapshot token so
|
|
9
|
+
* edit/delete can reject a stale index (E-21).
|
|
10
|
+
* @module @lmzhen/dsh-evolution-learning-graph
|
|
11
|
+
*/
|
|
12
|
+
import type { Context } from '@deepseek-ai/cordis';
|
|
13
|
+
import { type WriteOrigin } from '@lmzhen/dsh-evolution-core/skills';
|
|
14
|
+
import z from '@deepseek-ai/schemastery';
|
|
15
|
+
export interface GraphNode {
|
|
16
|
+
id: string;
|
|
17
|
+
kind: 'skill' | 'memory';
|
|
18
|
+
label: string;
|
|
19
|
+
}
|
|
20
|
+
export interface GraphEdge {
|
|
21
|
+
from: string;
|
|
22
|
+
to: string;
|
|
23
|
+
type: 'related' | 'memory_skill';
|
|
24
|
+
}
|
|
25
|
+
export interface LearningGraph {
|
|
26
|
+
nodes: GraphNode[];
|
|
27
|
+
edges: GraphEdge[];
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Structural summary of the skill subgraph (Hermes `learning_graph` density
|
|
31
|
+
* parity): edges per skill node and the share of skills no edge touches.
|
|
32
|
+
* Memory nodes are excluded — they carry token-matched edges by construction,
|
|
33
|
+
* which would dilute the isolation signal the statistic exists to expose.
|
|
34
|
+
*/
|
|
35
|
+
export interface GraphDensity {
|
|
36
|
+
skillNodes: number;
|
|
37
|
+
relatedEdges: number;
|
|
38
|
+
edgesPerNode: number;
|
|
39
|
+
isolatedPct: number;
|
|
40
|
+
}
|
|
41
|
+
export declare function graphDensity(graph: LearningGraph): GraphDensity;
|
|
42
|
+
/**
|
|
43
|
+
* Render one node's display line for `/evolution graph`.
|
|
44
|
+
*
|
|
45
|
+
* A skill node's id IS its name, so `● <name>` already addresses it — an
|
|
46
|
+
* isolated skill (no edge) is addressable by name alone. A memory node's id
|
|
47
|
+
* is the `memory:<source>:<index>:<snapshot>` string `buildLearningGraph`
|
|
48
|
+
* emits, so the id is appended in brackets: an isolated memory node (no edge
|
|
49
|
+
* carrying its id) is otherwise unaddressable from the render. The full id is
|
|
50
|
+
* shown (not the bare `memory:<source>:<index>` prefix) so it matches the id
|
|
51
|
+
* form the edge lines render and so the trailing snapshot — the E-21 token the
|
|
52
|
+
* mutation commands use to reject a stale index — survives the copy/paste
|
|
53
|
+
* (F-322). A bare prefix would round-trip through `parseGraphNodeId` but would
|
|
54
|
+
* silently skip the E-21 drift guard in `readMemoryIndex`.
|
|
55
|
+
*/
|
|
56
|
+
export declare function renderNodeLine(node: GraphNode): string;
|
|
57
|
+
/**
|
|
58
|
+
* Build a small deterministic graph from usage records and memory entries.
|
|
59
|
+
* Memory node ids follow `memory:<source>:<index>` (source = memory|user,
|
|
60
|
+
* index = position in that file's entries) — the SAME rule the parser
|
|
61
|
+
* `parseGraphNodeId` accepts, so graph detail/edit/delete round-trips.
|
|
62
|
+
*
|
|
63
|
+
* Skill-skill edges are semantic only (B-line G3): each entry of `related`
|
|
64
|
+
* (skill name -> names its frontmatter references, from
|
|
65
|
+
* `relatedSkillNames`) becomes an edge when BOTH endpoints exist in the
|
|
66
|
+
* usage set, self-edges are dropped and undirected duplicates collapse. An
|
|
67
|
+
* omitted `related` yields no skill-skill edges — the former alphabet-order
|
|
68
|
+
* chain was a placeholder that connected unrelated neighbors.
|
|
69
|
+
*/
|
|
70
|
+
export declare function buildLearningGraph(usage: ReadonlyMap<string, unknown>, memoryEntries: readonly string[], userEntries?: readonly string[], related?: ReadonlyMap<string, readonly string[]>): LearningGraph;
|
|
71
|
+
export type GraphNodeId = {
|
|
72
|
+
kind: 'skill';
|
|
73
|
+
name: string;
|
|
74
|
+
} | {
|
|
75
|
+
kind: 'memory';
|
|
76
|
+
source: 'memory' | 'user';
|
|
77
|
+
index: number;
|
|
78
|
+
snapshot?: string;
|
|
79
|
+
};
|
|
80
|
+
/**
|
|
81
|
+
* E-21 snapshot token: a deterministic 8-hex-char digest of a memory entry's
|
|
82
|
+
* rendered label (first line, first 80 chars). The graph builder embeds it in
|
|
83
|
+
* the memory node id so a later edit/delete can detect index drift — any
|
|
84
|
+
* memory write between the last render and the command shifts `memory:<source>:<index>`
|
|
85
|
+
* positions, and the token lets the command reject a stale index instead of
|
|
86
|
+
* mutating the wrong entry. FNV-1a (no imports, cross-platform).
|
|
87
|
+
*/
|
|
88
|
+
export declare function memorySnapshotOf(entry: string): string;
|
|
89
|
+
export interface MemoryIndexCheck {
|
|
90
|
+
ok: boolean;
|
|
91
|
+
/** The current entry at the index, present when ok. */
|
|
92
|
+
entry?: string;
|
|
93
|
+
message?: string;
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* E-21 TOCTOU guard for a memory node operation. Re-reads the entry at
|
|
97
|
+
* `parsed.index` and, when the id carries a snapshot token, verifies the
|
|
98
|
+
* current entry's label still matches it. A mismatch means a memory write
|
|
99
|
+
* shifted the index between the last `/graph` render and this command, so the
|
|
100
|
+
* operation is refused (the caller surfaces "re-run /graph"). A missing
|
|
101
|
+
* snapshot (a hand-typed bare `memory:<source>:<index>` id) skips the check
|
|
102
|
+
* and falls back to operating on whatever currently sits at the index.
|
|
103
|
+
*/
|
|
104
|
+
export declare function readMemoryIndex(parsed: Extract<GraphNodeId, {
|
|
105
|
+
kind: 'memory';
|
|
106
|
+
}>, entries: readonly string[]): MemoryIndexCheck;
|
|
107
|
+
/**
|
|
108
|
+
* Parse a graph node id: skill names pass through; `memory:<source>:<index>`
|
|
109
|
+
* becomes a memory node. An optional trailing `:<snapshot>` (the E-21
|
|
110
|
+
* `memorySnapshotOf` token the builder embeds) is carried so edit/delete can
|
|
111
|
+
* detect index drift; a bare index id (hand-typed) still parses with no
|
|
112
|
+
* snapshot and skips the drift check.
|
|
113
|
+
*/
|
|
114
|
+
export declare function parseGraphNodeId(id: string): GraphNodeId | null;
|
|
115
|
+
/** Resolve a parsed node to its current content (read-only). */
|
|
116
|
+
export declare function resolveGraphNode(parsed: GraphNodeId, repository: {
|
|
117
|
+
readSkill(name: string): Promise<string | null>;
|
|
118
|
+
readMemory(target: 'memory' | 'user'): Promise<string[]>;
|
|
119
|
+
}): Promise<{
|
|
120
|
+
ok: boolean;
|
|
121
|
+
message: string;
|
|
122
|
+
}>;
|
|
123
|
+
/**
|
|
124
|
+
* E-26 approval seam (soft-probed, mirrors tool-skill-manage): graph skill
|
|
125
|
+
* mutations route through the same `evolutionApproval.request` gate. The
|
|
126
|
+
* staged `args` use the skill_manage runner's shape so the runner tool-skill-
|
|
127
|
+
* manage registers for `kind: 'skill'` replays them on approve.
|
|
128
|
+
*/
|
|
129
|
+
export declare const name = "evolution-learning-graph";
|
|
130
|
+
export interface Config {
|
|
131
|
+
/** V10-11 (P2-7): skill tree root for graph reads/edits; empty (default)
|
|
132
|
+
* resolves through `resolveSkillsRoot` to the shared default root. Keeps
|
|
133
|
+
* the graph on the SAME skills tree the tools/catalog read under a
|
|
134
|
+
* custom-root deployment (previously the default root was hardcoded). */
|
|
135
|
+
root?: string;
|
|
136
|
+
/** P2-26 (v19): the deployment's benign threat labels. The graph edit/delete
|
|
137
|
+
* channel writes skill content through the same SkillLibrary as the tools,
|
|
138
|
+
* so it must honour the same exemption list — without it a label allowed on
|
|
139
|
+
* the tool channel was refused here, and the refusal named a config key this
|
|
140
|
+
* channel could not reach. */
|
|
141
|
+
threatExemptLabels?: string[];
|
|
142
|
+
}
|
|
143
|
+
export declare const Config: z<Config>;
|
|
144
|
+
/**
|
|
145
|
+
* F-10: rendered-line cap for the `/graph` directory — nodes span the
|
|
146
|
+
* whole usage set plus every memory entry and the edge list is a full join, so
|
|
147
|
+
* a large library used to produce an unbounded command result. Nodes and edges
|
|
148
|
+
* are each capped at this many lines (the density footer always renders the
|
|
149
|
+
* true totals); overflow shows a `…N more` marker instead.
|
|
150
|
+
*/
|
|
151
|
+
export declare const GRAPH_RENDER_LINE_CAP = 200;
|
|
152
|
+
/** Join lines under the render cap; overflow is summarized, not dropped silently. */
|
|
153
|
+
export declare function capRenderedLines(lines: string[]): string;
|
|
154
|
+
/**
|
|
155
|
+
* G1/1.2: the graph commands' write-admission call, as a NAMED function.
|
|
156
|
+
*
|
|
157
|
+
* The gates run at the execution point: these commands write at the bytes, exactly like the tool's
|
|
158
|
+
* execution path, so the read-before-write gate does not apply and a missing session read set is not a
|
|
159
|
+
* refusal. `delete` archives (reversible) and is allowed through by the protection gate by design;
|
|
160
|
+
* `update` is what a protected skill is refused for.
|
|
161
|
+
*
|
|
162
|
+
* Named rather than inlined because the wiring it represents - "this command passes the SAME sequence" -
|
|
163
|
+
* has to be provable by a case that fails when the call disappears.
|
|
164
|
+
* @param services - the policy source and the warn sink, both from the command's own context.
|
|
165
|
+
* @param request - the action, the target name, the new body for an update, and the library write origin.
|
|
166
|
+
* @returns the refusal message, or null when the write may proceed.
|
|
167
|
+
*/
|
|
168
|
+
export declare function graphWriteGate(services: {
|
|
169
|
+
readonly policy: unknown;
|
|
170
|
+
readonly warn: (message: string) => void;
|
|
171
|
+
}, request: {
|
|
172
|
+
readonly action: 'update' | 'delete';
|
|
173
|
+
readonly name: string;
|
|
174
|
+
readonly content?: string | undefined;
|
|
175
|
+
readonly origin: WriteOrigin;
|
|
176
|
+
}): Promise<string | null>;
|
|
177
|
+
export declare function apply(ctx: Context, rawConfig?: Config): void;
|
|
178
|
+
//# sourceMappingURL=index.d.ts.map
|