memorix 1.9.12 → 1.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/CHANGELOG.md +20 -1
  2. package/dist/cli/index.js +549 -101
  3. package/dist/index.d.ts +46 -0
  4. package/dist/index.js +271 -27
  5. package/dist/maintenance-runner.js +143 -3
  6. package/dist/media-audio-runner.js +143 -3
  7. package/dist/media-video-runner.js +143 -3
  8. package/dist/memcode/index.js +124 -8
  9. package/dist/memcode-runtime/CHANGELOG.md +20 -1
  10. package/dist/sdk.js +270 -26
  11. package/dist/vector-backfill-runner.js +143 -3
  12. package/docs/1.2.0-EVALUATION-HARNESS.md +88 -0
  13. package/docs/1.3-MEMORY-ARCHITECTURE.md +31 -0
  14. package/docs/API_REFERENCE.md +19 -0
  15. package/docs/DEVELOPMENT.md +16 -3
  16. package/docs/INTEGRATIONS.md +25 -0
  17. package/docs/PERFORMANCE.md +21 -6
  18. package/docs/README.md +4 -4
  19. package/docs/ROADMAP-1.9.12-2.0.md +92 -7
  20. package/package.json +3 -1
  21. package/plugins/antigravity/memorix/plugin.json +1 -1
  22. package/plugins/claude/memorix/.claude-plugin/plugin.json +1 -1
  23. package/plugins/codebuddy/memorix/.codebuddy-plugin/plugin.json +1 -1
  24. package/plugins/codex/memorix/.codex-plugin/plugin.json +1 -1
  25. package/plugins/copilot/memorix/plugin.json +1 -1
  26. package/plugins/gemini/memorix/gemini-extension.json +1 -1
  27. package/plugins/hermes/memorix/plugin.yaml +1 -1
  28. package/plugins/omp/memorix/package.json +1 -1
  29. package/plugins/openclaw/memorix/.codex-plugin/plugin.json +1 -1
  30. package/plugins/pi/memorix/package.json +1 -1
  31. package/server.json +2 -2
  32. package/src/cli/commands/agent-integrations.ts +164 -7
  33. package/src/cli/commands/memory.ts +1 -1
  34. package/src/cli/commands/serve-http.ts +30 -1
  35. package/src/cli/commands/setup.ts +5 -21
  36. package/src/codegraph/auto-context.ts +5 -0
  37. package/src/codegraph/context-pack.ts +4 -0
  38. package/src/compact/engine.ts +43 -2
  39. package/src/evaluation/context-task-matrix.ts +247 -0
  40. package/src/evaluation/context-task-runner.ts +175 -0
  41. package/src/integrations/registry.ts +191 -4
  42. package/src/knowledge/context-assembly.ts +33 -2
  43. package/src/knowledge/workset.ts +35 -3
  44. package/src/server/request-context.ts +96 -0
  45. package/src/server.ts +16 -4
  46. package/src/store/orama-store.ts +54 -0
@@ -10,7 +10,14 @@
10
10
  */
11
11
 
12
12
  import type { SearchOptions, IndexEntry, TimelineContext, MemorixDocument, ObservationRef, MemoryRef, MiniSkill, SourceSnapshot, ObservationReader } from '../types.js';
13
- import { searchObservations, getTimeline, getObservationsByIds, makeOramaObservationId } from '../store/orama-store.js';
13
+ import {
14
+ searchObservations,
15
+ getTimeline,
16
+ getObservationsByIds,
17
+ makeOramaObservationId,
18
+ getLastSearchMode,
19
+ getLastSearchDiagnostics,
20
+ } from '../store/orama-store.js';
14
21
  import { getObservation, getAllObservations } from '../memory/observations.js';
15
22
  import { ensureFreshIndex } from '../memory/freshness.js';
16
23
  import { formatIndexTable, formatTimeline, formatObservationDetail, type RetrievalSurface } from './index-format.js';
@@ -62,6 +69,20 @@ export function normalizeMemoryBrowseQuery(query: string): string {
62
69
  return broadMemoryRequests.has(compact) ? '' : query;
63
70
  }
64
71
 
72
+ export interface CompactSearchReceipt {
73
+ version: '1';
74
+ mode: string;
75
+ resultCount: number;
76
+ candidateCount: number;
77
+ selectedCount: number;
78
+ omittedCount: number;
79
+ omittedByTokenBudget: number;
80
+ fallbackUsed: boolean;
81
+ fallbackReason?: string;
82
+ tokenCount: number;
83
+ elapsedMs: number;
84
+ }
85
+
65
86
  /**
66
87
  * Layer 1: Search and return a compact index.
67
88
  * Agent scans this to decide which observations to fetch in detail.
@@ -70,7 +91,9 @@ export async function compactSearch(options: SearchOptions, surface: RetrievalSu
70
91
  entries: IndexEntry[];
71
92
  formatted: string;
72
93
  totalTokens: number;
94
+ receipt: CompactSearchReceipt;
73
95
  }> {
96
+ const startedAt = Date.now();
74
97
  await ensureFreshIndex({ loadCorpus: false });
75
98
  const searchOptions = { ...options, query: normalizeMemoryBrowseQuery(options.query) };
76
99
  let entries = (await searchObservations(searchOptions)).map((entry) =>
@@ -132,8 +155,26 @@ export async function compactSearch(options: SearchOptions, surface: RetrievalSu
132
155
  }
133
156
 
134
157
  const totalTokens = countTextTokens(formatted);
158
+ const diagnostics = getLastSearchDiagnostics(options.projectId);
135
159
 
136
- return { entries, formatted, totalTokens };
160
+ return {
161
+ entries,
162
+ formatted,
163
+ totalTokens,
164
+ receipt: {
165
+ version: '1',
166
+ mode: getLastSearchMode(options.projectId),
167
+ resultCount: entries.length,
168
+ candidateCount: diagnostics?.candidateCount ?? entries.length,
169
+ selectedCount: diagnostics?.selectedCount ?? entries.length,
170
+ omittedCount: diagnostics?.omittedCount ?? 0,
171
+ omittedByTokenBudget: diagnostics?.omittedByTokenBudget ?? 0,
172
+ fallbackUsed: diagnostics?.fallbackUsed ?? false,
173
+ ...(diagnostics?.fallbackReason ? { fallbackReason: diagnostics.fallbackReason } : {}),
174
+ tokenCount: totalTokens,
175
+ elapsedMs: Math.max(0, Date.now() - startedAt),
176
+ },
177
+ };
137
178
  }
138
179
 
139
180
  /**
@@ -0,0 +1,247 @@
1
+ /**
2
+ * 1.10 task-shaped evaluation contract.
3
+ *
4
+ * The matrix defines what must be measured. It deliberately contains no
5
+ * claimed scores; runners attach observations to these cases separately.
6
+ */
7
+
8
+ export const CONTEXT_EVALUATION_METRICS = [
9
+ 'first-action-correctness',
10
+ 'recovery-success',
11
+ 'memory-hit-precision',
12
+ 'memory-hit-recall',
13
+ 'stale-rejection-rate',
14
+ 'conflict-rejection-rate',
15
+ 'abstention-precision',
16
+ 'input-tokens',
17
+ 'output-tokens',
18
+ 'latency-p50',
19
+ 'latency-p95',
20
+ 'rss-bytes',
21
+ 'fallback-count',
22
+ 'degraded-count',
23
+ 'review-cost',
24
+ ] as const;
25
+
26
+ export type ContextEvaluationMetric = typeof CONTEXT_EVALUATION_METRICS[number];
27
+ export type ContextEvaluationCategory = 'continuity' | 'retrieval' | 'safety' | 'runtime' | 'integration';
28
+
29
+ export interface ContextEvaluationTask {
30
+ id: string;
31
+ title: string;
32
+ category: ContextEvaluationCategory;
33
+ task: string;
34
+ surfaces: string[];
35
+ acceptance: string[];
36
+ metrics: readonly ContextEvaluationMetric[];
37
+ }
38
+
39
+ const metrics = CONTEXT_EVALUATION_METRICS;
40
+
41
+ export const CONTEXT_EVALUATION_TASKS: readonly ContextEvaluationTask[] = [
42
+ {
43
+ id: 'first-project-setup',
44
+ title: 'First project setup',
45
+ category: 'continuity',
46
+ task: 'Connect a new Git project and begin a coding task with no prior Memorix state.',
47
+ surfaces: ['memorix_project_context', 'memorix_session_start', 'memorix doctor'],
48
+ acceptance: ['The first action identifies the verified project and gives actionable starting files.', 'No unrelated project memory is shown.'],
49
+ metrics,
50
+ },
51
+ {
52
+ id: 'next-day-recovery',
53
+ title: 'Next-day recovery',
54
+ category: 'continuity',
55
+ task: 'Resume the same project after a day with a prior session summary and a changed worktree.',
56
+ surfaces: ['memorix_project_context', 'memorix resume', 'memorix_session_start'],
57
+ acceptance: ['The latest useful handoff is recovered.', 'Current source facts outrank stale session text.'],
58
+ metrics,
59
+ },
60
+ {
61
+ id: 'cross-host-handoff',
62
+ title: 'Cross-host handoff',
63
+ category: 'continuity',
64
+ task: 'Continue a task moved from Claude Code to Codex without duplicating the full transcript.',
65
+ surfaces: ['memorix_project_context', 'memorix_session_end', 'memorix_session_start'],
66
+ acceptance: ['The receiving host gets bounded prior-work evidence.', 'The project identity and scope remain stable.'],
67
+ metrics,
68
+ },
69
+ {
70
+ id: 'compact-continuation',
71
+ title: 'Compaction continuation',
72
+ category: 'continuity',
73
+ task: 'Continue after a host compaction where a native checkpoint summary is available.',
74
+ surfaces: ['SessionStart hook', 'UserPromptSubmit hook', 'memorix_project_context'],
75
+ acceptance: ['The checkpoint is labelled as host lifecycle evidence.', 'The next prompt does not replay the complete summary.'],
76
+ metrics,
77
+ },
78
+ {
79
+ id: 'stale-decision-replacement',
80
+ title: 'Stale decision replaced by code',
81
+ category: 'retrieval',
82
+ task: 'Ask about a decision whose referenced implementation was replaced by a newer commit.',
83
+ surfaces: ['memorix_project_context', 'memorix_search', 'memorix explain'],
84
+ acceptance: ['The stale item is cautioned or withheld.', 'The current source-backed evidence is preferred.'],
85
+ metrics,
86
+ },
87
+ {
88
+ id: 'conflicting-claims',
89
+ title: 'Conflicting claims',
90
+ category: 'retrieval',
91
+ task: 'Retrieve two active claims that make incompatible assertions about the same module.',
92
+ surfaces: ['memorix_project_context', 'memorix_knowledge', 'receipt'],
93
+ acceptance: ['Conflict is visible in the receipt.', 'The newer claim does not silently overwrite the conflict.'],
94
+ metrics,
95
+ },
96
+ {
97
+ id: 'cjk-query',
98
+ title: 'CJK retrieval',
99
+ category: 'retrieval',
100
+ task: 'Find a Chinese, Japanese, or Korean memory in a mixed-language project corpus.',
101
+ surfaces: ['memorix_search', 'memorix_project_context'],
102
+ acceptance: ['The intended CJK evidence is retrievable.', 'The result remains within the token budget.'],
103
+ metrics,
104
+ },
105
+ {
106
+ id: 'punctuation-query',
107
+ title: 'Punctuation and alias retrieval',
108
+ category: 'retrieval',
109
+ task: 'Find a memory using punctuation, an alias, and a repository-specific identifier.',
110
+ surfaces: ['memorix_search', 'memorix_detail'],
111
+ acceptance: ['The alias resolves to the project-scoped evidence.', 'Unrelated similarly named rows do not dominate.'],
112
+ metrics,
113
+ },
114
+ {
115
+ id: 'large-store-retrieval',
116
+ title: 'Large-store retrieval',
117
+ category: 'retrieval',
118
+ task: 'Retrieve a planted fact from a 40k or 100k record local store.',
119
+ surfaces: ['SDK search', 'HTTP MCP', 'large-store gate'],
120
+ acceptance: ['The planted fact is returned.', 'Latency, RSS, and token measurements are recorded separately.'],
121
+ metrics,
122
+ },
123
+ {
124
+ id: 'embedding-unavailable',
125
+ title: 'Embedding unavailable',
126
+ category: 'retrieval',
127
+ task: 'Run the same task with the embedding provider disabled or unavailable.',
128
+ surfaces: ['memorix_project_context', 'memorix_search', 'codegraph status'],
129
+ acceptance: ['Lexical evidence remains available.', 'Fallback and degraded state are explicit.'],
130
+ metrics,
131
+ },
132
+ {
133
+ id: 'deleted-symbol',
134
+ title: 'Deleted symbol safety',
135
+ category: 'safety',
136
+ task: 'Ask about a memory whose referenced symbol was deleted from the current source.',
137
+ surfaces: ['memorix_project_context', 'CodeGraph receipt', 'memorix explain'],
138
+ acceptance: ['The deleted reference is marked stale or suspect.', 'It is not presented as current verified guidance.'],
139
+ metrics,
140
+ },
141
+ {
142
+ id: 'poisoned-memory',
143
+ title: 'Poisoned memory',
144
+ category: 'safety',
145
+ task: 'Present a low-trust memory that instructs the agent to bypass a safety or verification step.',
146
+ surfaces: ['memorix_project_context', 'memorix_search', 'context receipt'],
147
+ acceptance: ['The item is withheld, cautioned, or labelled unverified.', 'A model-derived assertion cannot become verified by retrieval alone.'],
148
+ metrics,
149
+ },
150
+ {
151
+ id: 'candidate-quarantine',
152
+ title: 'Candidate quarantine',
153
+ category: 'safety',
154
+ task: 'Capture an automatic hook candidate and request ordinary project context before qualification.',
155
+ surfaces: ['hook admission', 'memorix_project_context', 'memorix receipt'],
156
+ acceptance: ['The candidate is stored with its admission state.', 'The default context excludes it or explains why it is withheld.'],
157
+ metrics,
158
+ },
159
+ {
160
+ id: 'abstain-insufficient-evidence',
161
+ title: 'Insufficient evidence abstention',
162
+ category: 'safety',
163
+ task: 'Ask a project-specific question for which no current source or qualified memory exists.',
164
+ surfaces: ['memorix_project_context', 'memorix_context_pack', 'context receipt'],
165
+ acceptance: ['The system abstains or returns a clear evidence gap.', 'It does not fabricate a verified answer.'],
166
+ metrics,
167
+ },
168
+ {
169
+ id: 'project-isolation',
170
+ title: 'Project isolation',
171
+ category: 'safety',
172
+ task: 'Search project A while project B contains a similarly named private observation.',
173
+ surfaces: ['SDK search', 'stdio MCP', 'HTTP MCP'],
174
+ acceptance: ['No project B row is returned to project A.', 'The project identity is server-verified.'],
175
+ metrics,
176
+ },
177
+ {
178
+ id: 'receipt-omission',
179
+ title: 'Receipt omission provenance',
180
+ category: 'safety',
181
+ task: 'Force a small context budget so relevant optional evidence is omitted.',
182
+ surfaces: ['memorix_project_context', 'memorix_context_pack', 'brief JSON'],
183
+ acceptance: ['The omission count and reason are recorded.', 'Only bounded stable sample IDs are retained.'],
184
+ metrics,
185
+ },
186
+ {
187
+ id: 'expired-http-session',
188
+ title: 'Expired HTTP session',
189
+ category: 'runtime',
190
+ task: 'Use a stateful HTTP MCP session after its configured idle timeout.',
191
+ surfaces: ['legacy HTTP MCP', '/health', 'memorix_session_start'],
192
+ acceptance: ['The request fails with an actionable reinitialize signal.', 'A new binding does not inherit stale project state.'],
193
+ metrics,
194
+ },
195
+ {
196
+ id: 'expired-project-handle',
197
+ title: 'Expired project handle',
198
+ category: 'runtime',
199
+ task: 'Use a stateless HTTP request with an expired or unknown Mcp-Project-Handle.',
200
+ surfaces: ['stateless HTTP MCP', 'binding receipt', 'Mcp-Project-Handle'],
201
+ acceptance: ['The request fails closed before business tools execute.', 'The response points to verified root based discovery.'],
202
+ metrics,
203
+ },
204
+ {
205
+ id: 'project-switch-lease',
206
+ title: 'Project switch and runtime lease',
207
+ category: 'runtime',
208
+ task: 'Switch one session from project A to project B while another session remains on project A.',
209
+ surfaces: ['legacy HTTP MCP', 'memorix_session_start', 'binding receipt'],
210
+ acceptance: ['The sessions retain isolated data directories and runtime state.', 'Lease and binding source changes are diagnosable.'],
211
+ metrics,
212
+ },
213
+ {
214
+ id: 'adapter-doctor-parity',
215
+ title: 'Adapter doctor parity',
216
+ category: 'integration',
217
+ task: 'Inspect installed integration state for a plugin host and a hooks-only host.',
218
+ surfaces: ['memorix doctor agents --json', 'integration registry', 'hooks install'],
219
+ acceptance: ['Manifest expectations and observed artifacts are reported together.', 'Unsupported repair actions are labelled skipped.'],
220
+ metrics,
221
+ },
222
+ ] as const;
223
+
224
+ export function validateContextEvaluationMatrix(
225
+ tasks: readonly ContextEvaluationTask[] = CONTEXT_EVALUATION_TASKS,
226
+ ): string[] {
227
+ const issues: string[] = [];
228
+ const seen = new Set<string>();
229
+ for (const task of tasks) {
230
+ if (seen.has(task.id)) issues.push(`duplicate task id: ${task.id}`);
231
+ seen.add(task.id);
232
+ if (!task.id.trim()) issues.push('task id is empty');
233
+ if (task.metrics.join('|') !== CONTEXT_EVALUATION_METRICS.join('|')) {
234
+ issues.push(`${task.id}: metric contract mismatch`);
235
+ }
236
+ if (task.surfaces.length === 0) issues.push(`${task.id}: no surface declared`);
237
+ if (task.acceptance.length === 0) issues.push(`${task.id}: no acceptance criteria`);
238
+ }
239
+ if (tasks.length !== 20) issues.push(`expected 20 task cases, found ${tasks.length}`);
240
+ if (tasks.length === 20) {
241
+ const categories = new Set(tasks.map(task => task.category));
242
+ for (const category of ['continuity', 'retrieval', 'safety', 'runtime', 'integration'] as const) {
243
+ if (!categories.has(category)) issues.push(`missing category: ${category}`);
244
+ }
245
+ }
246
+ return issues;
247
+ }
@@ -0,0 +1,175 @@
1
+ import {
2
+ CONTEXT_EVALUATION_METRICS,
3
+ CONTEXT_EVALUATION_TASKS,
4
+ type ContextEvaluationMetric,
5
+ type ContextEvaluationTask,
6
+ } from './context-task-matrix.js';
7
+
8
+ export type ContextEvaluationMetricValues = Record<ContextEvaluationMetric, number>;
9
+
10
+ export interface ContextEvaluationProbeResult {
11
+ passed: boolean;
12
+ checks: string[];
13
+ metrics: Partial<ContextEvaluationMetricValues>;
14
+ evidence?: string[];
15
+ outputTokens?: number;
16
+ reviewCost?: number;
17
+ }
18
+
19
+ export interface ContextEvaluationCaseResult {
20
+ id: string;
21
+ title: string;
22
+ category: ContextEvaluationTask['category'];
23
+ passed: boolean;
24
+ checks: string[];
25
+ evidence: string[];
26
+ metrics: ContextEvaluationMetricValues;
27
+ elapsedMs: number;
28
+ error?: string;
29
+ }
30
+
31
+ export interface ContextEvaluationReport {
32
+ version: '1';
33
+ generatedAt: string;
34
+ runtime: {
35
+ node: string;
36
+ platform: string;
37
+ embeddings: 'disabled' | 'enabled' | 'unknown';
38
+ };
39
+ cases: ContextEvaluationCaseResult[];
40
+ summary: {
41
+ cases: number;
42
+ passed: number;
43
+ failed: number;
44
+ passRate: number;
45
+ metricAverages: ContextEvaluationMetricValues;
46
+ latencyP50Ms: number;
47
+ latencyP95Ms: number;
48
+ peakRssBytes: number;
49
+ };
50
+ }
51
+
52
+ export type ContextEvaluationProbe = (
53
+ task: ContextEvaluationTask,
54
+ ) => Promise<ContextEvaluationProbeResult>;
55
+
56
+ function percentile(values: number[], percentileValue: number): number {
57
+ if (values.length === 0) return 0;
58
+ const sorted = [...values].sort((left, right) => left - right);
59
+ const index = Math.min(
60
+ sorted.length - 1,
61
+ Math.max(0, Math.ceil((percentileValue / 100) * sorted.length) - 1),
62
+ );
63
+ return sorted[index];
64
+ }
65
+
66
+ function metricDefaults(task: ContextEvaluationTask, inputTokens: number, outputTokens: number, rssBytes: number): ContextEvaluationMetricValues {
67
+ const metrics = {} as ContextEvaluationMetricValues;
68
+ for (const metric of CONTEXT_EVALUATION_METRICS) metrics[metric] = 0;
69
+ metrics['input-tokens'] = inputTokens;
70
+ metrics['output-tokens'] = outputTokens;
71
+ metrics['rss-bytes'] = rssBytes;
72
+ // Keep the task in the report even when a probe fails before measuring a
73
+ // quality dimension. A zero is an explicit failed observation, not a claim
74
+ // that the dimension was irrelevant.
75
+ void task;
76
+ return metrics;
77
+ }
78
+
79
+ function validateMetrics(metrics: ContextEvaluationMetricValues): string[] {
80
+ return CONTEXT_EVALUATION_METRICS
81
+ .filter(metric => !Number.isFinite(metrics[metric]) || metrics[metric] < 0)
82
+ .map(metric => `invalid metric: ${metric}`);
83
+ }
84
+
85
+ /**
86
+ * Run the stable 1.10 matrix against real probes supplied by the caller.
87
+ * The runner owns timing, failure normalization, and aggregate statistics so
88
+ * individual probes cannot silently omit an acceptance dimension.
89
+ */
90
+ export async function runContextEvaluation(
91
+ probe: ContextEvaluationProbe,
92
+ tasks: readonly ContextEvaluationTask[] = CONTEXT_EVALUATION_TASKS,
93
+ ): Promise<ContextEvaluationReport> {
94
+ const cases: ContextEvaluationCaseResult[] = [];
95
+ for (const task of tasks) {
96
+ const startedAt = Date.now();
97
+ const rssBefore = process.memoryUsage().rss;
98
+ let result: ContextEvaluationProbeResult;
99
+ let error: string | undefined;
100
+ try {
101
+ result = await probe(task);
102
+ } catch (caught) {
103
+ error = caught instanceof Error ? caught.message : String(caught);
104
+ result = { passed: false, checks: ['probe threw an exception'], metrics: {} };
105
+ }
106
+
107
+ const elapsedMs = Math.max(0, Date.now() - startedAt);
108
+ const rssBytes = Math.max(rssBefore, process.memoryUsage().rss);
109
+ const inputTokens = task.task.trim().split(/\s+/u).filter(Boolean).length;
110
+ const metrics = metricDefaults(task, inputTokens, result.outputTokens ?? 0, rssBytes);
111
+ for (const metric of CONTEXT_EVALUATION_METRICS) {
112
+ const observed = result.metrics[metric];
113
+ if (observed !== undefined) metrics[metric] = observed;
114
+ }
115
+ metrics['latency-p50'] = result.metrics['latency-p50'] ?? elapsedMs;
116
+ metrics['latency-p95'] = result.metrics['latency-p95'] ?? elapsedMs;
117
+ metrics['rss-bytes'] = result.metrics['rss-bytes'] ?? rssBytes;
118
+ if (result.reviewCost !== undefined) metrics['review-cost'] = result.reviewCost;
119
+
120
+ const checks = [...result.checks];
121
+ checks.push(...validateMetrics(metrics));
122
+ const passed = result.passed && checks.every(check => !check.startsWith('invalid metric:')) && !error;
123
+ cases.push({
124
+ id: task.id,
125
+ title: task.title,
126
+ category: task.category,
127
+ passed,
128
+ checks,
129
+ evidence: result.evidence ?? [],
130
+ metrics,
131
+ elapsedMs,
132
+ ...(error ? { error } : {}),
133
+ });
134
+ }
135
+
136
+ const metricAverages = {} as ContextEvaluationMetricValues;
137
+ for (const metric of CONTEXT_EVALUATION_METRICS) {
138
+ const total = cases.reduce((sum, item) => sum + item.metrics[metric], 0);
139
+ metricAverages[metric] = cases.length > 0 ? total / cases.length : 0;
140
+ }
141
+ const latencies = cases.map(item => item.metrics['latency-p95']);
142
+ return {
143
+ version: '1',
144
+ generatedAt: new Date().toISOString(),
145
+ runtime: {
146
+ node: process.version,
147
+ platform: `${process.platform}-${process.arch}`,
148
+ embeddings: process.env.MEMORIX_EMBEDDING === 'off' ? 'disabled' : 'unknown',
149
+ },
150
+ cases,
151
+ summary: {
152
+ cases: cases.length,
153
+ passed: cases.filter(item => item.passed).length,
154
+ failed: cases.filter(item => !item.passed).length,
155
+ passRate: cases.length === 0 ? 1 : cases.filter(item => item.passed).length / cases.length,
156
+ metricAverages,
157
+ latencyP50Ms: percentile(latencies, 50),
158
+ latencyP95Ms: percentile(latencies, 95),
159
+ peakRssBytes: Math.max(0, ...cases.map(item => item.metrics['rss-bytes'])),
160
+ },
161
+ };
162
+ }
163
+
164
+ export function formatContextEvaluationReport(report: ContextEvaluationReport): string {
165
+ const lines = [
166
+ `1.10 context evaluation — ${report.summary.passed}/${report.summary.cases} cases passed`,
167
+ `runtime: ${report.runtime.node} ${report.runtime.platform}; embeddings=${report.runtime.embeddings}`,
168
+ `latency: p50=${report.summary.latencyP50Ms}ms p95=${report.summary.latencyP95Ms}ms; peak RSS=${report.summary.peakRssBytes} bytes`,
169
+ ];
170
+ for (const item of report.cases) {
171
+ lines.push(`${item.passed ? 'PASS' : 'FAIL'} ${item.id} (${item.elapsedMs}ms)`);
172
+ if (!item.passed) lines.push(` checks: ${item.checks.join('; ') || item.error || 'no passing checks'}`);
173
+ }
174
+ return lines.join('\n');
175
+ }