dsh-continual-evolve 0.2.0 → 0.4.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 (66) hide show
  1. package/README.md +83 -371
  2. package/README.zh.md +84 -235
  3. package/lib/apply.js +8 -2
  4. package/lib/approval.d.ts +6 -0
  5. package/lib/approval.js +9 -1
  6. package/lib/auto.d.ts +55 -4
  7. package/lib/auto.js +61 -5
  8. package/lib/benchmark-command.d.ts +9 -0
  9. package/lib/benchmark-command.js +333 -0
  10. package/lib/benchmark.d.ts +70 -0
  11. package/lib/benchmark.js +107 -1
  12. package/lib/command.d.ts +3 -0
  13. package/lib/command.js +62 -441
  14. package/lib/evaluate.d.ts +7 -0
  15. package/lib/evaluate.js +22 -7
  16. package/lib/evolve-event.d.ts +38 -0
  17. package/lib/evolve-event.js +49 -0
  18. package/lib/failures.d.ts +39 -0
  19. package/lib/failures.js +170 -0
  20. package/lib/fate.d.ts +5 -2
  21. package/lib/fate.js +13 -8
  22. package/lib/goal-command.d.ts +7 -0
  23. package/lib/goal-command.js +37 -0
  24. package/lib/index.d.ts +51 -25
  25. package/lib/index.js +33 -1
  26. package/lib/inject.d.ts +24 -1
  27. package/lib/inject.js +93 -5
  28. package/lib/llm-text.d.ts +30 -0
  29. package/lib/llm-text.js +49 -0
  30. package/lib/mount-command.d.ts +10 -0
  31. package/lib/mount-command.js +48 -0
  32. package/lib/plan.js +5 -0
  33. package/lib/planner.d.ts +1 -1
  34. package/lib/planner.js +13 -39
  35. package/lib/promotion.d.ts +62 -0
  36. package/lib/promotion.js +102 -0
  37. package/lib/render.d.ts +1 -3
  38. package/lib/render.js +0 -4
  39. package/lib/review.d.ts +4 -1
  40. package/lib/review.js +10 -38
  41. package/lib/rollback.d.ts +1 -3
  42. package/lib/rollback.js +0 -8
  43. package/lib/score.d.ts +15 -0
  44. package/lib/score.js +74 -5
  45. package/lib/service.d.ts +2 -2
  46. package/lib/service.js +7 -3
  47. package/lib/skill-render.d.ts +23 -0
  48. package/lib/skill-render.js +68 -0
  49. package/lib/skill.d.ts +2 -5
  50. package/lib/skill.js +2 -29
  51. package/lib/skillquality.d.ts +1 -2
  52. package/lib/skillquality.js +2 -2
  53. package/lib/state.js +6 -1
  54. package/lib/store.d.ts +1 -3
  55. package/lib/store.js +0 -7
  56. package/lib/tool.js +22 -1
  57. package/lib/types.d.ts +8 -0
  58. package/lib/usage.d.ts +45 -0
  59. package/lib/usage.js +115 -0
  60. package/lib/validate.d.ts +12 -2
  61. package/lib/validate.js +26 -1
  62. package/lib/wrapup-command.d.ts +9 -0
  63. package/lib/wrapup-command.js +212 -0
  64. package/lib/wrapup.d.ts +29 -15
  65. package/lib/wrapup.js +69 -42
  66. package/package.json +10 -8
package/lib/usage.js ADDED
@@ -0,0 +1,115 @@
1
+ /**
2
+ * Entry usage tracking (gap B1): records how many times each entry has been
3
+ * injected into system prompts. The counts are durable (persisted to disk)
4
+ * and exposed in `evolve_list` and the gate's archive-candidate reporting,
5
+ * so "zero-usage stale entries" can be surfaced for cleanup.
6
+ *
7
+ * Storage: `<baseDir>/evolve/usage.json` — a flat JSON object mapping
8
+ * `kind:id` to an integer count. Reads are tolerant of missing/corrupt files;
9
+ * writes are atomic (tmp + rename).
10
+ */
11
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
12
+ import { join } from "node:path";
13
+ const USAGE_FILE = "usage.json";
14
+ function usagePath(baseDir) {
15
+ return join(baseDir, "evolve", USAGE_FILE);
16
+ }
17
+ /**
18
+ * Load the usage store from disk; returns an empty store when absent or
19
+ * corrupt. Accepts BOTH on-disk shapes:
20
+ * - legacy (≤0.3.x): a flat `{ "kind:id": count }` map,
21
+ * - v2: `{ version: 2, counts, lastSession }` with per-session dedup.
22
+ */
23
+ export function loadUsage(baseDir) {
24
+ const path = usagePath(baseDir);
25
+ try {
26
+ if (!existsSync(path))
27
+ return { counts: {}, lastSession: {} };
28
+ const raw = JSON.parse(readFileSync(path, "utf8"));
29
+ if (typeof raw === "object" && raw !== null && !Array.isArray(raw)) {
30
+ const record = raw;
31
+ if (record["version"] === 2 && typeof record["counts"] === "object" && record["counts"] !== null) {
32
+ return {
33
+ counts: record["counts"],
34
+ lastSession: typeof record["lastSession"] === "object" && record["lastSession"] !== null
35
+ ? record["lastSession"]
36
+ : {},
37
+ };
38
+ }
39
+ // Legacy flat map: every key is a count.
40
+ return { counts: raw, lastSession: {} };
41
+ }
42
+ return { counts: {}, lastSession: {} };
43
+ }
44
+ catch {
45
+ return { counts: {}, lastSession: {} };
46
+ }
47
+ }
48
+ /** Persist the usage store atomically (always the v2 shape). */
49
+ export function saveUsage(baseDir, store) {
50
+ const dir = join(baseDir, "evolve");
51
+ mkdirSync(dir, { recursive: true });
52
+ const path = usagePath(baseDir);
53
+ const tmp = `${path}.${process.pid}.tmp`;
54
+ writeFileSync(tmp, `${JSON.stringify({ version: 2, counts: store.counts, lastSession: store.lastSession ?? {} }, null, 2)}\n`, "utf8");
55
+ renameSync(tmp, path);
56
+ }
57
+ /** Build the usage key for an entry. */
58
+ export function usageKey(kind, id) {
59
+ return `${kind}:${id}`;
60
+ }
61
+ /**
62
+ * Increment injection counts for the entries that were actually injected.
63
+ * Called after `entriesSectionText` renders the injected block. Keys not
64
+ * present in the store are initialized to 1.
65
+ *
66
+ * Session dedup (2026-08-22): with a sessionId, each key counts AT MOST
67
+ * ONCE per session — the old per-build counting produced meaningless
68
+ * numbers (one entry hit 2311× in a week) and hid the real "how many
69
+ * sessions found this useful" signal that staleness decay needs. Without
70
+ * a sessionId the call degrades to legacy always-increment behavior.
71
+ */
72
+ export function recordInjection(baseDir, injectedKeys, sessionId) {
73
+ if (injectedKeys.length === 0)
74
+ return;
75
+ const store = loadUsage(baseDir);
76
+ let dirty = false;
77
+ for (const key of injectedKeys) {
78
+ if (sessionId !== undefined && store.lastSession?.[key] === sessionId) {
79
+ continue;
80
+ }
81
+ store.counts[key] = (store.counts[key] ?? 0) + 1;
82
+ if (store.lastSession && sessionId !== undefined) {
83
+ store.lastSession[key] = sessionId;
84
+ }
85
+ dirty = true;
86
+ }
87
+ if (dirty) {
88
+ saveUsage(baseDir, store);
89
+ }
90
+ }
91
+ /**
92
+ * Get the injection count for a specific entry. Returns 0 when the entry
93
+ * has never been injected (absent from the store).
94
+ */
95
+ export function getUsageCount(store, kind, id) {
96
+ return store.counts[usageKey(kind, id)] ?? 0;
97
+ }
98
+ /**
99
+ * Find entries with zero injection usage. Returns `{kind, id, title}` for
100
+ * each entry that has never been injected — prime candidates for archival.
101
+ */
102
+ export function zeroUsageEntries(state, store) {
103
+ const results = [];
104
+ for (const kind of Object.keys(state.entries)) {
105
+ for (const entry of Object.values(state.entries[kind])) {
106
+ if (entry.scope !== "local")
107
+ continue;
108
+ if (getUsageCount(store, kind, entry.id) === 0) {
109
+ results.push({ kind, id: entry.id, title: entry.title });
110
+ }
111
+ }
112
+ }
113
+ return results;
114
+ }
115
+ //# sourceMappingURL=usage.js.map
package/lib/validate.d.ts CHANGED
@@ -4,8 +4,18 @@
4
4
  * the base system prompt, required fields per action, and the executable
5
5
  * contract skill entries must carry.
6
6
  */
7
- import type { RefinementEdit } from "./types.js";
7
+ import type { HarnessScope, RefinementEdit } from "./types.js";
8
8
  export declare const BASE_SYSTEM_PROMPT_ID = "base_system_prompt";
9
+ /**
10
+ * Gap C2: mechanical check that an edit's declared blast radius is coherent
11
+ * with the scope it targets. A session-scoped edit claiming "general" would
12
+ * silently read like a cross-project tactical rule; a global edit claiming
13
+ * "session" would contradict its persistence. Absent blastRadius is NOT
14
+ * rejected (pre-C2 data and manual edits stay compatible) — the planner is
15
+ * instructed to always declare it, and this rule catches what it declares
16
+ * incoherently.
17
+ */
18
+ export declare function validateBlastRadiusScope(scope: HarnessScope, blastRadius: "general" | "project" | "session"): string | undefined;
9
19
  /** Returns a human-readable failure reason, or undefined when the edit passes. */
10
- export declare function validateEdit(edit: RefinementEdit, computedId: string | undefined): string | undefined;
20
+ export declare function validateEdit(edit: RefinementEdit, computedId: string | undefined, scope?: HarnessScope): string | undefined;
11
21
  //# sourceMappingURL=validate.d.ts.map
package/lib/validate.js CHANGED
@@ -2,8 +2,26 @@ import { validateSkillEntryContent } from "./skillquality.js";
2
2
  const ACTIONS = new Set(["create", "update", "delete", "archive"]);
3
3
  const KINDS = new Set(["prompt", "memory", "skill", "subagent"]);
4
4
  export const BASE_SYSTEM_PROMPT_ID = "base_system_prompt";
5
+ /**
6
+ * Gap C2: mechanical check that an edit's declared blast radius is coherent
7
+ * with the scope it targets. A session-scoped edit claiming "general" would
8
+ * silently read like a cross-project tactical rule; a global edit claiming
9
+ * "session" would contradict its persistence. Absent blastRadius is NOT
10
+ * rejected (pre-C2 data and manual edits stay compatible) — the planner is
11
+ * instructed to always declare it, and this rule catches what it declares
12
+ * incoherently.
13
+ */
14
+ export function validateBlastRadiusScope(scope, blastRadius) {
15
+ if (scope === "local" && blastRadius === "general") {
16
+ return "local-scope edit must declare blastRadius \"session\" or \"project\" (\"general\" would claim a cross-project rule)";
17
+ }
18
+ if (scope === "global" && blastRadius === "session") {
19
+ return "global-scope edit must declare blastRadius \"general\" or \"project\" (\"session\" contradicts cross-session persistence)";
20
+ }
21
+ return undefined;
22
+ }
5
23
  /** Returns a human-readable failure reason, or undefined when the edit passes. */
6
- export function validateEdit(edit, computedId) {
24
+ export function validateEdit(edit, computedId, scope) {
7
25
  if (!ACTIONS.has(edit.action)) {
8
26
  return `unsupported action ${String(edit.action)}`;
9
27
  }
@@ -16,6 +34,13 @@ export function validateEdit(edit, computedId) {
16
34
  if (edit.action !== "create" && !edit.id) {
17
35
  return `${edit.action} requires id`;
18
36
  }
37
+ // Gap C2: blast-radius/scope coherence is a mechanical property of the
38
+ // edit payload itself — checked for every action, not only create/update.
39
+ if (scope && edit.blastRadius !== undefined) {
40
+ const blastError = validateBlastRadiusScope(scope, edit.blastRadius);
41
+ if (blastError)
42
+ return blastError;
43
+ }
19
44
  // Archive only names an existing entry: no title/content payload, and the
20
45
  // base system prompt stays immutable under every action.
21
46
  if (edit.action === "archive") {
@@ -0,0 +1,9 @@
1
+ /**
2
+ * The `/evolve wrapup` subcommand handler. Extracted from command.ts (P2-2).
3
+ */
4
+ import type { Context } from "@deepseek-ai/cordis";
5
+ import type { CommandInvocation, CommandResult } from "@deepseek-ai/dsh-commands";
6
+ import type { EvolutionEngine } from "./service.js";
7
+ import { type PromotionPolicy } from "./promotion.js";
8
+ export declare function executeWrapupCommand(ctx: Context, engine: EvolutionEngine, invocation: CommandInvocation, policy?: PromotionPolicy): Promise<CommandResult>;
9
+ //# sourceMappingURL=wrapup-command.d.ts.map
@@ -0,0 +1,212 @@
1
+ import { questionServiceOf, requireGlobalApproval } from "./approval.js";
2
+ import { assessLocalEntries, candidateKey, filterPromotable, listLocalCandidates, splitArchiveGuards, splitPromoteBlocked, splitPromoteProposals, wholePromoteProposals } from "./wrapup.js";
3
+ import { DEFAULT_PROMOTION_POLICY } from "./promotion.js";
4
+ function success(text) {
5
+ return { kind: "success", text };
6
+ }
7
+ export async function executeWrapupCommand(ctx, engine, invocation, policy = DEFAULT_PROMOTION_POLICY) {
8
+ const sessionId = invocation.agent.id;
9
+ const localState = engine.load("local", sessionId);
10
+ const globalState = engine.load("global", undefined);
11
+ const candidates = listLocalCandidates(localState, globalState, engine.baseDir);
12
+ if (candidates.length === 0) {
13
+ return success(`(nothing to wrap up: ${sessionId}'s local store has no active, un-promoted entries — use /evolve list to inspect it)`);
14
+ }
15
+ // 1. Classify: the model judges each audited candidate's fate.
16
+ const assessment = await assessLocalEntries(ctx, invocation.agent, candidates, { signal: invocation.signal });
17
+ const byKey = new Map(candidates.map((candidate) => [candidateKey(candidate.kind, candidate.id), candidate]));
18
+ // 2. Partition by action. Deterministic guards re-check the LIVE global
19
+ // store right before anything lands (state may have changed mid-call).
20
+ const { promotable, skipped } = filterPromotable(assessment.items, globalState, candidates, policy);
21
+ const promoteItems = promotable.filter((item) => item.verdict === "promote");
22
+ const archiveItems = assessment.items.filter((item) => item.verdict === "archive");
23
+ // Split promotion (A-form): archive a mixed entry but promote ONLY the
24
+ // cleaned durable part the model extracted. Guarded the same way as whole
25
+ // promotes — a split that would duplicate a globally covered topic is
26
+ // dropped and the entry archives plain.
27
+ const splitItems = [];
28
+ const splitSkipped = [];
29
+ for (const item of archiveItems) {
30
+ if (!item.promote)
31
+ continue;
32
+ const candidate = byKey.get(item.key);
33
+ if (!candidate) {
34
+ splitSkipped.push({ key: item.key, reason: "not in the audited candidate list" });
35
+ continue;
36
+ }
37
+ const blocked = splitPromoteBlocked(item, globalState, candidate.kind, policy);
38
+ if (blocked) {
39
+ splitSkipped.push({ key: item.key, reason: blocked });
40
+ continue;
41
+ }
42
+ splitItems.push({ item, candidate });
43
+ }
44
+ // Plain archives (no split payload): the symmetric guard — an archive that
45
+ // is NOT globally covered AND was distilled from real user messages must
46
+ // not proceed silently.
47
+ const plainArchives = archiveItems.filter((item) => !item.promote);
48
+ const { silent: silentArchives, review: reviewArchives } = splitArchiveGuards(plainArchives, candidates);
49
+ const keepItems = assessment.items.filter((item) => item.verdict === "keep");
50
+ // 3. Report the assessment before touching anything.
51
+ const lines = [
52
+ `wrapup assessment (${sessionId}): ${candidates.length} candidates${candidates.some((c) => c.coveredGlobally) ? `, ${candidates.filter((c) => c.coveredGlobally).length} covered globally` : ""}`,
53
+ `${assessment.rationale}`,
54
+ ];
55
+ for (const [heading, items] of [
56
+ ["PROMOTE (to global)", promoteItems],
57
+ ["SPLIT (archive + promote durable part)", splitItems.map((split) => split.item)],
58
+ ["ARCHIVE", silentArchives],
59
+ ["ARCHIVE (needs review)", reviewArchives],
60
+ ["KEEP", keepItems],
61
+ ]) {
62
+ lines.push(`${heading}: ${items.length}`);
63
+ for (const item of items) {
64
+ const candidate = byKey.get(item.key);
65
+ const title = candidate ? candidate.title : item.key;
66
+ const splitNote = item.promote ? ` → 拆出提升「${item.promote.title}」` : "";
67
+ lines.push(`- ${item.key} "${title}"${splitNote} — ${item.reason}`);
68
+ }
69
+ }
70
+ for (const skip of skipped) {
71
+ lines.push(`- promote skipped: ${skip.key} — ${skip.reason}`);
72
+ }
73
+ for (const skip of splitSkipped) {
74
+ lines.push(`- split skipped: ${skip.key} — ${skip.reason}`);
75
+ }
76
+ lines.push("");
77
+ const applied = [];
78
+ // 4. Global writes: governed resource — ONE human approval gate covers
79
+ // every create (whole promotes AND split promotions). On approval:
80
+ // - whole promote → create global copy + stamp local promotedTo+archivedAt;
81
+ // - split → create the cleaned durable part + archive the original with
82
+ // promotedTo. On rejection: whole promotes are not written, and each
83
+ // split's original STILL archives plain (its snapshot half deserves
84
+ // the archive; the durable half is reported for manual handling).
85
+ const wholeCreates = promoteItems.map((item) => ({ item, candidate: byKey.get(item.key) }));
86
+ const splitCreates = splitItems;
87
+ const allCreates = new Set([...wholeCreates.map((c) => c.item.key), ...splitCreates.map((c) => c.item.key)]);
88
+ if (allCreates.size > 0) {
89
+ const what = `wrapup 将写入跨会话 global store(共 ${allCreates.size} 条:${promoteItems.length} 条整条提升 + ${splitItems.length} 条拆解提升):\n${[
90
+ ...promoteItems.map((item) => `- 整条提升 ${item.key} "${byKey.get(item.key)?.title ?? item.key}"`),
91
+ ...splitItems.map((split) => `- 拆解提升 ${split.item.key} → 清洗「${split.item.promote?.title}」(原条目随之归档)`),
92
+ ].join("\n")}`;
93
+ let promoteAllowed = true;
94
+ try {
95
+ await requireGlobalApproval(ctx, invocation.agent, invocation.signal, what);
96
+ }
97
+ catch (cause) {
98
+ promoteAllowed = false;
99
+ const message = `global 写入未批准 — 整条提升与拆解提升均未写入 (${cause instanceof Error ? cause.message : String(cause)})`;
100
+ applied.push(message);
101
+ lines.push(message);
102
+ }
103
+ if (promoteAllowed) {
104
+ // Whole promotes: create global entry, retire the local copy.
105
+ // Shared proposal builders keep the wrap-up command and the gate's
106
+ // local-fate dimension writing IDENTICAL edits.
107
+ for (const { item, candidate } of wholeCreates) {
108
+ if (!candidate)
109
+ continue;
110
+ const proposals = wholePromoteProposals(item, candidate, sessionId);
111
+ const globalResult = engine.apply("global", undefined, proposals.global, { scope: "global" });
112
+ const createdId = globalResult.appliedEdits.find((edit) => edit.applied)?.id ?? candidate.id;
113
+ const localResult = engine.apply("local", sessionId, proposals.localStamp(createdId), {
114
+ scope: "local",
115
+ baselineState: localState,
116
+ });
117
+ applied.push(`promoted ${item.key} → global:${createdId} (${globalResult.id}; local stamped ${localResult.id})`);
118
+ }
119
+ // Split promotions: create the cleaned durable part, retire the
120
+ // original local entry (its snapshot half is archived along).
121
+ for (const { item, candidate } of splitCreates) {
122
+ if (!item.promote)
123
+ continue;
124
+ const proposals = splitPromoteProposals(item, candidate, sessionId);
125
+ const globalResult = engine.apply("global", undefined, proposals.global, { scope: "global" });
126
+ const createdId = globalResult.appliedEdits.find((edit) => edit.applied)?.id ?? candidate.id;
127
+ const localResult = engine.apply("local", sessionId, proposals.localStamp(createdId), {
128
+ scope: "local",
129
+ baselineState: localState,
130
+ });
131
+ applied.push(`split ${item.key}: promoted cleaned part → global:${createdId} (${globalResult.id}); original archived (${localResult.id})`);
132
+ }
133
+ }
134
+ else {
135
+ // Rejected: whole promotes stay un-written; each split's original
136
+ // still archives plain (reported, data restorable).
137
+ for (const { item, candidate } of splitCreates) {
138
+ if (!candidate)
139
+ continue;
140
+ const result = engine.apply("local", sessionId, {
141
+ summary: `wrapup: split promotion not approved — archive original ${item.key} plain`,
142
+ rationale: item.reason,
143
+ expectedOutcome: `The original leaves injection; the cleaned part was NOT written (reported for manual handling).`,
144
+ edits: [{ action: "archive", kind: candidate.kind, id: candidate.id }],
145
+ }, { scope: "local", baselineState: localState });
146
+ applied.push(`split ${item.key}: promotion not approved — original archived plain (${result.id})`);
147
+ }
148
+ }
149
+ }
150
+ // 5. Silent archives: deterministic local action (hidden from injection,
151
+ // data kept restorable) — covered topics and operational entries need no
152
+ // confirmation, matching the original behavior.
153
+ for (const item of silentArchives) {
154
+ const candidate = byKey.get(item.key);
155
+ if (!candidate)
156
+ continue;
157
+ const result = engine.apply("local", sessionId, {
158
+ summary: `wrapup: archive local ${item.key} — ${item.reason}`,
159
+ rationale: item.reason,
160
+ expectedOutcome: `The entry stops being injected but stays restorable.`,
161
+ edits: [{ action: "archive", kind: candidate.kind, id: candidate.id }],
162
+ }, { scope: "local", baselineState: localState });
163
+ applied.push(`archived ${item.key} (${result.id})`);
164
+ }
165
+ // 6. Review archives (symmetric guard): not covered globally + distilled
166
+ // from real user messages — the user decides before this content is
167
+ // hidden from future sessions. No question service → conservative keep.
168
+ const userQuestions = questionServiceOf(ctx);
169
+ for (const item of reviewArchives) {
170
+ const candidate = byKey.get(item.key);
171
+ if (!candidate)
172
+ continue;
173
+ if (!userQuestions) {
174
+ applied.push(`kept ${item.key} — archive pending user confirmation (no question service)`);
175
+ continue;
176
+ }
177
+ const questionId = "evolve-wrapup-archive-review";
178
+ let archiveConfirmed = false;
179
+ try {
180
+ const answer = await userQuestions.ask({
181
+ questions: [
182
+ {
183
+ id: questionId,
184
+ question: `wrapup:条目「${candidate.title}」未被全局覆盖且源自真实对话,直接归档会隐藏它(数据保留、可恢复)。确认归档?`,
185
+ options: [{ label: "归档" }, { label: "保留" }],
186
+ },
187
+ ],
188
+ agent: invocation.agent,
189
+ signal: invocation.signal,
190
+ });
191
+ archiveConfirmed = answer.answers?.find((entry) => entry.id === questionId)?.selected?.includes("归档") ?? false;
192
+ }
193
+ catch {
194
+ archiveConfirmed = false;
195
+ }
196
+ if (archiveConfirmed) {
197
+ const result = engine.apply("local", sessionId, {
198
+ summary: `wrapup: archive local ${item.key} (user-confirmed) — ${item.reason}`,
199
+ rationale: item.reason,
200
+ expectedOutcome: `The entry stops being injected but stays restorable.`,
201
+ edits: [{ action: "archive", kind: candidate.kind, id: candidate.id }],
202
+ }, { scope: "local", baselineState: localState });
203
+ applied.push(`archived ${item.key} (user-confirmed, ${result.id})`);
204
+ }
205
+ else {
206
+ applied.push(`kept ${item.key} — user declined the archive`);
207
+ }
208
+ }
209
+ lines.push(...(applied.length > 0 ? applied : ["(no changes applied — all entries kept)"]));
210
+ return success(lines.join("\n"));
211
+ }
212
+ //# sourceMappingURL=wrapup-command.js.map
package/lib/wrapup.d.ts CHANGED
@@ -21,6 +21,7 @@
21
21
  import type { Context } from "@deepseek-ai/cordis";
22
22
  import type { Agent } from "@deepseek-ai/dsh-agent";
23
23
  import type { HarnessEntry, HarnessState, RefinementKind, RefinementProposal } from "./types.js";
24
+ import { type PromotionPolicy } from "./promotion.js";
24
25
  /** What should happen to one local entry at session end. */
25
26
  export type WrapupVerdict = "promote" | "archive" | "keep";
26
27
  /** A classified local entry: `key` matches one audited candidate exactly. */
@@ -74,6 +75,18 @@ export interface WrapupCandidate {
74
75
  * really covers the local content.
75
76
  */
76
77
  globalHints: GlobalHint[];
78
+ /**
79
+ * Injection usage count (gap B1): how many times this entry was included
80
+ * in a system-prompt assembly. Zero means the entry was never used — a
81
+ * strong staleness signal the assessor can weigh.
82
+ */
83
+ injectionCount: number;
84
+ /**
85
+ * Staleness flag (gap B2): true when the entry has both zero injection
86
+ * usage AND a recency score below the staleness threshold (old + unused).
87
+ * The assessor is instructed to prefer "archive" for stale entries.
88
+ */
89
+ stale: boolean;
77
90
  }
78
91
  export declare function candidateKey(kind: RefinementKind, id: string): string;
79
92
  /**
@@ -100,14 +113,7 @@ export declare function globalCoverageDetected(globalState: HarnessState, kind:
100
113
  * bare boolean. Bounded: a handful of best matches, never the whole store.
101
114
  */
102
115
  export declare function globalHintsFor(globalState: HarnessState, kind: RefinementKind, entry: Pick<HarnessEntry, "id" | "title">): GlobalHint[];
103
- /**
104
- * The auditable local candidates of a session: every non-archived local
105
- * entry that has not already been promoted (a promoted entry's lifecycle is
106
- * finished — the global copy is the live one). Each carries its
107
- * `coveredGlobally` flag so the assessor never wastes a promote on a topic
108
- * the global store already owns.
109
- */
110
- export declare function listLocalCandidates(state: HarnessState, globalState: HarnessState): WrapupCandidate[];
116
+ export declare function listLocalCandidates(state: HarnessState, globalState: HarnessState, baseDir?: string): WrapupCandidate[];
111
117
  /**
112
118
  * Parse and validate the model's assessment JSON. Defense is mechanical:
113
119
  * keys outside the candidate list are dropped, verdicts outside the enum
@@ -133,9 +139,16 @@ export interface PromotableSplit {
133
139
  * Apply-time deterministic guard: re-check every promote verdict against the
134
140
  * global store right before it lands. The LLM classification may be stale
135
141
  * (a gate ran while assessing) or wrong; this ensures a promote never writes
136
- * a duplicate global entry. Pure and unit-tested.
142
+ * a duplicate, project-scoped, or too-thin global entry. Pure and unit-tested.
143
+ *
144
+ * Guards (2026-08-22 promotion policy):
145
+ * - audited candidate list + title coverage (pre-existing),
146
+ * - project-scoped content markers (absolute paths / session ids) — the
147
+ * global store is shared across projects and must stay portable,
148
+ * - thin content below the policy floor (framing outweighs the fact),
149
+ * - near-duplicate of an existing global entry by content overlap.
137
150
  */
138
- export declare function filterPromotable(items: readonly WrapupItem[], globalState: HarnessState, candidates: readonly WrapupCandidate[]): PromotableSplit;
151
+ export declare function filterPromotable(items: readonly WrapupItem[], globalState: HarnessState, candidates: readonly WrapupCandidate[], policy?: PromotionPolicy): PromotableSplit;
139
152
  export interface ArchiveReviewSplit {
140
153
  /** Archives that may proceed silently: topic already covered, no real
141
154
  * distillation source, or the archive half of an already-approved split. */
@@ -166,11 +179,12 @@ export declare function needsArchiveReview(item: WrapupItem, candidate: WrapupCa
166
179
  export declare function splitArchiveGuards(items: readonly WrapupItem[], candidates: readonly WrapupCandidate[]): ArchiveReviewSplit;
167
180
  /**
168
181
  * Apply-time guard for a split promotion (archive + promote sub-object):
169
- * the cleaned title must not duplicate a topic already covered globally. A
170
- * duplicate split is dropped (the entry still archives plain) rather than
171
- * half-promoting a redundancy.
182
+ * the cleaned payload must pass the same promotion policy as a whole
183
+ * promote no global coverage duplicate, no project-scoped content, not
184
+ * too thin, no near-duplicate global entry. A blocked split is dropped (the
185
+ * entry still archives plain) rather than half-promoting a redundancy.
172
186
  */
173
- export declare function splitPromoteBlocked(item: WrapupItem, globalState: HarnessState, kind: RefinementKind): string | undefined;
187
+ export declare function splitPromoteBlocked(item: WrapupItem, globalState: HarnessState, kind: RefinementKind, policy?: PromotionPolicy): string | undefined;
174
188
  /**
175
189
  * Shared proposal builders for a WHOLE promotion — used by both the
176
190
  * `/evolve wrapup` command and the gate's local-fate dimension so the two
@@ -194,7 +208,7 @@ export declare function splitPromoteProposals(item: WrapupItem, candidate: Wrapu
194
208
  global: RefinementProposal;
195
209
  localStamp: (createdId: string) => RefinementProposal;
196
210
  };
197
- export declare const WRAPUP_ASSESS_SYSTEM_PROMPT = "You are the /evolve session wrap-up assessor.\n\nA session is ending and its local harness entries need a fate. Classify each\nlisted entry exactly once:\n\n- \"promote\" \u2014 the content is a stable, durable, CROSS-SESSION reusable lesson:\n a durable user preference, a project-level fact or convention, a reusable\n procedure or skill. Future sessions would benefit from seeing it.\n- \"archive\" \u2014 the content is session-specific task progress, one-off noise,\n superseded or obsolete, or already covered by the global store (note\n \"covered globally\" in the reason).\n- \"keep\" \u2014 still actively useful to this session, or genuinely uncertain.\n\nRules:\n- When an entry is marked \"covered globally\" in the listing, prefer \"archive\"\n or \"keep\" over \"promote\" \u2014 promoting a duplicate gains nothing.\n- Do not promote local task state, work-in-progress notes, or content tied to\n one session's ephemeral details.\n- Skills: only \"promote\" a skill entry that is a genuinely reusable procedure\n meeting the DSH skill quality standard; one-off workflows are \"archive\" or\n \"keep\".\n- SPLIT PROMOTION: when an entry mixes a stable, cross-session-reusable part\n WITH session-specific snapshot details, do NOT promote it whole. Instead\n give verdict \"archive\" WITH a \"promote\" sub-object holding a CLEANED\n version of only the durable part (a stable title + the persistent facts,\n stripped of dates/states/one-off figures). Ephemeral snapshot content stays\n out of the sub-object \u2014 it is left behind in the archive. A sub-object is\n only meaningful on \"archive\" verdicts.\n\nReturn JSON only:\n{\n \"rationale\": \"one or two sentences\",\n \"items\": [\n {\"key\": \"memory:foo\", \"verdict\": \"promote|archive|keep\", \"reason\": \"why\"},\n {\"key\": \"memory:bar\", \"verdict\": \"archive\", \"reason\": \"why\",\n \"promote\": {\"title\": \"cleaned stable title\", \"content\": \"cleaned durable part only\"}}\n ]\n}\nOnly keys from the provided list are allowed; any entry you omit defaults to \"keep\".";
211
+ export declare const WRAPUP_ASSESS_SYSTEM_PROMPT = "You are the /evolve session wrap-up assessor.\n\nA session is ending and its local harness entries need a fate. Classify each\nlisted entry exactly once:\n\n- \"promote\" \u2014 the content is a stable, durable, CROSS-SESSION reusable lesson:\n a durable user preference, a project-level fact or convention, a reusable\n procedure or skill. Future sessions would benefit from seeing it.\n- \"archive\" \u2014 the content is session-specific task progress, one-off noise,\n superseded or obsolete, or already covered by the global store (note\n \"covered globally\" in the reason), or stale (old + never injected \u2014 note\n \"stale (injectionCount=0, recency low)\" in the reason).\n- \"keep\" \u2014 still actively useful to this session, or genuinely uncertain.\n\nRules:\n- When an entry is marked \"covered globally\" in the listing, prefer \"archive\"\n or \"keep\" over \"promote\" \u2014 promoting a duplicate gains nothing.\n- When an entry is marked \"stale\" (injectionCount=0 and low recency), prefer\n \"archive\" \u2014 the entry has never been used and is old, so it is unlikely to\n be needed again. Only \"keep\" if the content is clearly valuable despite low\n usage (e.g. a safety policy that rarely triggers but is critical).\n- Do not promote local task state, work-in-progress notes, or content tied to\n one session's ephemeral details.\n- Skills: only \"promote\" a skill entry that is a genuinely reusable procedure\n meeting the DSH skill quality standard; one-off workflows are \"archive\" or\n \"keep\".\n- SPLIT PROMOTION: when an entry mixes a stable, cross-session-reusable part\n WITH session-specific snapshot details, do NOT promote it whole. Instead\n give verdict \"archive\" WITH a \"promote\" sub-object holding a CLEANED\n version of only the durable part (a stable title + the persistent facts,\n stripped of dates/states/one-off figures). Ephemeral snapshot content stays\n out of the sub-object \u2014 it is left behind in the archive. A sub-object is\n only meaningful on \"archive\" verdicts.\n\nReturn JSON only:\n{\n \"rationale\": \"one or two sentences\",\n \"items\": [\n {\"key\": \"memory:foo\", \"verdict\": \"promote|archive|keep\", \"reason\": \"why\"},\n {\"key\": \"memory:bar\", \"verdict\": \"archive\", \"reason\": \"why\",\n \"promote\": {\"title\": \"cleaned stable title\", \"content\": \"cleaned durable part only\"}}\n ]\n}\nOnly keys from the provided list are allowed; any entry you omit defaults to \"keep\".";
198
212
  export interface AssessOptions {
199
213
  /** Output token budget for the assessment call. */
200
214
  maxOutputTokens?: number;