bilmem 0.1.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.
@@ -0,0 +1,311 @@
1
+ import { d as EvidenceRelation, r as ReconciliationResult, K as Knowledge, q as ReconciliationAction, C as ConfidenceTier, o as Observation, c as Evidence, n as KnowledgeType, m as KnowledgeStatus, l as KnowledgeStage, S as Scope, i as KnowledgeHistoryEntry, k as KnowledgeOutcomesSummary, P as Provenance, L as UnknownState, H as UnknownReason, G as UnknownNextAction, U as UnknownRecord, b as BilmemMetrics, p as OutcomeRecord, O as OutcomeType, T as TaskTrajectory, g as KnowledgeBudgetConfig, A as ActionType, R as ResolveOptions, a as ResolutionResult } from '../types-Nxq5Gzay.js';
2
+ export { B as BilmemConfig, E as EvaluatedRule, I as InvestigationReceipt, e as JevExplanation, f as JevMatchStatus, J as JevResult, h as KnowledgeDiff, j as KnowledgeMetrics, N as NextEvidenceAction, s as RelationType, t as ResolutionReason, u as ResolutionState, v as RevisionSnapshot, w as RuleCondition, x as RuleDefinition, y as RuleSet, z as TemporalMetadata, D as TrajectoryEvent, F as TrajectoryEventType } from '../types-Nxq5Gzay.js';
3
+ import { M as MetricEvent, S as Storage } from '../canonical-CglQQ0xc.js';
4
+ import { BilmemRetriever as Retriever, OramaIndex as SearchIndex } from '../search/index.js';
5
+
6
+ /**
7
+ * Lightweight, in-memory graph structure for managing relations between
8
+ * files, observations, evidence, and knowledge nodes.
9
+ */
10
+ declare class EvidenceGraph {
11
+ private fromMap;
12
+ private toMap;
13
+ constructor(relations?: EvidenceRelation[]);
14
+ addRelation(relation: EvidenceRelation): void;
15
+ getRelationsFrom(fromId: string): EvidenceRelation[];
16
+ getRelationsTo(toId: string): EvidenceRelation[];
17
+ getRelationsBetween(fromId: string, toId: string): EvidenceRelation[];
18
+ getAllRelations(): EvidenceRelation[];
19
+ findCoChanged(file: string, threshold?: number): Array<{
20
+ file: string;
21
+ weight: number;
22
+ }>;
23
+ findConnected(id: string, maxDepth?: number): string[];
24
+ toJSON(): EvidenceRelation[];
25
+ static fromJSON(relations: EvidenceRelation[]): EvidenceGraph;
26
+ }
27
+
28
+ /**
29
+ * Deterministic mapping between confidence tiers and normalized float scores.
30
+ * Replaces arbitrary precision floats with explainable thresholds.
31
+ */
32
+ declare function tierToConfidence(tier: ConfidenceTier): number;
33
+ declare function confidenceToTier(score: number): ConfidenceTier;
34
+ declare function hashString(input: string): string;
35
+ declare function createObservation(params: {
36
+ source: string;
37
+ claim: string;
38
+ provenance?: Provenance;
39
+ confidence?: number;
40
+ positive?: string[];
41
+ negative?: string[];
42
+ details?: Record<string, unknown>;
43
+ }): Observation;
44
+ /**
45
+ * Creates or consolidates evidence based on underlying source.
46
+ * Crucial constraint: Multiple agents reading the same source must NOT count as independent evidence.
47
+ */
48
+ declare function createEvidence(observation: Observation, type?: 'supports' | 'contradicts' | 'observes'): Evidence;
49
+ declare function createKnowledge(params: {
50
+ id: string;
51
+ type?: KnowledgeType;
52
+ status?: KnowledgeStatus;
53
+ stage?: KnowledgeStage;
54
+ statement: string;
55
+ positive?: string[];
56
+ negative?: string[];
57
+ relations?: string[];
58
+ depends_on?: string[];
59
+ resolves?: string[];
60
+ question?: string;
61
+ confidence?: number;
62
+ confidenceTier?: ConfidenceTier;
63
+ evidence?: string[];
64
+ scope?: Scope;
65
+ tags?: string[];
66
+ history?: KnowledgeHistoryEntry[];
67
+ outcomesSummary?: KnowledgeOutcomesSummary;
68
+ }): Knowledge;
69
+ /**
70
+ * Calculate effective confidence combining evidence ratio and outcome history.
71
+ */
72
+ declare function calculateEffectiveConfidence(knowledge: Knowledge): number;
73
+ /**
74
+ * Checks if two statements express opposite polarity or semantic contradiction.
75
+ * Essential rule: High lexical similarity does NOT imply MERGE.
76
+ * "cache enabled in production" vs "cache disabled in production" have opposite polarity.
77
+ */
78
+ declare function detectPolarContradiction(stmtA: string, stmtB: string): {
79
+ contradicted: boolean;
80
+ reason?: string;
81
+ };
82
+ /**
83
+ * Reconcile an incoming candidate lesson with existing knowledge.
84
+ * Classifies the action as: NEW, MERGE, UPDATE, SUPPORT, CONTRADICT, SPECIALIZE, GENERALIZE, IGNORE.
85
+ */
86
+ declare function reconcileKnowledge(candidate: Partial<Knowledge> & {
87
+ statement: string;
88
+ }, existingList: Knowledge[]): ReconciliationResult;
89
+ /**
90
+ * Apply reconciliation to knowledge base.
91
+ */
92
+ declare function applyReconciliation(reconciliation: ReconciliationResult, candidate: Partial<Knowledge> & {
93
+ statement: string;
94
+ }, existingList: Knowledge[], storage?: {
95
+ appendMetricEvent(event: MetricEvent): Promise<void>;
96
+ }): {
97
+ updatedKnowledge: Knowledge;
98
+ action: ReconciliationAction;
99
+ createdId: string;
100
+ };
101
+
102
+ declare function createUnknown(params: {
103
+ id: string;
104
+ state?: UnknownState;
105
+ reason?: UnknownReason;
106
+ statement?: string;
107
+ checked?: string[];
108
+ next?: UnknownNextAction;
109
+ scope?: Scope;
110
+ }): UnknownRecord;
111
+ /**
112
+ * Checks if a specific path or query was already investigated,
113
+ * helping agents avoid repeating useless investigations.
114
+ */
115
+ declare function hasBeenInvestigated(unknowns: UnknownRecord[], target: string): {
116
+ investigated: boolean;
117
+ record?: UnknownRecord;
118
+ reason?: string;
119
+ };
120
+ /**
121
+ * Update an existing unknown with new checked paths or update its state when partially known or resolved.
122
+ */
123
+ declare function updateUnknown(record: UnknownRecord, updates: {
124
+ state?: UnknownState;
125
+ reason?: UnknownReason;
126
+ statement?: string;
127
+ addChecked?: string[];
128
+ next?: UnknownNextAction;
129
+ }): UnknownRecord;
130
+
131
+ declare function createOutcome(params: {
132
+ knowledgeId?: string;
133
+ taskId?: string;
134
+ result: OutcomeType;
135
+ context?: {
136
+ positive?: string[];
137
+ negative?: string[];
138
+ };
139
+ feedback?: string;
140
+ }): OutcomeRecord;
141
+ /**
142
+ * Apply outcome to a knowledge unit and recalculate its confidence.
143
+ */
144
+ declare function applyOutcomeToKnowledge(knowledge: Knowledge, outcome: OutcomeRecord): Knowledge;
145
+ declare class MetricsTracker {
146
+ private metrics;
147
+ constructor(initial?: Partial<BilmemMetrics>);
148
+ recordHit(): void;
149
+ recordMiss(): void;
150
+ recordReused(): void;
151
+ recordUnknownResolved(): void;
152
+ recordInvestigationPrevented(): void;
153
+ recordCandidateMerged(): void;
154
+ recordStaleDetected(): void;
155
+ recordContradiction(): void;
156
+ recordPromoted(): void;
157
+ recordSuperseded(): void;
158
+ getMetrics(): BilmemMetrics;
159
+ toJSON(): BilmemMetrics;
160
+ }
161
+
162
+ interface DistilledLesson {
163
+ id: string;
164
+ statement: string;
165
+ positive: string[];
166
+ negative: string[];
167
+ confidence: number;
168
+ evidence: string[];
169
+ tags: string[];
170
+ reasoning: string;
171
+ }
172
+ interface TrajectoryLearningResult {
173
+ taskId: string;
174
+ observations: Observation[];
175
+ evidence: Evidence[];
176
+ candidateLessons: Array<Partial<Knowledge> & {
177
+ statement: string;
178
+ }>;
179
+ reconciliations: Array<{
180
+ candidate: Partial<Knowledge> & {
181
+ statement: string;
182
+ };
183
+ result: ReconciliationResult;
184
+ appliedKnowledge?: Knowledge;
185
+ action: ReconciliationAction;
186
+ }>;
187
+ dryRun: boolean;
188
+ }
189
+ /**
190
+ * Distill a task trajectory into a compact, reusable candidate lesson.
191
+ * Avoids dumping raw trajectories into permanent memory;
192
+ * extracts only the crystallized insight (what worked, what failed, negative patterns).
193
+ */
194
+ declare function distillTrajectory(trajectory: TaskTrajectory): DistilledLesson | null;
195
+ /**
196
+ * Executes the complete staged trajectory learning pipeline:
197
+ * trajectory → observations → candidate lessons → reconcile → knowledge
198
+ *
199
+ * Honors the "Memory should grow by refinement, not accumulation" principle.
200
+ * Raw trajectory is never dumped directly to knowledge.
201
+ */
202
+ declare function learnFromTrajectory(trajectory: TaskTrajectory, existingKnowledge?: Knowledge[], options?: {
203
+ dryRun?: boolean;
204
+ storage?: {
205
+ appendMetricEvent(event: any): Promise<void>;
206
+ };
207
+ }): TrajectoryLearningResult;
208
+ /**
209
+ * Handle explicit user correction as high-quality evidence.
210
+ * Prevents future agents from repeatedly making the same invalid assumption.
211
+ */
212
+ declare function processUserCorrection(params: {
213
+ topic: string;
214
+ incorrectAssumption: string;
215
+ correctFact: string;
216
+ context?: string[];
217
+ author?: string;
218
+ }): {
219
+ observation: Observation;
220
+ knowledge: Knowledge;
221
+ };
222
+
223
+ interface SourceDependencyIndex {
224
+ sourceToKnowledge: Map<string, Set<string>>;
225
+ }
226
+ declare function normalizeSourceKey(source: string): string;
227
+ /**
228
+ * Builds a reverse index mapping source paths / files to the knowledge IDs that depend on them.
229
+ */
230
+ declare function buildDependencyIndex(knowledgeList: Knowledge[]): SourceDependencyIndex;
231
+ interface StalenessCheckResult {
232
+ knowledgeId: string;
233
+ affected: boolean;
234
+ status: KnowledgeStatus;
235
+ changedSources: string[];
236
+ unchangedSources: string[];
237
+ reason?: string;
238
+ }
239
+ /**
240
+ * Checks a knowledge item against a list of changed file paths / sources.
241
+ * If any supporting dependency changed, marks as 'needs_revalidation'.
242
+ */
243
+ declare function checkKnowledgeStaleness(knowledge: Knowledge, changedSources: string[]): StalenessCheckResult;
244
+ /**
245
+ * Marks knowledge units as 'needs_revalidation' when their underlying dependencies change,
246
+ * preserving transparent history and reasons without deleting the knowledge.
247
+ */
248
+ declare function markStaleKnowledge(knowledgeList: Knowledge[], changedSources: string[]): {
249
+ updatedKnowledge: Knowledge[];
250
+ affectedCount: number;
251
+ };
252
+ /**
253
+ * Checks a list of knowledge units against changed sources and returns the affected items.
254
+ */
255
+ declare function checkKnowledgeListStaleness(knowledgeList: Knowledge[], changedSources: string[]): {
256
+ affectedKnowledge: Knowledge[];
257
+ updatedKnowledge: Knowledge[];
258
+ affectedCount: number;
259
+ };
260
+
261
+ /**
262
+ * Determines initial quarantine stage for a new knowledge item.
263
+ * Deterministic facts (e.g. compiler config, explicit package manifests) skip probation directly to 'active'.
264
+ * Speculative lessons, heuristics, and inferences start in 'candidate' stage.
265
+ */
266
+ declare function determineInitialStage(knowledge: Partial<Knowledge>): KnowledgeStage;
267
+ /**
268
+ * Evaluates whether a knowledge item qualifies for promotion along the quarantine ladder:
269
+ * CANDIDATE -> PROBATION -> ACTIVE
270
+ */
271
+ declare function evaluatePromotion(knowledge: Knowledge): {
272
+ promoted: boolean;
273
+ newStage: KnowledgeStage;
274
+ reason?: string;
275
+ };
276
+ /**
277
+ * Calculates deterministic knowledge value metric.
278
+ * Combines reuse frequency, evidence backing, successful task outcomes, and penalizes misleading outcomes.
279
+ * Used during compaction and knowledge budget management.
280
+ */
281
+ declare function calculateKnowledgeValue(knowledge: Knowledge): number;
282
+ /**
283
+ * Applies a task outcome record to a knowledge item:
284
+ * Updates outcome telemetry, recalculates value, and triggers promotion or demotion.
285
+ */
286
+ declare function recordOutcomeOnKnowledge(knowledge: Knowledge, outcome: OutcomeRecord): {
287
+ updatedKnowledge: Knowledge;
288
+ actionTaken?: string;
289
+ };
290
+ /**
291
+ * Enforces knowledge budget without arbitrarily deleting provenance.
292
+ * When active knowledge exceeds budget, demotes lowest-value items to probation/candidate.
293
+ */
294
+ declare function enforceKnowledgeBudget(knowledgeList: Knowledge[], budget?: KnowledgeBudgetConfig): {
295
+ modifiedList: Knowledge[];
296
+ demotedCount: number;
297
+ };
298
+
299
+ /**
300
+ * Relative cost table for evidence-gathering actions.
301
+ * Smallest action likely to resolve uncertainty is preferred.
302
+ */
303
+ declare const RELATIVE_COSTS: Record<ActionType, number>;
304
+ /**
305
+ * Core Epistemic Resolver:
306
+ * Answers: "Do I know enough to act, what do I know does not apply,
307
+ * what am I missing, and what is the cheapest next step to resolve the uncertainty?"
308
+ */
309
+ declare function resolveEpistemicQuery(options: ResolveOptions, storage: Storage, retriever?: Retriever | SearchIndex): Promise<ResolutionResult>;
310
+
311
+ export { ActionType, BilmemMetrics, ConfidenceTier, type DistilledLesson, Evidence, EvidenceGraph, EvidenceRelation, Knowledge, KnowledgeBudgetConfig, KnowledgeHistoryEntry, KnowledgeOutcomesSummary, KnowledgeStage, KnowledgeStatus, KnowledgeType, MetricsTracker, Observation, OutcomeRecord, OutcomeType, Provenance, RELATIVE_COSTS, ReconciliationAction, ReconciliationResult, ResolutionResult, ResolveOptions, Scope, type SourceDependencyIndex, type StalenessCheckResult, TaskTrajectory, type TrajectoryLearningResult, UnknownNextAction, UnknownReason, UnknownRecord, UnknownState, applyOutcomeToKnowledge, applyReconciliation, buildDependencyIndex, calculateEffectiveConfidence, calculateKnowledgeValue, checkKnowledgeListStaleness, checkKnowledgeStaleness, confidenceToTier, createEvidence, createKnowledge, createObservation, createOutcome, createUnknown, detectPolarContradiction, determineInitialStage, distillTrajectory, enforceKnowledgeBudget, evaluatePromotion, hasBeenInvestigated, hashString, learnFromTrajectory, markStaleKnowledge, normalizeSourceKey, processUserCorrection, reconcileKnowledge, recordOutcomeOnKnowledge, resolveEpistemicQuery, tierToConfidence, updateUnknown };