dsh-continual-evolve 0.6.1 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/store.js CHANGED
@@ -4,20 +4,49 @@
4
4
  * Layout (self-contained under the DSH home; no dependency on session
5
5
  * persistence internals):
6
6
  *
7
- * <dshHome>/evolve/global/harness_state.json cross-session store
7
+ * <dshHome>/evolve/global/harness_state.json cross-project store
8
8
  * <dshHome>/evolve/global/refinements.jsonl applied results (rollback source)
9
- * <dshHome>/evolve/local/<sessionId>/... per-session store
9
+ * <dshHome>/evolve/projects/<slug-hash>/... per-project store
10
+ * <dshHome>/evolve/local/<sessionId>/... per-session staging store
10
11
  *
11
12
  * Snapshot discipline is code-enforced: before any mutating apply, the
12
13
  * pre-apply state is copied to `snapshots/<refinementId>.json`. The model has
13
14
  * no way to skip it — it runs inside the service, not in a prompt.
14
15
  */
15
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
16
+ import { existsSync, mkdirSync, readFileSync, readdirSync, statSync, unlinkSync, writeFileSync } from "node:fs";
16
17
  import { join } from "node:path";
18
+ import { sanitizeProjectKey } from "./project.js";
17
19
  import { stateFilePath } from "./state.js";
18
20
  export const EVOLVE_DIR = "evolve";
21
+ /**
22
+ * Storage-hygiene defaults (#20): history used to grow append-only without
23
+ * bound (dozens of full-state snapshot copies, unbounded JSONL). Retention
24
+ * is count-based and generous — rollback only ever needs recent snapshots
25
+ * and readers (`failures.ts` over reviews) need a working window, not the
26
+ * full past. Tunable via the `historyRetain` plugin config.
27
+ */
28
+ export const DEFAULT_SNAPSHOT_RETAIN = 20;
29
+ export const DEFAULT_REFINEMENTS_RETAIN = 500;
30
+ export const DEFAULT_REVIEWS_RETAIN = 500;
31
+ export const DEFAULT_TOKEN_USAGE_RETAIN = 500;
32
+ /** Defaults applied for absent / non-positive retention fields (fail loud never: clamp, don't throw). */
33
+ export function resolveHistoryRetention(raw) {
34
+ const pick = (value, fallback) => typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.floor(value) : fallback;
35
+ return {
36
+ snapshots: pick(raw?.snapshots, DEFAULT_SNAPSHOT_RETAIN),
37
+ refinements: pick(raw?.refinements, DEFAULT_REFINEMENTS_RETAIN),
38
+ reviews: pick(raw?.reviews, DEFAULT_REVIEWS_RETAIN),
39
+ tokenUsage: pick(raw?.tokenUsage, DEFAULT_TOKEN_USAGE_RETAIN),
40
+ };
41
+ }
42
+ /**
43
+ * Resolve store paths for a scope. For `project` the `sessionId` parameter
44
+ * carries the project key (see {@link resolveProjectKey} in project.ts) —
45
+ * it is sanitized to a single path segment so an externally supplied key
46
+ * can never traverse out of `evolve/projects/`.
47
+ */
19
48
  export function storePaths(baseDir, scope, sessionId) {
20
- const scopeDir = scope === "global" ? "global" : join("local", sessionId ?? "anonymous");
49
+ const scopeDir = scope === "global" ? "global" : scope === "project" ? join("projects", sanitizeProjectKey(sessionId ?? "project")) : join("local", sessionId ?? "anonymous");
21
50
  const stateDir = join(baseDir, EVOLVE_DIR, scopeDir);
22
51
  return {
23
52
  stateDir,
@@ -41,6 +70,72 @@ export function appendResult(paths, result) {
41
70
  mkdirSync(paths.stateDir, { recursive: true });
42
71
  writeFileSync(paths.resultsPath, `${JSON.stringify(result)}\n`, { encoding: "utf8", flag: "a" });
43
72
  }
73
+ /**
74
+ * Prune a store's snapshots to the newest `retain` files (by mtime, oldest
75
+ * first). Best-effort: a missing directory or an unlink failure never breaks
76
+ * the apply path — the next apply retries.
77
+ */
78
+ export function pruneSnapshots(snapshotsDir, retain) {
79
+ const keep = Math.floor(retain);
80
+ if (!(keep > 0) || !existsSync(snapshotsDir))
81
+ return;
82
+ let files;
83
+ try {
84
+ files = readdirSync(snapshotsDir).filter((f) => f.endsWith(".json"));
85
+ }
86
+ catch {
87
+ return; // unreadable directory — leave it for the next attempt
88
+ }
89
+ if (files.length <= keep)
90
+ return;
91
+ const withTime = [];
92
+ for (const file of files) {
93
+ try {
94
+ withTime.push({ file, mtime: statSync(join(snapshotsDir, file)).mtimeMs });
95
+ }
96
+ catch {
97
+ // unstatable file — keep it rather than delete blindly
98
+ }
99
+ }
100
+ withTime.sort((a, b) => a.mtime - b.mtime);
101
+ for (const victim of withTime.slice(0, Math.max(0, withTime.length - keep))) {
102
+ try {
103
+ unlinkSync(join(snapshotsDir, victim.file));
104
+ }
105
+ catch {
106
+ // one bad unlink must not stop the sweep or the apply path
107
+ }
108
+ }
109
+ }
110
+ /**
111
+ * Truncate a JSONL file to its last `retain` non-empty lines. No-op when the
112
+ * file is missing or already within budget — the common case costs one
113
+ * read and no write.
114
+ */
115
+ export function pruneJsonlFile(path, retain) {
116
+ const keep = Math.floor(retain);
117
+ if (!(keep > 0) || !existsSync(path))
118
+ return;
119
+ let lines;
120
+ try {
121
+ lines = readFileSync(path, "utf8").split("\n").filter((l) => l.trim().length > 0);
122
+ }
123
+ catch {
124
+ return; // unreadable file — leave it for the next attempt
125
+ }
126
+ if (lines.length <= keep)
127
+ return;
128
+ try {
129
+ writeFileSync(path, `${lines.slice(-keep).join("\n")}\n`, "utf8");
130
+ }
131
+ catch {
132
+ // truncation failure must not break the write path that called it
133
+ }
134
+ }
135
+ /** Reviews audit-trail path shared by the gate, fate, and tool events. */
136
+ export function reviewsPath(baseDir) {
137
+ return join(baseDir, EVOLVE_DIR, "reviews.jsonl");
138
+ }
44
139
  /** Read the applied results history; malformed lines are skipped, never fatal. */
45
140
  export function loadResults(paths) {
46
141
  if (!existsSync(paths.resultsPath)) {
@@ -0,0 +1,68 @@
1
+ import type { TokenUsage } from "@deepseek-ai/dsh-llm";
2
+ import type { StreamTextObservation, StreamTextUsageObserver } from "./llm-text.js";
3
+ export declare const TOKEN_USAGE_LEDGER_VERSION = 1;
4
+ /** Plugin-owned direct call paths represented in the ledger. */
5
+ export declare const TOKEN_USAGE_PHASES: readonly ["review", "planner", "wrapup", "fate"];
6
+ export type TokenUsagePhase = (typeof TOKEN_USAGE_PHASES)[number];
7
+ /** Whether the provider supplied a usage sample; missing is never treated as zero. */
8
+ export type TokenUsageStatus = "reported" | "missing";
9
+ /** How the exact full-call total was obtained. */
10
+ export type TokenTotalSource = "provider" | "derived" | "unavailable";
11
+ /** One retained direct-call observation. */
12
+ export interface TokenUsageRecord {
13
+ version: typeof TOKEN_USAGE_LEDGER_VERSION;
14
+ timestamp: string;
15
+ sessionId: string;
16
+ phase: TokenUsagePhase;
17
+ provider: string;
18
+ model: string;
19
+ outcome: StreamTextObservation["outcome"];
20
+ usageStatus: TokenUsageStatus;
21
+ /** Absent exactly when {@link usageStatus} is `missing`. */
22
+ usage?: TokenUsage;
23
+ totalSource: TokenTotalSource;
24
+ }
25
+ /** Caller-owned destination and failure hook; phase/provider/model are supplied by the call site. */
26
+ export interface TokenUsageTarget {
27
+ baseDir: string;
28
+ sessionId: string;
29
+ retain: number;
30
+ onError?: (cause: unknown) => void;
31
+ }
32
+ /** Loaded retained window plus corrupt-line count for honest coverage reporting. */
33
+ export interface LoadedTokenUsage {
34
+ records: TokenUsageRecord[];
35
+ corruptLines: number;
36
+ }
37
+ /** Aggregate provider-reported buckets over a retained ledger window. */
38
+ export interface TokenUsageTotals {
39
+ calls: number;
40
+ reportedCalls: number;
41
+ missingUsageCalls: number;
42
+ uncachedInputTokens: number;
43
+ cacheReadTokens: number;
44
+ cacheWriteTokens: number;
45
+ outputTokens: number;
46
+ reasoningTokens: number;
47
+ totalTokens: number;
48
+ }
49
+ /** Absolute path of the direct-call token ledger. */
50
+ export declare function tokenUsagePath(baseDir: string): string;
51
+ /** Exact full-call total, with the old-peer fallback only when `totalTokens` is absent. */
52
+ export declare function exactTokenTotal(usage: TokenUsage): number;
53
+ /** Build the observer attached to one `streamText` call. Errors are diagnostic-only. */
54
+ export declare function createTokenUsageObserver(target: TokenUsageTarget, phase: TokenUsagePhase, provider: string, model: string): StreamTextUsageObserver;
55
+ /**
56
+ * Append one call and enforce the dedicated tail budget. Append + conditional
57
+ * prune stay in one synchronous block, so concurrent async callers in one DSH
58
+ * process cannot interleave the read/truncate/write. Multiple DSH processes
59
+ * sharing one baseDir are outside the plugin's storage contract.
60
+ */
61
+ export declare function appendTokenUsage(target: TokenUsageTarget, record: TokenUsageRecord): void;
62
+ /** Load valid records from the retained ledger; malformed lines never break `/evolve usage`. */
63
+ export declare function loadTokenUsage(baseDir: string): LoadedTokenUsage;
64
+ /** Sum exact provider-reported buckets without double-counting reasoning or cache fields. */
65
+ export declare function aggregateTokenUsage(records: readonly TokenUsageRecord[]): TokenUsageTotals;
66
+ /** Render the human-facing direct-call ledger section. */
67
+ export declare function renderTokenUsageReport(ledger: LoadedTokenUsage, retain: number): string[];
68
+ //# sourceMappingURL=token-usage.d.ts.map
@@ -0,0 +1,211 @@
1
+ /**
2
+ * Provider-reported token accounting for plugin-owned direct LLM calls.
3
+ *
4
+ * The review gate, planner, wrap-up command, and local-fate classifier all use
5
+ * the shared `streamText` helper. These calls do not belong to an Agent turn
6
+ * (they pass no sessionId), so the host session token-meter cannot attribute
7
+ * them. This ledger records the exact `TokenUsage` emitted by the adapter at
8
+ * the one shared stream boundary instead.
9
+ *
10
+ * Storage: `<baseDir>/evolve/token-usage.jsonl`. The file contains route and
11
+ * count metadata only — never prompts, responses, or tool arguments — and is
12
+ * trimmed to its dedicated retention budget after each synchronous append.
13
+ */
14
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
15
+ import { join } from "node:path";
16
+ import { EVOLVE_DIR, pruneJsonlFile } from "./store.js";
17
+ const TOKEN_USAGE_FILE = "token-usage.jsonl";
18
+ export const TOKEN_USAGE_LEDGER_VERSION = 1;
19
+ /** Plugin-owned direct call paths represented in the ledger. */
20
+ export const TOKEN_USAGE_PHASES = ["review", "planner", "wrapup", "fate"];
21
+ /** Absolute path of the direct-call token ledger. */
22
+ export function tokenUsagePath(baseDir) {
23
+ return join(baseDir, EVOLVE_DIR, TOKEN_USAGE_FILE);
24
+ }
25
+ /** Exact full-call total, with the old-peer fallback only when `totalTokens` is absent. */
26
+ export function exactTokenTotal(usage) {
27
+ if (usage.totalTokens !== undefined)
28
+ return usage.totalTokens;
29
+ return usage.inputTokens + usage.outputTokens + (usage.cacheReadTokens ?? 0) + (usage.cacheWriteTokens ?? 0);
30
+ }
31
+ /** Build the observer attached to one `streamText` call. Errors are diagnostic-only. */
32
+ export function createTokenUsageObserver(target, phase, provider, model) {
33
+ return (observation) => {
34
+ try {
35
+ appendTokenUsage(target, {
36
+ version: TOKEN_USAGE_LEDGER_VERSION,
37
+ timestamp: new Date().toISOString(),
38
+ sessionId: target.sessionId,
39
+ phase,
40
+ provider,
41
+ model,
42
+ outcome: observation.outcome,
43
+ usageStatus: observation.usage ? "reported" : "missing",
44
+ ...(observation.usage ? { usage: observation.usage } : {}),
45
+ totalSource: observation.usage
46
+ ? observation.usage.totalTokens !== undefined
47
+ ? "provider"
48
+ : "derived"
49
+ : "unavailable",
50
+ });
51
+ }
52
+ catch (cause) {
53
+ target.onError?.(cause);
54
+ }
55
+ };
56
+ }
57
+ /**
58
+ * Append one call and enforce the dedicated tail budget. Append + conditional
59
+ * prune stay in one synchronous block, so concurrent async callers in one DSH
60
+ * process cannot interleave the read/truncate/write. Multiple DSH processes
61
+ * sharing one baseDir are outside the plugin's storage contract.
62
+ */
63
+ export function appendTokenUsage(target, record) {
64
+ if (!isTokenUsageRecord(record)) {
65
+ throw new Error("evolve: refusing to append an invalid token-usage record");
66
+ }
67
+ const dir = join(target.baseDir, EVOLVE_DIR);
68
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
69
+ writeFileSync(tokenUsagePath(target.baseDir), `${JSON.stringify(record)}\n`, {
70
+ encoding: "utf8",
71
+ flag: "a",
72
+ mode: 0o600,
73
+ });
74
+ pruneJsonlFile(tokenUsagePath(target.baseDir), target.retain);
75
+ }
76
+ /** Load valid records from the retained ledger; malformed lines never break `/evolve usage`. */
77
+ export function loadTokenUsage(baseDir) {
78
+ const path = tokenUsagePath(baseDir);
79
+ if (!existsSync(path))
80
+ return { records: [], corruptLines: 0 };
81
+ let lines;
82
+ try {
83
+ lines = readFileSync(path, "utf8").split("\n");
84
+ }
85
+ catch {
86
+ return { records: [], corruptLines: 0 };
87
+ }
88
+ const records = [];
89
+ let corruptLines = 0;
90
+ for (const line of lines) {
91
+ if (line.trim().length === 0)
92
+ continue;
93
+ try {
94
+ const parsed = JSON.parse(line);
95
+ if (isTokenUsageRecord(parsed))
96
+ records.push(parsed);
97
+ else
98
+ corruptLines += 1;
99
+ }
100
+ catch {
101
+ corruptLines += 1;
102
+ }
103
+ }
104
+ return { records, corruptLines };
105
+ }
106
+ /** Sum exact provider-reported buckets without double-counting reasoning or cache fields. */
107
+ export function aggregateTokenUsage(records) {
108
+ const totals = {
109
+ calls: records.length,
110
+ reportedCalls: 0,
111
+ missingUsageCalls: 0,
112
+ uncachedInputTokens: 0,
113
+ cacheReadTokens: 0,
114
+ cacheWriteTokens: 0,
115
+ outputTokens: 0,
116
+ reasoningTokens: 0,
117
+ totalTokens: 0,
118
+ };
119
+ for (const record of records) {
120
+ if (record.usageStatus === "missing" || !record.usage) {
121
+ totals.missingUsageCalls += 1;
122
+ continue;
123
+ }
124
+ totals.reportedCalls += 1;
125
+ totals.uncachedInputTokens += record.usage.inputTokens;
126
+ totals.cacheReadTokens += record.usage.cacheReadTokens ?? 0;
127
+ totals.cacheWriteTokens += record.usage.cacheWriteTokens ?? 0;
128
+ totals.outputTokens += record.usage.outputTokens;
129
+ totals.reasoningTokens += record.usage.reasoningTokens ?? 0;
130
+ totals.totalTokens += exactTokenTotal(record.usage);
131
+ }
132
+ return totals;
133
+ }
134
+ /** Render the human-facing direct-call ledger section. */
135
+ export function renderTokenUsageReport(ledger, retain) {
136
+ const { records, corruptLines } = ledger;
137
+ if (records.length === 0) {
138
+ const corrupt = corruptLines > 0 ? ` ${corruptLines} corrupt line(s) ignored.` : "";
139
+ return [
140
+ `direct LLM token usage: no valid calls in the retained tail.${corrupt}`,
141
+ `window: last ${retain} call(s), not a lifetime total.`,
142
+ "scope: review/planner/wrapup/fate only; host benchmark subagents, their agent-loop calls, and per-entry injection cost are excluded.",
143
+ ];
144
+ }
145
+ const totals = aggregateTokenUsage(records);
146
+ const lines = [
147
+ `direct LLM token usage: ${totals.calls} valid calls (${totals.reportedCalls} reported usage, ${totals.missingUsageCalls} missing)${corruptLines > 0 ? `; ${corruptLines} corrupt line(s) ignored` : ""}`,
148
+ ` uncached input: ${totals.uncachedInputTokens}`,
149
+ ` cache read: ${totals.cacheReadTokens}`,
150
+ ` cache write: ${totals.cacheWriteTokens}`,
151
+ ` output: ${totals.outputTokens}`,
152
+ ` reasoning: ${totals.reasoningTokens}${records.some((record) => record.usageStatus === "reported" && record.usage?.reasoningTokens === undefined) ? " (partial provider reports)" : ""}`,
153
+ ` exact total: ${totals.totalTokens} (reported calls only)`,
154
+ `window: last ${retain} call(s), not a lifetime total.`,
155
+ "by phase:",
156
+ ];
157
+ for (const phase of TOKEN_USAGE_PHASES) {
158
+ const phaseRecords = records.filter((record) => record.phase === phase);
159
+ if (phaseRecords.length === 0)
160
+ continue;
161
+ const phaseTotals = aggregateTokenUsage(phaseRecords);
162
+ lines.push(` ${phase.padEnd(7)} ${phaseTotals.calls} calls · ${phaseTotals.totalTokens} tokens`);
163
+ }
164
+ const last = records.at(-1);
165
+ if (last) {
166
+ const lastTotal = last.usage ? exactTokenTotal(last.usage) : "usage unavailable";
167
+ lines.push(`last: ${last.phase} ${last.provider}/${last.model} · ${last.outcome} · ${lastTotal} tokens · ${last.timestamp}`);
168
+ }
169
+ lines.push("scope: review/planner/wrapup/fate only; host benchmark subagents, their agent-loop calls, and per-entry injection cost are excluded.");
170
+ return lines;
171
+ }
172
+ function isTokenUsageRecord(value) {
173
+ if (typeof value !== "object" || value === null || Array.isArray(value))
174
+ return false;
175
+ const record = value;
176
+ if (record["version"] !== TOKEN_USAGE_LEDGER_VERSION ||
177
+ typeof record["timestamp"] !== "string" ||
178
+ typeof record["sessionId"] !== "string" ||
179
+ typeof record["provider"] !== "string" ||
180
+ typeof record["model"] !== "string" ||
181
+ typeof record["outcome"] !== "string" ||
182
+ !TOKEN_USAGE_PHASES.includes(record["phase"]) ||
183
+ !["success", "max-tokens", "error", "aborted", "empty"].includes(record["outcome"]) ||
184
+ !["reported", "missing"].includes(record["usageStatus"]) ||
185
+ !["provider", "derived", "unavailable"].includes(record["totalSource"])) {
186
+ return false;
187
+ }
188
+ if (record["usageStatus"] === "missing") {
189
+ return record["usage"] === undefined && record["totalSource"] === "unavailable";
190
+ }
191
+ if (!isTokenUsage(record["usage"]))
192
+ return false;
193
+ const expectedSource = record["usage"]["totalTokens"] !== undefined ? "provider" : "derived";
194
+ return record["totalSource"] === expectedSource;
195
+ }
196
+ function isCount(value) {
197
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
198
+ }
199
+ function isTokenUsage(value) {
200
+ if (typeof value !== "object" || value === null || Array.isArray(value))
201
+ return false;
202
+ const usage = value;
203
+ if (!isCount(usage["inputTokens"]) || !isCount(usage["outputTokens"]))
204
+ return false;
205
+ for (const key of ["totalTokens", "cacheReadTokens", "cacheWriteTokens", "reasoningTokens"]) {
206
+ if (usage[key] !== undefined && !isCount(usage[key]))
207
+ return false;
208
+ }
209
+ return true;
210
+ }
211
+ //# sourceMappingURL=token-usage.js.map
package/lib/tool.d.ts CHANGED
@@ -6,8 +6,20 @@
6
6
  import type { Context } from "@deepseek-ai/cordis";
7
7
  import type { HarnessScope } from "./types.js";
8
8
  import type { EvolutionEngine } from "./service.js";
9
- /** Accept both the boolean tool parameter (`global: true`) and the string form. */
9
+ /**
10
+ * Accept the string form (`scope: "project"`) with the legacy boolean tool
11
+ * parameter (`global: true`) as fallback. `scope` wins when both are given.
12
+ */
10
13
  export declare function scopeOf(value: unknown, fallback: HarnessScope): HarnessScope;
14
+ /**
15
+ * Collect the target ids for an evolve_delete call: legacy single `id`
16
+ * plus the batch `ids` array, de-duplicated in first-seen order. Throws
17
+ * loudly when neither carries an id — a silent no-op delete would look
18
+ * like success while deleting nothing.
19
+ *
20
+ * @throws when both `id` and `ids` are absent or empty.
21
+ */
22
+ export declare function collectDeleteIds(id: unknown, ids: unknown): string[];
11
23
  export interface ToolGateOptions {
12
24
  requireGlobalApproval: boolean;
13
25
  }