knodin 0.14.0 → 0.14.2

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/dist/bin/cli.js CHANGED
@@ -15,8 +15,8 @@ import { spawn, spawnSync } from "node:child_process";
15
15
  import fs from "node:fs";
16
16
  import path from "node:path";
17
17
  import { fileURLToPath } from "node:url";
18
- import { canUseSessionContextCache, parseClaudeHookPayload, readSessionContextCache, recordClaudeLifecycleEvent, renderSessionContext, SESSION_CONTEXT_BUDGET_LINE, sessionStartHookOutput, writeSessionContextCache, } from "../src/agent-events.js";
19
- import { inspectClaudeAgentHooks, installClaudeAgentHooks, uninstallClaudeAgentHooks, } from "../src/agent-hooks.js";
18
+ import { canUseSessionContextCache, deriveStatusNextAction, evaluatePreToolUseNudge, parseClaudeHookPayload, preToolUseHookOutput, readSessionContextCache, recordClaudeLifecycleEvent, renderSessionContext, SESSION_CONTEXT_BUDGET_LINE, sessionStartHookOutput, writeSessionContextCache, } from "../src/agent-events.js";
19
+ import { inspectClaudeAgentHooks, installClaudeAgentHooks, SUPPORTED_AGENT_HOOK_CLIENTS, uninstallClaudeAgentHooks, } from "../src/agent-hooks.js";
20
20
  import { detectSupportedAgents, parseInitScope, } from "../src/agent-integration.js";
21
21
  import { refreshExternalGraphArtifacts, writeArtifactRefreshRecord, } from "../src/artifact-refresh.js";
22
22
  import { formatBackupHuman, installBackupRetention, listBackups, maybeRunOpportunisticRetention, pruneBackups, removeBackupRetention, retentionDoctor, retentionStatus, runInstalledRetention, } from "../src/backup-retention.js";
@@ -1431,23 +1431,25 @@ async function main() {
1431
1431
  }
1432
1432
  if (cmd === "agent-hooks") {
1433
1433
  const action = invocation.commandPath[1];
1434
- const client = selectorValue("--client") ?? "claude";
1435
- if (client !== "claude")
1436
- throw new Error("knodin agent-hooks: only --client claude is supported");
1434
+ const clientRaw = selectorValue("--client") ?? "claude";
1435
+ if (!SUPPORTED_AGENT_HOOK_CLIENTS.includes(clientRaw))
1436
+ throw new Error("knodin agent-hooks: --client must be claude, gemini, codex, copilot, or antigravity");
1437
+ const client = clientRaw;
1437
1438
  if (invocation.options.dryRun === true && action !== "install")
1438
1439
  throw new Error("knodin agent-hooks: --dry-run applies only to install");
1439
1440
  let hookResult;
1440
1441
  if (action === "install") {
1441
1442
  const quote = (value) => `'${value.replaceAll("'", `'"'"'`)}'`;
1442
1443
  hookResult = installClaudeAgentHooks({
1444
+ client,
1443
1445
  command: runtimeCommand.map(quote).join(" "),
1444
1446
  dryRun: invocation.options.dryRun === true,
1445
1447
  });
1446
1448
  }
1447
1449
  else if (action === "status")
1448
- hookResult = inspectClaudeAgentHooks();
1450
+ hookResult = inspectClaudeAgentHooks({ client });
1449
1451
  else if (action === "uninstall")
1450
- hookResult = uninstallClaudeAgentHooks();
1452
+ hookResult = uninstallClaudeAgentHooks({ client });
1451
1453
  else
1452
1454
  throw new Error("knodin agent-hooks requires install, status, or uninstall");
1453
1455
  process.stdout.write(jsonOutput
@@ -1899,13 +1901,17 @@ async function main() {
1899
1901
  break;
1900
1902
  }
1901
1903
  if (event !== "session-start") {
1904
+ let nudge = null;
1902
1905
  try {
1906
+ if (event === "pre-tool") {
1907
+ nudge = evaluatePreToolUseNudge(repo, payload);
1908
+ }
1903
1909
  recordClaudeLifecycleEvent(repo, event, payload);
1904
1910
  }
1905
1911
  catch {
1906
1912
  // Optional telemetry must never interrupt the agent.
1907
1913
  }
1908
- result = null;
1914
+ result = nudge ? preToolUseHookOutput(nudge) : null;
1909
1915
  break;
1910
1916
  }
1911
1917
  const startedAt = performance.now();
@@ -2498,17 +2504,21 @@ async function main() {
2498
2504
  break;
2499
2505
  }
2500
2506
  case "status": {
2501
- const snapshot = async () => ({
2502
- ...attachLifecycleHealth(repo, await engine.status(repo, {
2507
+ const snapshot = async () => {
2508
+ const rawStatus = await engine.status(repo, {
2503
2509
  audit: rest.includes("--deep") ? "deep" : "adaptive",
2504
- })),
2505
- integration: inspectRepositoryIntegrationStatus(repo),
2506
- update: trustedUpdateStatus({
2507
- currentVersion: KNODIN_VERSION,
2508
- installMethod: detectUpdateInstallMethod(runtimeCommand),
2509
- env: process.env,
2510
- }),
2511
- });
2510
+ });
2511
+ return {
2512
+ ...attachLifecycleHealth(repo, rawStatus),
2513
+ nextAction: deriveStatusNextAction(rawStatus),
2514
+ integration: inspectRepositoryIntegrationStatus(repo),
2515
+ update: trustedUpdateStatus({
2516
+ currentVersion: KNODIN_VERSION,
2517
+ installMethod: detectUpdateInstallMethod(runtimeCommand),
2518
+ env: process.env,
2519
+ }),
2520
+ };
2521
+ };
2512
2522
  if (rest.includes("--watch")) {
2513
2523
  const intervalRaw = selectorValue("--interval");
2514
2524
  const intervalSeconds = intervalRaw === undefined ? 1 : Number(intervalRaw);
@@ -2,7 +2,7 @@ import fs from "node:fs";
2
2
  import path from "node:path";
3
3
  import { indexCoverageCore, indexCoverageNotice } from "./index-coverage-read.js";
4
4
  import { countOutputTokens } from "./output-telemetry.js";
5
- import { appendSessionEvent, } from "./session-telemetry.js";
5
+ import { appendSessionEvent, hasTurnEvidenceBeforeEdit, isSessionTelemetryEnabled, } from "./session-telemetry.js";
6
6
  export const SESSION_CONTEXT_BUDGET_LINE = "Budget: at most 600 tokens, 8 KiB, 12 items.";
7
7
  const KNOWN_OPERATIONS = new Set([
8
8
  "context",
@@ -144,3 +144,36 @@ export function sessionStartHookOutput(text) {
144
144
  },
145
145
  };
146
146
  }
147
+ export function preToolUseHookOutput(text) {
148
+ return {
149
+ hookSpecificOutput: {
150
+ hookEventName: "PreToolUse",
151
+ additionalContext: text,
152
+ },
153
+ };
154
+ }
155
+ export function evaluatePreToolUseNudge(repo, payload, options) {
156
+ const classified = classifyTool(payload);
157
+ if (classified.toolCategory !== "edit")
158
+ return null;
159
+ if (!payload.session_id)
160
+ return null;
161
+ if (!options?.forceCheck && !isSessionTelemetryEnabled(repo))
162
+ return null;
163
+ if (hasTurnEvidenceBeforeEdit(repo, payload.session_id))
164
+ return null;
165
+ return "Tip: No knodin evidence operation (explain, query impact, search, context) was recorded in this turn before editing. Call knodin explain or knodin query impact on the target symbol first to verify callers and blast radius.";
166
+ }
167
+ export function deriveStatusNextAction(status) {
168
+ if (status.coverage?.indexedFiles === 0) {
169
+ return "Run `knodin index` to index the repository before relying on graph evidence.";
170
+ }
171
+ if (status.status === "repair-needed") {
172
+ return "Run `knodin repair` (or `knodin index --clean` if schema/corruption persists) before relying on graph evidence.";
173
+ }
174
+ if (status.status === "stale" ||
175
+ (status.freshness?.state !== undefined && status.freshness.state !== "fresh")) {
176
+ return "Run `knodin index` to refresh stale graph evidence, or call `knodin context` with explicit freshness awareness.";
177
+ }
178
+ return "Call `knodin context` for task orientation, `knodin explain <symbol>` for symbol investigation, or `knodin query impact <symbol> --direction upstream` before editing.";
179
+ }
@@ -2,8 +2,26 @@ import fs from "node:fs";
2
2
  import os from "node:os";
3
3
  import path from "node:path";
4
4
  const OWNED_COMMAND = "knodin agent-event";
5
- function settingsPath(homeDir = os.homedir()) {
6
- return path.join(homeDir, ".claude", "settings.json");
5
+ export const SUPPORTED_AGENT_HOOK_CLIENTS = [
6
+ "claude",
7
+ "gemini",
8
+ "codex",
9
+ "copilot",
10
+ "antigravity",
11
+ ];
12
+ function settingsPath(homeDir = os.homedir(), client = "claude") {
13
+ switch (client) {
14
+ case "claude":
15
+ return path.join(homeDir, ".claude", "settings.json");
16
+ case "gemini":
17
+ return path.join(homeDir, ".gemini", "settings.json");
18
+ case "codex":
19
+ return path.join(homeDir, ".codex", "hooks.json");
20
+ case "copilot":
21
+ return path.join(homeDir, ".copilot", "hooks.json");
22
+ case "antigravity":
23
+ return path.join(homeDir, ".gemini", "antigravity", "hooks.json");
24
+ }
7
25
  }
8
26
  function assertNotSymlink(filePath) {
9
27
  for (const candidate of [path.dirname(filePath), filePath]) {
@@ -95,21 +113,23 @@ function mergedSettings(existing, command) {
95
113
  return document;
96
114
  }
97
115
  export function inspectClaudeAgentHooks(options = {}) {
98
- const filePath = settingsPath(options.homeDir);
116
+ const client = options.client ?? "claude";
117
+ const filePath = settingsPath(options.homeDir, client);
99
118
  assertNotSymlink(filePath);
100
119
  const document = readSettings(filePath);
101
120
  const serialized = JSON.stringify(document);
102
121
  const count = serialized.split(OWNED_COMMAND).length - 1;
103
122
  return {
104
123
  schemaVersion: 1,
105
- client: "claude",
124
+ client,
106
125
  settingsPath: filePath,
107
126
  installed: count > 0,
108
127
  managedEntries: count,
109
128
  };
110
129
  }
111
130
  export function installClaudeAgentHooks(options = {}) {
112
- const filePath = settingsPath(options.homeDir);
131
+ const client = options.client ?? "claude";
132
+ const filePath = settingsPath(options.homeDir, client);
113
133
  assertNotSymlink(filePath);
114
134
  const before = readSettings(filePath);
115
135
  const after = mergedSettings(before, options.command ?? "knodin");
@@ -126,7 +146,7 @@ export function installClaudeAgentHooks(options = {}) {
126
146
  }
127
147
  return {
128
148
  schemaVersion: 1,
129
- client: "claude",
149
+ client,
130
150
  settingsPath: filePath,
131
151
  changed,
132
152
  dryRun: options.dryRun === true,
@@ -134,10 +154,11 @@ export function installClaudeAgentHooks(options = {}) {
134
154
  };
135
155
  }
136
156
  export function uninstallClaudeAgentHooks(options = {}) {
137
- const filePath = settingsPath(options.homeDir);
157
+ const client = options.client ?? "claude";
158
+ const filePath = settingsPath(options.homeDir, client);
138
159
  assertNotSymlink(filePath);
139
160
  if (!fs.existsSync(filePath))
140
- return { removed: false, settingsPath: filePath };
161
+ return { schemaVersion: 1, client, removed: false, settingsPath: filePath };
141
162
  const document = readSettings(filePath);
142
163
  const hadOwned = ownedEntry(document);
143
164
  removeOwned(document);
@@ -149,8 +170,11 @@ export function uninstallClaudeAgentHooks(options = {}) {
149
170
  }
150
171
  return {
151
172
  schemaVersion: 1,
152
- client: "claude",
173
+ client,
153
174
  removed: hadOwned,
154
175
  settingsPath: filePath,
155
176
  };
156
177
  }
178
+ export const inspectAgentHooks = inspectClaudeAgentHooks;
179
+ export const installAgentHooks = installClaudeAgentHooks;
180
+ export const uninstallAgentHooks = uninstallClaudeAgentHooks;
@@ -339,7 +339,7 @@ function createCliProgram(capture = () => { }) {
339
339
  .description("manage optional user-global coding-agent lifecycle hooks");
340
340
  for (const action of ["install", "status", "uninstall"])
341
341
  leaf(agentHooks, action, `${action} optional coding-agent hooks`, capture)
342
- .option("--client <client>", "coding-agent client; currently claude")
342
+ .option("--client <client>", "coding-agent client: claude, gemini, codex, copilot, or antigravity")
343
343
  .option("--dry-run", "preview settings changes without writing");
344
344
  leaf(program, "agent-event <event>", "internal coding-agent lifecycle event", capture);
345
345
  leaf(program, "refresh-artifacts [event]", "refresh external graph artifacts", capture);
@@ -0,0 +1,412 @@
1
+ import { createHash } from "node:crypto";
2
+ function dcg(grades) {
3
+ return grades.reduce((sum, grade, index) => sum + (2 ** grade - 1) / Math.log2(index + 2), 0);
4
+ }
5
+ export function computeCorpusDigest(files) {
6
+ const hash = createHash("sha256");
7
+ for (const key of Object.keys(files).sort()) {
8
+ hash.update(key);
9
+ hash.update("\0");
10
+ hash.update(files[key] ?? "");
11
+ hash.update("\0");
12
+ }
13
+ return hash.digest("hex");
14
+ }
15
+ function detectPostFixLeakage(testCase, runs) {
16
+ for (const token of testCase.postFixLeakageTokens) {
17
+ if (!token)
18
+ continue;
19
+ const pattern = new RegExp(String.raw `\b${token.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\b`);
20
+ if (pattern.test(testCase.query)) {
21
+ return `query contains post-fix token "${token}"`;
22
+ }
23
+ for (const run of runs) {
24
+ if (!run)
25
+ continue;
26
+ for (const item of run.rankedItems) {
27
+ if (pattern.test(item.identity) ||
28
+ (item.sourceSnippet && pattern.test(item.sourceSnippet))) {
29
+ return `${run.tool} output leaked post-fix token "${token}"`;
30
+ }
31
+ }
32
+ }
33
+ }
34
+ return null;
35
+ }
36
+ function scoreSingleToolRun(testCase, run, k) {
37
+ const missingMetricReasons = {};
38
+ if (run.status !== "completed") {
39
+ const reason = run.failureReason ?? `tool status is ${run.status}`;
40
+ for (const metric of [
41
+ "nDcgAtK",
42
+ "recallAtK",
43
+ "changedFileRecallAtK",
44
+ "unchangedSupportRecallAtK",
45
+ "usefulSourceTokens",
46
+ "unusedSourceTokens",
47
+ "latencyMs",
48
+ "peakRssBytes",
49
+ ]) {
50
+ missingMetricReasons[metric] = reason;
51
+ }
52
+ return {
53
+ tool: run.tool,
54
+ toolVersion: run.toolVersion,
55
+ mode: run.mode,
56
+ status: run.status,
57
+ nDcgAtK: null,
58
+ recallAtK: null,
59
+ changedFileRecallAtK: null,
60
+ unchangedSupportRecallAtK: null,
61
+ usefulSourceTokens: null,
62
+ unusedSourceTokens: null,
63
+ latencyMs: null,
64
+ peakRssBytes: null,
65
+ withinBudget: null,
66
+ missingMetricReasons,
67
+ judgedUsefulness: [],
68
+ };
69
+ }
70
+ const labelById = new Map();
71
+ const labelByFile = new Map();
72
+ for (const label of testCase.relevanceLabels) {
73
+ labelById.set(label.identity, label);
74
+ if (!labelByFile.has(label.filePath)) {
75
+ labelByFile.set(label.filePath, label);
76
+ }
77
+ }
78
+ const bounded = run.rankedItems.slice(0, k);
79
+ const matchedLabels = new Set();
80
+ const observedGrades = [];
81
+ let usefulTokens = 0;
82
+ let unusedTokens = 0;
83
+ const judgedUsefulness = [];
84
+ for (const item of bounded) {
85
+ const label = labelById.get(item.identity) ?? labelByFile.get(item.filePath);
86
+ const tokens = item.estimatedTokens ??
87
+ (item.sourceSnippet ? Math.ceil(Buffer.byteLength(item.sourceSnippet, "utf8") / 4) : 0);
88
+ if (label && !matchedLabels.has(label.identity)) {
89
+ matchedLabels.add(label.identity);
90
+ observedGrades.push(label.grade);
91
+ usefulTokens += tokens;
92
+ }
93
+ else if (label) {
94
+ observedGrades.push(0);
95
+ usefulTokens += tokens;
96
+ }
97
+ else {
98
+ observedGrades.push(0);
99
+ unusedTokens += tokens;
100
+ }
101
+ judgedUsefulness.push({
102
+ identity: item.identity,
103
+ category: label ? label.category : "unlabeled",
104
+ judgedUseful: Boolean(label),
105
+ observedWriterUse: testCase.observedWriterUse?.[item.identity] ?? "unknown",
106
+ });
107
+ }
108
+ const idealGrades = testCase.relevanceLabels
109
+ .map((l) => l.grade)
110
+ .sort((a, b) => b - a)
111
+ .slice(0, k);
112
+ const idealDcg = dcg(idealGrades);
113
+ const nDcgAtK = idealDcg > 0 ? dcg(observedGrades) / idealDcg : 0;
114
+ const recallAtK = testCase.relevanceLabels.length > 0 ? matchedLabels.size / testCase.relevanceLabels.length : 0;
115
+ const changedLabels = testCase.relevanceLabels.filter((l) => l.category === "changed-file");
116
+ const unchangedSupportLabels = testCase.relevanceLabels.filter((l) => l.category === "unchanged-helper" || l.category === "unchanged-test");
117
+ const changedFileRecallAtK = changedLabels.length > 0
118
+ ? changedLabels.filter((l) => matchedLabels.has(l.identity)).length / changedLabels.length
119
+ : null;
120
+ if (changedFileRecallAtK === null) {
121
+ missingMetricReasons.changedFileRecallAtK = "no changed-file labels in case oracle";
122
+ }
123
+ const unchangedSupportRecallAtK = unchangedSupportLabels.length > 0
124
+ ? unchangedSupportLabels.filter((l) => matchedLabels.has(l.identity)).length /
125
+ unchangedSupportLabels.length
126
+ : null;
127
+ if (unchangedSupportRecallAtK === null) {
128
+ missingMetricReasons.unchangedSupportRecallAtK =
129
+ "no unchanged-helper or unchanged-test labels in case oracle";
130
+ }
131
+ if (run.latencyMs === undefined || run.latencyMs === null) {
132
+ missingMetricReasons.latencyMs = "latency was not measured for this run";
133
+ }
134
+ if (run.peakRssBytes === undefined || run.peakRssBytes === null) {
135
+ missingMetricReasons.peakRssBytes = "peak RSS was not measured for this run";
136
+ }
137
+ const withinBudget = run.responseBytes !== undefined &&
138
+ run.responseBytes !== null &&
139
+ run.sourceBytes !== undefined &&
140
+ run.sourceBytes !== null
141
+ ? run.responseBytes <= run.responseByteBudget && run.sourceBytes <= run.sourceByteBudget
142
+ : null;
143
+ if (withinBudget === null) {
144
+ missingMetricReasons.withinBudget = "responseBytes or sourceBytes missing";
145
+ }
146
+ return {
147
+ tool: run.tool,
148
+ toolVersion: run.toolVersion,
149
+ mode: run.mode,
150
+ status: bounded.length === 0 ? "empty-retrieval" : "completed",
151
+ nDcgAtK,
152
+ recallAtK,
153
+ changedFileRecallAtK,
154
+ unchangedSupportRecallAtK,
155
+ usefulSourceTokens: usefulTokens,
156
+ unusedSourceTokens: unusedTokens,
157
+ latencyMs: run.latencyMs ?? null,
158
+ peakRssBytes: run.peakRssBytes ?? null,
159
+ withinBudget,
160
+ missingMetricReasons,
161
+ judgedUsefulness,
162
+ };
163
+ }
164
+ export function evaluateHistoricalRetrievalCase(testCase, knodinRun, rgRun, k = 5) {
165
+ if (testCase.sourceAvailable === false) {
166
+ return {
167
+ caseId: testCase.caseId,
168
+ issueId: testCase.issueId,
169
+ preFixCommit: testCase.preFixCommit,
170
+ status: "missing-source",
171
+ statusReason: "pre-fix source snapshot is unavailable",
172
+ validForComparison: false,
173
+ winClaimed: false,
174
+ knodin: null,
175
+ rg: null,
176
+ delta: {
177
+ nDcgAtK: null,
178
+ recallAtK: null,
179
+ unchangedSupportRecallAtK: null,
180
+ usefulTokenShare: null,
181
+ reason: "missing-source",
182
+ },
183
+ };
184
+ }
185
+ if (testCase.revisionResolved === false || !/^[a-f0-9]{7,40}$/i.test(testCase.preFixCommit)) {
186
+ return {
187
+ caseId: testCase.caseId,
188
+ issueId: testCase.issueId,
189
+ preFixCommit: testCase.preFixCommit,
190
+ status: "unresolved-revision",
191
+ statusReason: `pre-fix revision "${testCase.preFixCommit}" could not be resolved`,
192
+ validForComparison: false,
193
+ winClaimed: false,
194
+ knodin: null,
195
+ rg: null,
196
+ delta: {
197
+ nDcgAtK: null,
198
+ recallAtK: null,
199
+ unchangedSupportRecallAtK: null,
200
+ usefulTokenShare: null,
201
+ reason: "unresolved-revision",
202
+ },
203
+ };
204
+ }
205
+ if (!testCase.observedCorpusSha256 ||
206
+ testCase.observedCorpusSha256 !== testCase.expectedCorpusSha256) {
207
+ return {
208
+ caseId: testCase.caseId,
209
+ issueId: testCase.issueId,
210
+ preFixCommit: testCase.preFixCommit,
211
+ status: "rejected-hash-mismatch",
212
+ statusReason: "observed pre-fix corpus SHA-256 does not match pinned expected digest",
213
+ validForComparison: false,
214
+ winClaimed: false,
215
+ knodin: null,
216
+ rg: null,
217
+ delta: {
218
+ nDcgAtK: null,
219
+ recallAtK: null,
220
+ unchangedSupportRecallAtK: null,
221
+ usefulTokenShare: null,
222
+ reason: "rejected-hash-mismatch",
223
+ },
224
+ };
225
+ }
226
+ if (testCase.relevanceLabels.length === 0 ||
227
+ !testCase.relevanceLabels.some((l) => l.category === "changed-file")) {
228
+ return {
229
+ caseId: testCase.caseId,
230
+ issueId: testCase.issueId,
231
+ preFixCommit: testCase.preFixCommit,
232
+ status: "invalid-labels",
233
+ statusReason: "relevanceLabels must include at least one changed-file recall floor label",
234
+ validForComparison: false,
235
+ winClaimed: false,
236
+ knodin: null,
237
+ rg: null,
238
+ delta: {
239
+ nDcgAtK: null,
240
+ recallAtK: null,
241
+ unchangedSupportRecallAtK: null,
242
+ usefulTokenShare: null,
243
+ reason: "invalid-labels",
244
+ },
245
+ };
246
+ }
247
+ const leakageReason = detectPostFixLeakage(testCase, [knodinRun, rgRun]);
248
+ if (leakageReason) {
249
+ return {
250
+ caseId: testCase.caseId,
251
+ issueId: testCase.issueId,
252
+ preFixCommit: testCase.preFixCommit,
253
+ status: "rejected-post-fix-leakage",
254
+ statusReason: leakageReason,
255
+ validForComparison: false,
256
+ winClaimed: false,
257
+ knodin: null,
258
+ rg: null,
259
+ delta: {
260
+ nDcgAtK: null,
261
+ recallAtK: null,
262
+ unchangedSupportRecallAtK: null,
263
+ usefulTokenShare: null,
264
+ reason: "rejected-post-fix-leakage",
265
+ },
266
+ };
267
+ }
268
+ if (knodinRun &&
269
+ rgRun &&
270
+ (knodinRun.responseByteBudget !== rgRun.responseByteBudget ||
271
+ knodinRun.sourceByteBudget !== rgRun.sourceByteBudget ||
272
+ knodinRun.mode !== rgRun.mode)) {
273
+ return {
274
+ caseId: testCase.caseId,
275
+ issueId: testCase.issueId,
276
+ preFixCommit: testCase.preFixCommit,
277
+ status: "budget-mismatch",
278
+ statusReason: "deltas require matched cold/warm mode and identical response/source budgets",
279
+ validForComparison: false,
280
+ winClaimed: false,
281
+ knodin: null,
282
+ rg: null,
283
+ delta: {
284
+ nDcgAtK: null,
285
+ recallAtK: null,
286
+ unchangedSupportRecallAtK: null,
287
+ usefulTokenShare: null,
288
+ reason: "budget-mismatch",
289
+ },
290
+ };
291
+ }
292
+ const knodinMetrics = knodinRun ? scoreSingleToolRun(testCase, knodinRun, k) : null;
293
+ const rgMetrics = rgRun ? scoreSingleToolRun(testCase, rgRun, k) : null;
294
+ if (!knodinMetrics ||
295
+ !rgMetrics ||
296
+ knodinMetrics.status === "failed" ||
297
+ knodinMetrics.status === "unavailable" ||
298
+ rgMetrics.status === "failed" ||
299
+ rgMetrics.status === "unavailable") {
300
+ return {
301
+ caseId: testCase.caseId,
302
+ issueId: testCase.issueId,
303
+ preFixCommit: testCase.preFixCommit,
304
+ status: "tool-execution-failed",
305
+ statusReason: "one or both tool runs failed or were unavailable",
306
+ validForComparison: false,
307
+ winClaimed: false,
308
+ knodin: knodinMetrics,
309
+ rg: rgMetrics,
310
+ delta: {
311
+ nDcgAtK: null,
312
+ recallAtK: null,
313
+ unchangedSupportRecallAtK: null,
314
+ usefulTokenShare: null,
315
+ reason: "tool-execution-failed",
316
+ },
317
+ };
318
+ }
319
+ const isEmpty = knodinMetrics.status === "empty-retrieval" && rgMetrics.status === "empty-retrieval";
320
+ const nDcgDelta = knodinMetrics.nDcgAtK !== null && rgMetrics.nDcgAtK !== null
321
+ ? knodinMetrics.nDcgAtK - rgMetrics.nDcgAtK
322
+ : null;
323
+ const recallDelta = knodinMetrics.recallAtK !== null && rgMetrics.recallAtK !== null
324
+ ? knodinMetrics.recallAtK - rgMetrics.recallAtK
325
+ : null;
326
+ const supportRecallDelta = knodinMetrics.unchangedSupportRecallAtK !== null && rgMetrics.unchangedSupportRecallAtK !== null
327
+ ? knodinMetrics.unchangedSupportRecallAtK - rgMetrics.unchangedSupportRecallAtK
328
+ : null;
329
+ const knodinTotalTokens = (knodinMetrics.usefulSourceTokens ?? 0) + (knodinMetrics.unusedSourceTokens ?? 0);
330
+ const rgTotalTokens = (rgMetrics.usefulSourceTokens ?? 0) + (rgMetrics.unusedSourceTokens ?? 0);
331
+ const knodinUsefulShare = knodinTotalTokens > 0 ? (knodinMetrics.usefulSourceTokens ?? 0) / knodinTotalTokens : 0;
332
+ const rgUsefulShare = rgTotalTokens > 0 ? (rgMetrics.usefulSourceTokens ?? 0) / rgTotalTokens : 0;
333
+ const winClaimed = knodinMetrics.status === "completed" &&
334
+ knodinMetrics.withinBudget === true &&
335
+ (nDcgDelta ?? -1) >= 0 &&
336
+ (recallDelta ?? -1) >= 0 &&
337
+ ((nDcgDelta ?? 0) > 0 || (recallDelta ?? 0) > 0 || (supportRecallDelta ?? 0) > 0);
338
+ return {
339
+ caseId: testCase.caseId,
340
+ issueId: testCase.issueId,
341
+ preFixCommit: testCase.preFixCommit,
342
+ status: isEmpty ? "empty-retrieval" : "evaluated",
343
+ validForComparison: true,
344
+ winClaimed,
345
+ knodin: knodinMetrics,
346
+ rg: rgMetrics,
347
+ delta: {
348
+ nDcgAtK: nDcgDelta,
349
+ recallAtK: recallDelta,
350
+ unchangedSupportRecallAtK: supportRecallDelta,
351
+ usefulTokenShare: knodinUsefulShare - rgUsefulShare,
352
+ },
353
+ };
354
+ }
355
+ export function summarizeHistoricalRetrievalEvaluation(receipts, k = 5, thresholds = {
356
+ minNDcgDelta: 0.02,
357
+ minRecallDelta: 0,
358
+ maxMemoryCeilingBytes: 1024 * 1024 * 1024,
359
+ }) {
360
+ const comparable = receipts.filter((r) => r.validForComparison && r.knodin && r.rg);
361
+ const emptyRetrievalCases = receipts.filter((r) => r.status === "empty-retrieval").length;
362
+ const excludedCases = receipts.length - comparable.length;
363
+ const regressions = comparable.filter((r) => (r.delta.nDcgAtK !== null && r.delta.nDcgAtK < 0) ||
364
+ (r.delta.recallAtK !== null && r.delta.recallAtK < 0) ||
365
+ r.knodin?.withinBudget === false ||
366
+ (r.knodin?.peakRssBytes ?? 0) > thresholds.maxMemoryCeilingBytes).length;
367
+ const mean = (values) => {
368
+ const valid = values.filter((v) => typeof v === "number");
369
+ return valid.length > 0 ? valid.reduce((a, b) => a + b, 0) / valid.length : null;
370
+ };
371
+ const meanKnodinNDcg = mean(comparable.map((r) => r.knodin?.nDcgAtK));
372
+ const meanRgNDcg = mean(comparable.map((r) => r.rg?.nDcgAtK));
373
+ const meanKnodinRecall = mean(comparable.map((r) => r.knodin?.recallAtK));
374
+ const meanRgRecall = mean(comparable.map((r) => r.rg?.recallAtK));
375
+ const meanKnodinUnchangedSupportRecall = mean(comparable.map((r) => r.knodin?.unchangedSupportRecallAtK));
376
+ const meanRgUnchangedSupportRecall = mean(comparable.map((r) => r.rg?.unchangedSupportRecallAtK));
377
+ const nDcgImprovement = meanKnodinNDcg !== null && meanRgNDcg !== null ? meanKnodinNDcg - meanRgNDcg : null;
378
+ const recallImprovement = meanKnodinRecall !== null && meanRgRecall !== null ? meanKnodinRecall - meanRgRecall : null;
379
+ const retain = comparable.length > 0 &&
380
+ regressions === 0 &&
381
+ nDcgImprovement !== null &&
382
+ recallImprovement !== null &&
383
+ nDcgImprovement >= thresholds.minNDcgDelta &&
384
+ recallImprovement >= thresholds.minRecallDelta;
385
+ return {
386
+ schemaVersion: 1,
387
+ k,
388
+ thresholds,
389
+ denominators: {
390
+ totalCases: receipts.length,
391
+ evaluatedCases: comparable.length,
392
+ excludedCases,
393
+ emptyRetrievalCases,
394
+ regressions,
395
+ },
396
+ meanKnodinNDcg,
397
+ meanRgNDcg,
398
+ meanKnodinRecall,
399
+ meanRgRecall,
400
+ meanKnodinUnchangedSupportRecall,
401
+ meanRgUnchangedSupportRecall,
402
+ disposition: retain ? "retain-candidate" : "no-go-keep-incumbent",
403
+ dispositionReason: retain
404
+ ? "candidate improved declared usefulness and recall outcomes without quality, budget, or memory regression"
405
+ : comparable.length === 0
406
+ ? "no valid comparable cases were evaluated"
407
+ : regressions > 0
408
+ ? `${regressions} case(s) exhibited quality, budget, or memory regression`
409
+ : "observed improvement did not clear declared nDCG/recall thresholds",
410
+ receipts,
411
+ };
412
+ }